Adding Getters and Setters8:32 with Alena Holligan
What about the Getters and Setters for the rest of the properties? Do you have to add Getters and Setters for ALL of them? What if you don’t care about doing anything with the property before it gets set. Can we just leave those public?
Why Getters and Setters
Some of these are concepts we wont be covering in this course, but here are a few ides:
- Controlling the of behavior associated with getting or setting the property - this allows additional functionality (like validation) to be added more easily later.
- Hiding the internal representation of the property while exposing a property using an alternative representation.
- Allowing the getter/setter to be passed around as lambda expressions rather than values.
- Getters and setters can allow different access levels - for example the get may be public, but the set could be protected.
- Insulating your public interface from change - allowing the public interface to remain constant while the implementation changes without affecting existing consumers.
- Providing a debugging interception point for when a property changes at runtime.
- Improved interoperability with libraries that are designed to operate against property getter/setters - Mocking, Serialization, etc.
- Allowing inheritors to change the semantics of how the property behaves and is exposed by overriding the getter/setter methods.
You need to sign up for Treehouse in order to download course files.Sign up