DEV Community

Discussion on: Avoid getters and setters whenever possible

Collapse
 
magmax profile image
Miguel Ángel García

I see you had two different problems here: The important one, you found a getter returning a pointer, what means you have the control over the content. Aditionally, you put the blame on the getters and setters.

The feature I hate most about Java are equals, getters and setters. They are harder to read (car.setEngine(engine) against car.engine=engine) and harder to write, even with IDEs help, because I need to be generating them and maintaining them if I decide to change the variable name.

They require more code, so when I open the class I have to read those methods just to be sure they are not doing anything more than an assignment. This is time.

And all of this, as you said, to override one in a million.

I found a library, lombok (projectlombok.org/features/GetterS...), that helps you to avoid the implementations with annotations. It is true that it still require to use .getFoo and .setFoo, but I avoid generating them from the IDE and maintain them.

Anyways, I miss a feature in Java like Python's properties, that allow you to override just that method in a million:

class Foo:
    def __int__(self):
        bar = None    # normal public var
        _bazz = None  # private var to be used as property

    def getBazz(self):
        return _bazz

    def setBazz(self, value):
        self._bazz = 2 * value

    bazz = property(getBazz, setBazz)  # property declaration

foo = Foo()
foo.bar = 5
foo.bazz = 10
print(foo.bar)
print(foo.bazz)

So, you can change any public variable to a property just when you require to override that method.