Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Aaron Kaye
10,948 PointsJava variables vs getter methods (best practice)
My question came from the Java Data Structures class (Overriding an inherited method) although it is a generic question. I know both of the following would work, but I am wondering which would be 'Best Practice' (assuming the appropriate variables and methods already existed).
@Override
public String toString() {
return "BlogPost: " + getTitle() + " by " + getAuthor();
}
So the above method uses the objects getter methods to return the instance variables vs:
@Override
public String toString() {
return "BlogPost: " + mTitle + " by " + mAuthor;
}
As I said, I know both would work with the appropriate variables and methods in place but I am wondering if one is considered 'Best Practice'
1 Answer

Kyle Salisbury
Full Stack JavaScript Techdegree Student 16,363 PointsI've always been taught to avoid using member variables when possible. Not sure why though. As you said, both work.
Aaron Kaye
10,948 PointsAaron Kaye
10,948 PointsThanks Kyle, I really appreciate your feedback!