in object oriented programming oop design pattern programming solid ~ read.

Lixkov Substitution Principle - How To Solve It

In this post we are going to talk about how to the code that violates Lixkov Substitution Principle.

What is Lixkov Substitution Principle?

There are tons of definitions explaining what Lixkov Substitution Principle is. Here I am offering my own explanation which I think is the most stupid - If you have class A that extends from class B and yet A not fully taking the advantages of all the methods defined within class B, then it is a violation of Lixkov Substitution Principle.

Bad Code

Ok let's have a look at the code that violates the principle. We are going to use Java here since it is better suitable for the example presented here.

package com.oop;  
import java.util.*;

class Stack<T> extends ArrayList<T> {  
  private int stackPointer = 0;

  public void push(T item) {
    add(stackPointer++, item);
  }

  public T pop() {
    return remove(--stackPointer);
  }

  public static void main(String[] args) {
    Stack<String> myStack = new Stack<String>();

    myStack.push('1');
    myStack.clear();
    String s = myStack.pop();
  }
}

(Bad Code)

Here as you can see that we define a Stack class and it extends from ArrayList class. But remember that ArrayList class has a lot of its own methods like clear() which is not something you want Stack to have. So it violates the principle since by extending from ArrayList, it introduces something that Stack doesn't want.

Good Code

Let's have a look at the following modified version of it.

package com.oop;  
import java.util.*;

class Stack<T> {  
  ArrayList<T> contents = new ArrayList<T>();
  private int stackPointer = 0;

  public void push(T item) {
    contents.add(stackPointer++, item);
  }

  public T pop() {
    return contents.remove(--stackPointer);
  }

  public static void main(String[] args) {
    Stack<String> myStack = new Stack<String>();
    myStack.push('1');
    // myStack.clear(); this method is gone now :)
    String s = myStack.pop();
  }
}

(Good Code)

Here we replace extends to be contents in order to change the relationship between Stack and ArrayList from a extended relationship to a contain relationship.

End

Hope you guys have learnt something from this blog and if you have any opinions or ideas please leave a comment below. Thanks!

comments powered by Disqus