I was reading this MSDN article about the usage of properties and methods in .NET. It points out why and when to use properties or methods.
Properties are meant to be used like fields, meaning that properties should not be computationally complex or produce side effects.
Otherwise one should use methods.
I was asking myself how you could express this difference in Java.
What is your opinion?
I was asking myself how you could express this difference in Java.
Just don't use the get prefix on the method, as it normally implies that the method will be cheap (as getters usually only access fields, delegate to other getters, or perform fairly simple calculations based on other getters). For example, if a class has this interface:
class Blob {
long getLength() { ... }
ByteBuffer getBytes() { ... }
Sha1Checksum getChecksum() { ... }
}
... it would seem that getting the length, contents, and checksum from the Blob are equally costly. If we did like this, instead:
interface Blob {
long getLength() { ... }
ByteBuffer getBytes() { ... }
Sha1Checksum calculateChecksum() { ... }
}
... it becomes clear(er) that we can expect calculateChecksum() to be more expensive than the other operations, as its name says it's going to do more than just get something.
To a certain degree, the complexity is an implementation issue that shouldn't be seen in the interface (maybe I decide to calculate the checksum eagerly when the Blob is constructed?), but there are occasions where it makes sense to make a distinction.
I just don't agree with what that article says. Properties are syntactic sugar, otherwise you'd just use fields.
The point of getters/properties is encapsulation - the user does not know whether it's simply a field, something you compute every time or a random value.
This means that for me, every class in Java that is not a "Data Structure" has getters and setters for its fields (that need to be accessible).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With