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! While you're at it, check out some resources Treehouse students have shared here.

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

Java

Why is it bad practice to have the user directly edit the modifier?

At first we were modifying the public mCharacterName in the Pez example. When we changed it to private it required we create a method and constructor. This to me seems like excess coding. Why is it bad practice to change the modifier when in reality we are changing it, just not directly?

2 Answers

Craig Dennis
STAFF
Craig Dennis
Treehouse Teacher

By setting it private and only setting it in the constructor, after it's been initialized, no one externally can modify it. This is just like real life. Can't change Pez character heads after they have been created. This is what we want to convey to users of the class. They will not be able to change the character after it is created.

This is a very light walk into the world of encapsulation, an Object Oriented Programming principle. You should expose really only what you want to have exposed.

That make more sense?

Awesome! So like you said it's more to convey restrictions to the user than anything. That makes a lot of sense moving forward. Thanks Craig!

Using a getter is usually paired with a setter, which allows you to control the input beyond what the type declaration demands. A user could try to set the number of Pez to be more than is acceptable, or overcharge the GoKart battery, or set these values to negative numbers. These could all be fatal flaws.