0

I have 3 classes in Data Access project, and all 3 classes have many data access methods ( GetSomeList, InsertSomeData, UpdateSomeData …). All 3 classes have several methods that are same. I don’t want to write same methods 3 times. What is best approach here?

One possible solution would be to define one common class that will be inherited. Is this good approach?

Example:

public abstract class CommonDataLayer
{
    public int CommonMethod()
    {
        Random random = new Random();
        int randomNumber = random.Next(0, 100);
        return randomNumber;
    }
}

public class FirstDataLayer : CommonDataLayer
{
    public int FirstMethod()
    {
        return CommonMethod() + 1;
    }
}

public class SecondDataLayer : CommonDataLayer
{
    public int SecondMethod()
    {
        return CommonMethod() + 2;
    }
}

public class ThirtDataLayer : CommonDataLayer
{
    public int ThirtMethod()
    {
        return CommonMethod() +3;
    }
}
Raskolnikov
  • 3,791
  • 9
  • 43
  • 88
  • possible duplicate of [C# - Object Composition - Removing Boilerplate Code](http://stackoverflow.com/questions/15452377/c-sharp-object-composition-removing-boilerplate-code) – Philip Pittle Aug 27 '14 at 07:21

2 Answers2

2

Create a superclass for all of your classes and the common method implementation to your super class.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
0

A good approach is to:

One possible solution would be to define one common class that will be inherited. Is this good approach?

Yes

But in your code example, its not necessary to have FirstMethod, SecondMethod and ThirdMethod. You can invoke the CommonMethod directly from the derived class. You can override the CommonMethod if the derived method requires specific functionality.

public class FirstDataLayer : CommonDataLayer
{
    // This class uses CommonMethod from the Base Class
}


public class SecondDataLayer : CommonDataLayer
{
    @Override
    public int CommonMethod(){

    // EDIT code

          // Class specific implementation 
          return base.CommonMethod() +1;

    }
}

public class ThirdDataLayer : CommonDataLayer
{

    public int ThirdMethod(){

        // Class specific implementation 
        return base.CommonMethod() +2;

    }

 }     
CocoNess
  • 4,213
  • 4
  • 26
  • 43