IT:AD:Patterns:SOLID

Summary

For the moment take a second to view the slides I put together here:

home

SOLID is pure gold in terms of what it can do to the maintainability of your code. It’s an acronym of 5 other patterns:

SRP

A class that contains a little bit of everything is difficult to maintain. You have to fish around in it to figure out how it works. If it’s written by someone else, you might never figure it out – you’re told it’s just …legacy, and to keep shoving stuff in.

SRP tells you to watch out for the word AND.

If your web page Controller class is Authenticating, then Authorizing, then Logging, then Rendering, that’s 4 things.

So make that it into 4 classes,and let the base page Orchestrate the actions of those 4 helper classes or services.

OCP

That rule generally freaks out develops the first time they hear it (“What do you mean never go back in and fix things?!”).

That reaction totally makes sense if you program God Classes that do way too much. You’ll never get it right.

But if your classes are small, tight, solutions to singular problems – guess what? As long as the problem doesn’t change, the contents never will either. New problem? New jar.

LSP

Interfaces! Everything in the real world is done by Contract (ie Interfaces). You buy a bus ticket…and have no idea who will be your bus driver today. So why should you classes be so tightly tied to a named class?

They shouldn’t. They should never deal with SqlDataReader – but IDataReader.

DIP

Constructors are totally under-appreciated things.

A class that has a constructor that has no arguments is a lier.

It’s basically saying “I’m cool. To do this work, I don’t need anything.” And then somewhere in one of its methods, it goes and instantiates a service that it needs to complete it’s work. It lied.

What it should have said is…I’m cool to do the work you are asking – but to do it, at some point, I may need the following service. Please instantiate it for me, and pass it to me in my constructor.

Pay the cost up front – find out if the logger’s config is correctly set up BEFORE you make classes that need it. Etc.

There’s nothing like honesty.