L of SOLID (3/5)

Posted by Daniel Vela on February 28, 2018

This is the third of five posts talking about the SOLID principles. This principles are a great guide to write good source code. Each post will talk about one of the principles:

Liskov substitution principle

Any subtype of a class can be replaced with other subtype of the same class without affecting the correctnes of the software.

Sample

One sample could be a way to saparate the database from the rest of the app. Having a good sql interface, if the code works for a particular implementartion (like SQLite), also can work with the implementation for other (like MySQL). The way to do this is to create a base interface that has no method or property directly dependant of an specific implementation.

class DatabaseInterface {
  QueryResult* selectQuery(QueryParams* params);
};

class SQLiteInterface: DatabaseInterface {
  QueryResult* selectQuery(QueryParams* params);
};

class MySQLInterface: DatabaseInterface {
  QueryResult* selectQuery(QueryParams* params);
};

class MSSQLServerInterface: DatabaseInterface {
  QueryResult* selectQuery(QueryParams* params);
};

It’s tempting to use specific functionality of a concrete implementation, because it’s special. But doing so makes the software less reusable.