Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Subclass with same method

I have a superclass with two subclasses. The two subclasses both have a method with checks whether a chapter has content. For subclass 1 this method is HasContent(int chapterID) and for subclass 2 this is HasContent(int chapterID, int institution). As you can see subclass 2 has an extra parameter. The purpose of both methods is the same.

I was thinking to put the method HasContent in the superclass. Do you think i need to do this? If so, how should i implement this? Or is it more wisely to put both methods in their own subclass?

EDIT:

The body of HasDocuments looks like this: Subclass1:

Database DB = new Database();
int res = DB.ExecuteSpRetVal(chapterID, mInstitutionID);

if (res > 0)
    return true;
else
    return false;

Subclass2:

Database DB = new Database();
int res = DB.ExecuteSpRetVal(chapterID);

if (res > 0)
    return true;
else
    return false;
like image 509
Martijn Avatar asked Sep 20 '26 11:09

Martijn


1 Answers

Edit: Updated according to the question update.

Since you are clearly having almost the same logic in both methods, I'd refactor it like this:

abstract class SuperClass
{
    protected bool HasContentImpl(int chapterID, int institution)
    {
        Database db = new Database();
        int result;

        if (institution >= 0) // assuming negative numbers are out of range
            result = db.ExecuteSpRetVal(chapterID, institution);
        else
            result = db.ExecuteSpRetVal(chapterID);

        return result > 0;
    }
}

class SubClass1 : SuperClass
{
    public bool HasContent(int chapterID)
    {
        return base.HasContentImpl(chapterID, -1);
    }
}

class SubClass2 : SuperClass
{
    public bool HasContent(int chapterID, int institution)
    {
        return base.HasContentImpl(chapterID, institution);
    }
}
like image 108
Hosam Aly Avatar answered Sep 22 '26 00:09

Hosam Aly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!