J. Kevin Robbins wrote:
I see and understand your example, but I don't understand the advantage of this technique. Why would you do it this way? What are you gaining?
You may encounter scenarios where some properties can be derived from existing variables or from expressions. Take this example of a Person class:
This class has a birthDate property implemented as a variable named birthDate, but it also has an ageInYears property that is derived from a calculation involving the current date and the birthDate. Derived properties like this are usually read-only.
J. Kevin Robbins wrote:I see and understand your example, but I don't understand the advantage of this technique. Why would you do it this way? What are you gaining?
Let's look at Marshall's example and say you didn't have the ageInYears property.
Now, lets suppose a class, ClassA, needs to calculate the person's age:
Now, lets suppose another class, ClassB, also needs to perform the same calculation:
Now, lets suppose a multitude of other classes need to perform the same calculation. It is at this point alarm bells should be ringing about the violation of the DRY principle.
Sure, you could refactor the logic to calculate the person's age into some utility class that is invoked by all classes that need it.
However, such utility classes are not very OO. One of the fundamentals of OO is encapsulation which is to group (or encapsulate) data and its behaviour together. With this in mind, the data is the birth date of a person and the behaviour is the age in years calculation which should lead a developer to put these together in the same class.