If you have a class with some plain get/set properties, is there any reason to use the getters within the class methods, or should you just use the private member variables? I think there could be more of an argument over setters (validation logic?), but I’m wondering just about getters.
For example (in Java) – is there any reason to use option 2?:
public class Something { private int messageId; public int getMessageId() { return this.messageId; } public void setMessage(int messageId) { this.messageId = messageId; } public void doSomething() { // Option 1: doSomethingWithMessageId(messageId); // Option 2: doSomethingWithMessageId(getMessageId()); } }
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!