Reputation: 129
Does Liskov substitution say that refference do the other class must be in a base class not in some derived class? So inheritance and properties in case below is not right ?
abstract Location // place in the facility
{
public string Name;
}
Warehouse:Location
{
public int Capacity;
Public TypeOfProduct Product; ///--- this should be at base ? so in this case inheritance from Location is not good idea/real?
}
Upvotes: 0
Views: 455
Reputation: 36629
Does Liskov substitution principle say that reference do the other class must be in a base class not in some derived class?
LSP says nothing about references. It only requires that the declared interface has to be fulfilled by all derived classes. Note that this not only mean the things the compiler will check, but also the behavior.
Your example does not really demonstrate anything about LSP, since the two classes just has some fields, there is no real overriding or any behavior. Also note that a warehouse
probably not a location, it most likely has a location.
So lets create a very simple interface with some different kinds of implementation
public interface ILocation{
public string Name {get;}
}
public A: ILocation{
public string Name => "Hardcoded Name"; // Fine
}
public B: ILocation{
public string Name => name; // Also fine
private string name;
public ReferencedLocation(string name) => this.name = name;
}
public C: ILocation{
public string Name => throw new NotImplementedException(); // Not fine!
}
public D: ILocation{
public string Name => null; // Maybe fine?
}
Classes A and B both have names. If I got a ILocation
object I would not know, or care, what the name is, or where it came from. I should only care I actually got a name.
Class C is most likely a LSP violation. I expected a name but got an exception. This could easily result in bugs.
Class D return a null value. But there is nothing that tells if nulls are allowed or not. In my code I would disallow nulls unless otherwise specified, but you may take a different approach. The important thing is that everyone using your code agrees on what the expected behavior should be. If there is any risk for mistakes or confusion it is a good idea to specify the behavior of the interface with comments.
The overall goal of LSP is swap out the implementation and still ensure everything works as it should. A typical example would be something like data storage. You may have one implementation storing the data in a database for scalability and performance reasons. One implementation storing data to a file, for simpler installation. And one implementation storing data in memory, to make things easier to test. The users of the interface should not notice any difference regardless of implementation used, except possibly performance.
Upvotes: 1