Thursday, January 05, 2017

SOLID Principles for Dummies

As an OO programmer one of the things you're meant to practise is good OO design, and the SOLID principles embody that.

If you've read the SOLID wikipedia article it's a little long winded, so here's the SOLID principles simplified and written as negative reinforcement to help curb bad practices!

S - Single Responsibility Principle

Don't have classes do many things - a class should have a single purpose, I would go so far as to say a method should also have a single purpose. For example a DatabaseService class only interacts with a database, a save method only persists a value (as opposed to a method such as validateValueAndSave)

O - Open Closed Principle

Don't write decision logic based on sub class or sub class properties in the parent class - i.e. have sub classes make the sub type specific decisions. Make sure you extend classes, don't break the original abstract classes by modifying them,

L - Liskov Substitution Principle

Don't return an incompatible type in sub classes (or anything that suggests the sub class cannot support the operation as exactly defined by the parent class). For example in a Java method don't throw not supported exceptions in sub classes, in other languages, don't return types incompatible with the base type return value. By doing this it ensures any method (or iterator etc.) that takes a subclass argument and has no specific subclass feature usage, is able to have its argument substituted for the parent class without modification.

I - Interface Segregation Principle

Don't lump all functionality into one interface and thus have implementing classes provide functionality they can't support, instead create fine grained interfaces.

D - Dependency Inversion Principle

Don't use concrete types if there's an interface available for dependencies (in general coding to an interface is best practice anywhere). For example use List myDataList = createList(), not ArrayList myDataList = createList(), where List is an interface on ArrayList. This allows easy substitution of the dependency implementation later to another list type without breaking the code receiving the dependency. In short, a high level class should not depend on a low level class.

No comments: