Reputation: 3999
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;
}
}
Upvotes: 0
Views: 192
Reputation: 4222
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;
}
}
Upvotes: 0
Reputation: 68715
Create a superclass for all of your classes and the common method implementation to your super class.
Upvotes: 2