If you were to do a search, you'll find several forums/threads that are divided when it comes to this topic. Some say getters/setters are evil and should be avoided, that the object should perform the calculation/behavior, and give you the result. Some developers
use getters/setters, but with guidelines usually along the lines of:
Bad OO design: public fields.
Sort of bad OO design : when getters and setters are used, even when
not required
Great OO design : used only where they're really required - and that to expose the behaviour of your class instead of a tool to manipulate the data.
orHaving getters and setters does not in itself break encapsulation. What does break encapsulation is having a getter and a setter for every data member (every field, in java lingo). That is one step away from making all data members public.
BUT...what if you do need a getter for every field?
Suppose I had an Author class for a Bookstore or Library program(Java), so it will like something like this:
public class Author {
private int authorID;
private String authorFirstname;
private String authorLastname;
//Constructor left out to keep code readable.
public int getAuthorID(){
return this.authorID;
}
public String getauthorFirstname(){
this.authorFirstname;
}
public String getauthorLastname(){
this.authorLastname;
}
}
Now I can display useful information by overriding the toString() method, but with this approach I can also implement a method to sort by lastname, and then display the ID, first and last name. My point is without getters/setters, how would I display the information in a GUI? How would I sort by lastname, and display the data? Getters make it more flexible, because this class could also be used in a web project, and the data being displayed on a webpage rather than a GUI.
Is it bad practice when you have to expose all the fields with getters? Should I be re-thinking my design? If so, how?