SOLID dumbed down

Posted on January 15, 2021. Filed under: Uncategorized | Tags: , , , |

Extracted from This xkcd comic speaks on how some things are deceptively hard to program. What are some other examples of this? posted to r/learnprogramming

  • Single-responsibility principle – A class should only have a single responsibility, that is, only changes to one part of the software’s specification should be able to affect the specification of the class.

    A class should have a narrow purpose, i.e if you have a restaurant, your waiter class should not have functions for cooking food, that belongs to the chef. If a class has unintended or logically confusing functionality, you most likely misunderstood the system you’re modelling.

  • Open–closed principle – “Software entities … should be open for extension, but closed for modification.”

    The internals of classes should never be exposed and extensions of classes (I want method X to also do Y) should be handled through inheritance. this is to this day debatable, even if the internals of classes definitely shouldn’t be available to tinker with. These rules were written many years ago, and programming has somewhat moved on.

  • Liskov substitution principle – “Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.” See also design by contract.

    If you have a function that takes a dog that inherits from animal, that function should also take a cat. This one is a bit trickier and more devious than it looks from the start because what happens if you have a function that is specifically meant for cats? The answer is that the function you made probably don’t have to be for cats only.

  • Interface segregation principle – “Many client-specific interfaces are better than one general-purpose interface.”

    Keep your interfaces as specific as possible. It is harder to untangle a big mess than a small mess.

  • Dependency inversion principle – One should “depend upon abstractions, [not] concretions.”

    If you use abstractions, you can safely switch out the implementation. As an example, your program expects an SQLDataSet back from SQLDataRetriever. A better solution would be to get FruitDataModel from GetFruitData, and hide the technical implementation inside of that method. This is very commonly done using the repository pattern, i.e you call FruitRepository.GetFruitData(myFruitId), and you leave the how that happens to FruitRepository. This means that if you started using a JSON database, your program will work instantly by switching out the implementation of FruitRepository from your SQL one to a JSON one instead of spending days making your entire application work with JSON instead.

Liked it here?
Why not try sites on the blogroll...