Search code examples
c#oopcode-organization

Where would you place a method that has the same functionality but is inside 2 subclasses and has different parameters?


I am trying to restructure an application, and right now there are two classes which are subclasses of another class.

Both of these classes have a method. This method essentially does the same thing (get user information) but from different data sources and parses them differently (say one uses the Facebook API and the other a database). They also take in different parameters.

Does it structurally make sense to leave both methods in the subclasses with the same method name? Or is there a cleaner way of organizing the methods within the subclasses?


Solution

  • This is a perfect place to apply the strategy pattern.

    Rather than having a different GetUserInformationMethod call for each class, create a new class (or a delegate type) that exists just to get user information. Have a UserInformationGetter attribute which is an instance of your user information fetching class/delgate in the base class, and have the base class's GetUserInformation method invoke the delegate/class to get user information.

    The challenge of different parameters could be handled in a number of different ways, which depends on the parameters. If the parameters are related to the details of implementation (e.g. database connection strings), and not variant across users then you should tie that information to the UserInformationGetter class.

    If the information is dependent on the user, there are a number of strategies. I would suggest you create a type that encapsulates all the information about the user that is used to fetch user data in either case. Then you can pass this object to the methods, rather than parameters that vary accoridng to the method of data access.

    This way, you can vary the user information fetching strategy of your base classes independently of anything else which might vary between the classes. Additionally, you can vary the way you get user information at runtime, allowing your program to adapt to changing requirements easily.