Language (言語)

Developer perspective: Is ‘Private beats public’ applicable in software design?

Published:
Updated: 30 Sep 2022
software design

I remember hearing “Protect your members!” being taught in the very first semester of my CS curriculum.

As easy as it sounds, it takes experience to understand what it actually means. The majority of code I see, whether small, medium, or large codebase, is clearly in violation of this principle.

How often do you get to see code like this?

public class Employee 
{ 
    public string Name { get; set; } 
    public string Age { get; set; } 
    public double Salary { get; set; } 
    public void CalculateSalary() 
    { 
        //Salary = YourCalculationLogic... 
    } 
} 

 

I see it all the time. According to the contract above, you can give salary to an employee, but so does anybody else outside your class. It looks rather trivial in the beginning, but when your codebase grows larger, you will have to embrace new complexity challenges. If your Salary member needs to maintain domain-related invariant assertions, you will need to apply them over and over again outside of your Employee class.

You will start to decorate your code with repetitive null-checks, validation attributes, and other utilities, which will make your code less readable and more complex to maintain. Throwing a domain exception may not always solve your problem because, by the time it is thrown, it may be already too late to notify the most appropriate handler of your exception.

Often we solve complexities by introducing more complexity and by throwing more tools and technologies into it. I still believe that a lot of this complexity would not be necessary if we followed the good old OOP practices from start.

Written by: Alexander Yaremchuk, Software Developer

Discover more developer-oriented posts