InterviewSolution
Saved Bookmarks
| 1. |
Solve : Opinion on Getters/Setters? |
|
Answer» 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. or Quote Having 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: Code: [Select]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? There's nothing wrong with exposing EVERYTHING using getters and setters, what they MEAN by "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." is that you shouldn't just create them for every variable as a matter of course. You should only create a getter or setter if you actually have a use for it. |
|