Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I hide a method so it's not called by programmers but still usable in code?

Tags:

c#

inheritance

I have a class called Ship and a class called Lifeboat

Lifeboat inherits from Ship.

Ship contains a method called Validate() which is called before save and it has an abstract method called FurtherValidate() which it calls from Validate. The reason this is in place is so when you call validate on the base it also validates the class that is inheriting. So we have

public class Ship

public bool Validate()
{
    //validate properties only found on a ship

    FurtherValidate();
}

public abstract bool FurtherValidate();

So Lifeboat has

public override bool FurtherValidate()
{
    //validate properties only found on a lifeboat
}

This means anyone implementing Ship also needs to provide their own validation for their class and it's guaranteed to be called on the save as the base ship. Validate() is called which in turns calls the inherited validate.

How can we re work this so we still force inherited classes to implement FurtherValidate() but FurtherValidate() can never be called by the programmer. Currently you can called Lifeboat.FurtherValidate() and I want to somehow prevent this.

like image 240
Robert Avatar asked Nov 29 '22 12:11

Robert


2 Answers

protected abstract bool FurtherValidate();

only Ship and Lifeboat can see it now.

EDIT: Lifeboat must be able to see it. How should it be able to override FurtherValidate when it can't even see it. I would rename it to ValidateCore, the 'Core' part (to me) implies that it should not be called without a very good reason.

I don't think it's easy to make it abstract but not visible. You need to have some faith in your lifeboat ;)

like image 41
alvin Avatar answered Dec 18 '22 09:12

alvin


Short answer is, you can't hide the derived method from the class that's deriving it. However, you can refactor your code to accomplish what you're trying to achieve:

public class Ship
{    
    public virtual bool Validate()    
    {        
        //validate properties only found on a ship
        return true;
    }
}
public class Lifeboat : Ship
{   
    public override bool Validate()   
    {       
        base.Validate();       
        // lifeboat specific code
        return true;
    }
}
like image 80
Robert S. Avatar answered Dec 18 '22 08:12

Robert S.