Ratish Nair
Ratish Nair

Reputation: 21

Objective of Get Set

Is the only objective of get set is to access a private/protected variable, without breaking concept of encapsulation? Because as per my findings I cannot see any other use of get set property.

Upvotes: 2

Views: 99

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1499870

No - that's usually what it does, but accessors can perform whatever calculation you want. Fundamentally, a property is meant to provide access to logical state of a value - but that logical state doesn't have to translate to a single field of the same type in the implementation.

As an example, my Noda Time project has a LocalDate type with properties of Year, Month and Day. In v1, the backing field for LocalDate was a LocalDateTime which itself had a backing field representing the number of ticks since the Unix epoch, and the year/month/day was calculated from that.

In v2, there's an entirely different implementation, with a backing field packing the year/month/day values into a single long field but with much less calculation required.

Callers won't need to know there's been any change, but in neither version was the getter just returning the value of the backing field. The implementation detail was hidden from them.

Properties with both getters and setters are more likely to be backed by a simple field - but there, the setter may well perform validation checks, and the getter may be lazy too.

Upvotes: 11

Peter Carnesciali
Peter Carnesciali

Reputation: 431

Another use is you can have custom logic. For instance, when setting a variable, you can check to make sure it is in bounds.

For example, if you have a class Fraction, with numerator and denominator, when setting the denominator, you would want to check that it is not zero.

Upvotes: 1

Related Questions