Hacker News new | ask | show | jobs
by vaskebjorn 3156 days ago
In my experience writing getters and setters has been boilerplate 99% of the time.

But I still write them because situations arise where you do need to change the nature of that property, sometimes dynamically, and then it's suddenly worth it. You can, for instance, change a getter and none of the class's clients need to know or care about the change.

Though I haven't used Groovy much I like their approach to this: "Although the compiler creates the usual getter/setter logic, if you wish to do anything additional or different in those getters/setters, you’re free to still provide them, and the compiler will use your logic, instead of the default generated one."

3 comments

Why don't you just use plain fields, and if you need to change it later, delete the field and go fix all compile errors? That's an easy way to find all usages.

Or are you not talking about a statically-typed language which would find the errors when you temporarily delete a field?

You don't always control the code that uses it. You'll have a lot of angry customers if you break all their builds.
well, hopefully they aren't having the library update underneath them without warning. :P
> Though I haven't used Groovy much I like their approach to this

I like this a lot about Groovy as well. Groovy also provides annotations that relieve a lot of the other points too, such as @Immutable [1], @EqualsAndHashcode [2] and @ToString. It even supports meta-annotations which let you alias several annotations together as one so you can make a complete "data class" with a single annotation.

[1] http://docs.groovy-lang.org/latest/html/gapi/groovy/transfor...

[2] http://docs.groovy-lang.org/latest/html/gapi/groovy/transfor...

You might want to look into Project Lombok. It does exactly that, and it works well.
Five years Ago I started to use it. Never touched a project without again. Today I am really interested in kotlin, which provides many of these features.