Jon Skeet brought up this issue once in his videos (though didn't provide with an answer).
Let's say we have a Class named Person and the Person class has Name property
Then we have another class, Spy. Of course a Spy is a Person so we will derive from the Person class.
public class Person
{
public string Name { get; set; }
}
public class Spy : Person
{
}
We don't want people to know the Spy's name so we'd want this to give a compilation error:
static void ReportSpy(Spy spy) {
string name = spy.Name;
}
or either:
static void ReportSpy(Spy spy)
{
Person spyAsPerson = spy;
string name = spyAsPerson.Name;
}
How could we prevent this kind of things from happening?
Make the Name
property virtual
in the base Person
class. In derived Spy
class, override the property and throw Exception
in getter.
public class Person
{
public virtual string Name { get; set; }
}
public class Spy : Person
{
public override string Name
{
get
{
throw new Exception("You never ask for a spy's name!");
}
set
{
base.Name = value;
}
}
}
But, rather than throwing exception, I'd suggest something like
get
{
return "**********";
}
Because, it breaks LSP (mentioned in another answer). What that means here (just an example) is, I can always do like
Person x = new Spy();
and pass it to some other method, which might be like
void RegisterForNextBallGame(Person p)
{
playerList.Add(p.Name);
}
This method being unaware of the some spy roaming around the stadium, crashes while doing a simple honest duty!
Edit
Just to make it clear, this name=**********
is still not a right solution. It will just save from the exceptions! Later, one might find lot of Persons walking down the code with name ********** which will cause later surprises and other issues.
A better solution would be a better design. Check Nathan's answer to get some hint.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With