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

iOS

Logic of "Get" and "Set"

I'm still not 100% clear about when one would ever use 'get' and 'set methods. What's the benefit?

The 'set' method just seems to be the reverse of the 'get' method. Is this because the 'get' method modified the value in the first place? Please clarify what the purpose of the 'get' and 'set' are, the logic behind it, and some benefits for using them?

Thank you.

1 Answer

I come from a Java background, but I hope this will help you. Think about the thing you are accessing as an object. Perhaps we have a car class. The car class (object) has properties, such as topSpeed, gasMileage, color, etc. Getters and setters are the ways in which we are allowed to access those properties.

Now we have an instance of the class, a specific car, a dodgeChallenger.

If you want to check the value car's property, you have to access it. That's where getters come in. Through the getters, we get access to view (read) the properties.

Something like dodgeChallenger.getColor(), or dodgeChallenger.topSpeed()

In order to change (write to) those properties, we use setters.

dodgeChallenger.setColor("Plum Crazy") would be used to replace the current value with the new value "Plum Crazy".

Otherwise, we have no way to tell our object which property we are trying to work with, or what to do with that property.

Gets look at properties, and Sets change them.