Getters are always nice. If you forgot what brand you set at creation, it would be nice to have a way of getting it out of that object. What if you got that object from somewhere else? Figuring out the brand using a getter is easy that way. But getters should only be available on directly exposed values. No need to create a getter for internalVersionString
if it should not be publically known. But having a getter for colour
would be nice... after all, you can see the colour by looking at the laptop (which is a bad analogy for OOP, but it's fitting here IMHO).
Regarding setters... if you have only one attribute, there is not much of a (visible) difference indeed. But what lies beyond that is a deeper subject... mutability. Of course, using a constructor has a greater overhead than simply setting the attribute (getting memory for a whole new object vs. getting memory for a string).
A nice example of not using setters is the String
class in Java. A Java String
is immutable; once created, it cannot be changed whatsoever. If you want to replace characters or remove some parts, what you get is not a changed String, but instead a brand new String with the desired changes made. But what if you had a class called TextDocument
, that contained a whole file's worth of data? Having no ability to replace parts of that one without creating a whole new TextDocument
could be hindering.
Having setters automatically means your object is mutable; that means, your object is not fixed upon creation, but can be changed later on. An ArrayList
would be a nice example here. You'd certainly not want to allocate a whole new list only to change a single value.
The difference between mutable and immutable are not as clear when using simple cases like your laptop
class. Using immutable classes comes in handy when doing parallel work, using mutable classes comes in handy when handling big objects with a large amount of memory needed to allocate.
There's no one-fits-all solution for that problem. But for exposed attributes which should be directly changeable, a setter would be convenient instead of having to construct a whole new object. Imagine a class with multiple attributes... taking your laptop
for example, having a brand, a size, a colour and whatnot. If you just want to change the colour, having to construct a new laptop and copying over all the other attributes would be tedious, wouldn't it? A setter would make life easier for you in that case. Just call yourLaptop.setBrand("Dill");
and continue using that laptop. No reason to spend 500 bucks (or rather... bytes) for another one.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…