Search code examples
c#oopmethodssolid-principles

Design pattern for class with more than one methods


I am building an application that is calling various APIs, and as a newbie to SOLID principles and how a class should have single responsibility i am looking to design my class with SOLID in mind,

Internal class API_Caller
{
  public static getInfor1()
  {
    // do something in here
  }
  public static getInfo2()
  {// do something }
  public static getInfo3()
  {// do something}

}

if my class have more than one method is it following SOLID and,

other way is that is if all the methods are private so i expose as little as possible (When should methods be made private?) but is this good design pattern or should i just split the methods in to different classes ??

internal class API_Caller
{
    public Static CALL_APIs (API_Name)
    {
        switch (API_Name)
        {
            case "getinfo1":
              getInfor1();
              break;
            case "getinfo2":
              getinfo2();
              break;
        }
    }
    private static getInfor1(){// do something}
    private static getInfo2(){// do something}
    private static getInfo3(){// do something}
}

Solution

  • Are the three methods related ? Are they alternatives for each other ? Do they vary independently ?

    If each method represent a different way of achieving the same goal and might be used independently, then use can split them. Let's say you were getting weather forecast from Google or Amazon, you could do something like this:

    interface IWeatherProvider 
    { 
       //SomeReturnType Get();
    }
    
    class AmazonWeatherProvider : IWeatherProvider  
    { 
        // Implementation
    }
    
    class GoogleWeatherProvider : IWeatherProvider  
    { 
        // Implementation
    }
    

    In the example above, each class represent a different way to achieve the same responsibility.

    But if you have 2 methods : GetWeeklyForecast and GetDailyForecast . You can have these 2 in the same class (or interface). That doesn't usually violate SRP, they both go under the same responsibility (Getting Weather Forecast)

    You can also split into different classes in case the methods are completely unrelated and might change for different reasons or used by different clients.


    Be aware of how you're thinking about public / private methods. You can expose as many public methods as you need (These are the contract that you share with whomever is using the API). If you change the parameter types of a private method, you don't have a breaking change. But if you change the parameter types of a public method, you have a breaking change! All your clients now need to change their code !