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.

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow