Folks,

            Barbara Jane Liskov was the first women american computer scientst who earned a PHd in computer science. She is the one who also came up with Liskov substituion principle and it is the 'L' in SOLID. She coined this term in 1987. First let's see what it means in her own words. "If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when o1 is substituted for o2 then S is a subtype of T."

:)

In other words, if you have a sub type, it must be at any point of time substitutable for their base types. That's it.

Example -

Let's assume that you have a base class called Order and subtypes as EuropeOrder and AsianOrder. Let's further assume that orders raised by Asian distributors cannot be saved, because of some business rules. Let's see some quick code and when you try to compile this , it will break because of the business rule that we just mentioned. This is a demonstration of failure of LSP as we were not able to substitute (all the time) the base class with a sub type object.

public class Order {
public void saveOrder() {}

public void submitOrder() {}

}

public class EuropeOrder extends Order{

public void saveOrder() {
System.out.println("Saving Orders Raised by European Distributors . . . .");
}

public void submitOrder() {}

}

public class AsianOrder extends Order {
public void saveOrder() {
throw new UnsupportedOperationException();
}

public void submitOrder() {
}}

import java.util.ArrayList;
import java.util.List;

class Main {
public static void main(String args[]) {
List<Order> orderList = new ArrayList<Order>();
orderList.add(new Order());
orderList.add(new EuropeOrder());
orderList.add(new AsianOrder());
saveOrderPrint(orderList);
}

static void saveOrderPrint(List<Order> orderList) {
for (Order o : orderList) {
o.saveOrder();
}}}


So the key point to remember here is that we don't have to map all the facts that are found in the outside world to the code level also. An order raised by a distributor in Asia can be different from an order raised by a European distributor and hence the reason we could not save them(but we could do something else with them). Now what do we do ? We can go ahead and change some code here and there, put some if statements and make this code work, but that would be a violation of Open Close Principle. It is worth mentioning here that if we take care of LSP the OCP rule can be kept intact !

cheers !

rohit

Views: 68

Tags: Base, Class, Close, Liskov, Object, Open, Oriented, Principle, Programming, Sub, More…Substitution, Type

Comments are closed for this blog post

© 2013   Created by Rohit Pant.

Badges  |  Report an Issue  |  Terms of Service