ThePorcius
ThePorcius

Reputation: 123

Do classes that set, get and calculate data follow the S in SOLID?

Supposing I live in a country where every car brand has a different tax rate, and I have a base class called Car:

public class Car{
    public string CarType { get; set;}
    public int Year {get; set;}
    public abstract double calculateSalesTax();
}

Would it be OK to add an abstract method to calculate the sales tax? Or does that already breaks the SOLID principle? A usual guideline for S in SOLID is "If you have to use the word AND when describing your class, it's most likely breaking the principle". Here, the implementation of a method to calculate sales tax seems to be requiring that AND. This class sets the attributes of the car AND calculates its sales tax.

So If I implement the derived class

public class Volkswagen : Car{
    
    public override double calculateSalesTax(){
         //Something to calculate a VWs tax
    }
}

is it already breaking the S in SOLID?

Upvotes: 1

Views: 43

Answers (2)

jaco0646
jaco0646

Reputation: 17066

There is a more fundamental principle violated by exposing both data and logic from the same module: the definition of an object.

Paraphrasing Martin, an object hides its data and exposes its behaviors. A data structure exposes data and has no behaviors. What you have by exposing both, he refers to as a hybrid, which is the worst of both worlds.

Satisfying the SRP isn't a concern yet, because this isn't an object, by the definition the SRP refers to.

Upvotes: 0

Mark Seemann
Mark Seemann

Reputation: 233150

The SOLID principles are good heuristics, but they can be a little fuzzy. They serve as food for thought, not absolute rules.

Robert C. Martin describes the Single Responsibility Principle (SRP) as:

A class should have only one reason to change

The SRP and the other SOLID principles give you a framework for thinking ahead, but you can't predict the future. Unplanned reasons for change may occur in the future.

Still, thinking ahead, could there be more than one reason that you'd have to change those classes in the future?

It's conceivable that you might need to change the calculateSalesTax method in the future, but will you ever need to change the attributes of the class?

If not, then it doesn't violate the SRP. On the other hand, if you expect to have to change the attributes of the class in the future, as well as the calculateSalesTax method, then the SRP would be broken. If that's the case, you should consider alternative designs.

Upvotes: 1

Related Questions