Using getters within class methods

Java programmers in general tend to be very consistent about using getter methods. I program multiple languages and I'm not that consistent about it ;)

I'd say as long as you don't make a getter it's ok to use the raw variable - for private variables. When you make a getter, you should be using only that. When I make a getter for a private field, my IDE suggests that it replace raw field accesses for me automatically when I introduce a getter. Switching to using a getter is only a few keystrokes away (and without any chance of introducing errors), so I tend to delay it until I need it.

Of course, if you want to stuff like getter-injection, some types of proxying and subclassing framworks like hibernate, you have to user getters!


With getters you wont accidentally modify the variables :) Also, if you use both getters and the "raw" variable, your code can get confused.

Also, if you use inheritance and redefined the getter methods in child classes, getter-using methods will work properly, whereas those using the raw variables would not.


If you use the getter method everywhere - and in the future perform a code-search on all calls of getMessageId() you will find all of them, whereas if you had used the private ones, you may miss some.

Also if there's ever logic to be introduced in the setter method, you wont have to worry about changing more than 1 location for it.

Tags:

Getter