David_DD
David_DD

Reputation: 585

Does calling a method of the different class using switch violate Single Responsibility Principle?

I have two classes (A and B) and a Model (T) with some properties. In A class, There is a method with the passing model(T). We have to check a condition to check the name using a switch case, where the name matches the case then we have to call a public method of the B Class.

Public class A{
private IB _b;

public void methods(T t){
    switch(t.name){
        case Q.A
        _b.testmethod1(t);
        case Q.B
        _b.testmethod2(t);
        case Q.C
        _b.testmethod3(t);
        case Q.D
        _b.testmethod4(t);
    }}

I have tried the if condition instead of if but the meaning is the same. Does this code violate Single Responsibility Principle or the generalized code?

Does this code violate Single Responsibility Principle or the generalized code? if yes then let me know how to manage with switch case.

Upvotes: 0

Views: 42

Answers (1)

Pap-lapadon
Pap-lapadon

Reputation: 1

IMHO it just ignores the existence of SRP. It does not go against it per se, because it does not handle clear responsibilities. Your approach is the real problem. Generally, switches like this should be a code smell for you. I don't know what you exactly wanted to do here, but you would have to utilise polymorphism or implement a service class which should be responsible for handling these choices. By the way, I recommend not to use a switch here when you don't have a fallback case.

To summarise my solution:
Use polymorphism or implement a service class. Do not use a switch.

Upvotes: 0

Related Questions