Liskov Substitution Principle

It would be more logical to proceed by giving an example rather than making a definition on this subject. When the definition is made, scary and meaningless things can come out.

For example, let’s say you have a sales site. While the people you sell to are sometimes normal people, sometimes they can be companies. E.g; While selling pencils to a person named John Doe, you can sell 10 pencils to a company named Pencil Store.

Here, both parties are customers for you. Both John Doe and Pencil Store can be taken under the name of customer in general terms. As a table structure; name, surname, e-mail address, phone number, tckn and tax number fields. These are the basic definitions, as the name, e-mail address and phone fields will be common to each customer. It must be defined in the main class. In duplicate classes, specific definitions should be made.

In addition, when we want to issue an invoice, let’s have a function that gives the information to be written in the tax information field to be included in the invoice. In this function, the Tax Number field of the companies should be written on the invoice, while the TR Identity Number of the individuals is taken as the basis. Let’s see with sample code:

public abstract class Customer{
    public string Name;
    public string Email;
    public string Phone;

    public abstract void InvoiceTaxInformation();
}

public class Person:Customer{
    public string Surname;
    public string IDNumber;

    // If it is the person to be invoiced, the name and identity number are written. 
    public override void InvoiceTaxInformation(){
        Console.WriteLine(Name+ " / " + IDNumber);
    }
}

public class Company:Customer{
    public string TaxNumber;

    // If it is the company to be invoiced, the name and tax number are written 
    public override void InvoiceTaxInformation(){
        Console.WriteLine(Name + " / " + TaxNumber);
    }
}

As can be seen in the example above, the function named InvoiceTaxInfo returns different values for different Company for Person. Because they are both customers.

We can do it in the main class by using if or switch-case structure, whether the customer’s tax information will be written as a ID number or tax number. However, it will not be the right solution as it will remove the benefits provided by SOLID principles such as the longevity of the project and the ability to add new features.

You may also like...