Friday, July 6, 2012

Open/Closed Principle

With so many things interrelating, it's hard to explain the importance of one thing without relying on many other bits of knowledge.

Open/Closed is on of those things.

How can software be Open for Addition and Closed for Modification.

Surely I need to change code? And change it all the time.

Well, maybe.

If I write smaller functions, and smaller classes. If they do one thing, and do it correctly, then they probably don't need to change. Ever.

My larger blocks of functionality, which are made of the smaller blocks, will change more often, but if, for example I create a class or function to do a bilinear interpolation of a surface, then as long as it does a bilinear interpolation, I may need to optimize it, but it will only ever do a bilinear interpolation. If I want to do some other interpolation, I create a new class.

My higher level class may change to use the new interpolation, but I have not CHANGED the bilinear one.

I may wrap the General Bilinear interpolation in a class which is better named from the point of view of the problem domain, and takes domain named parameters. Rather than have an Bilinear.Interpolate(double x, double y)->double  my wrapper may be myChemicalMix.ApproximateReactionRate(double tempInCelcius, Acidity ph) -> ReactionRate.

Now my domain class does nothing but map my domain problem onto an interpolation. I no longer have to remember is x the Acidity or the Temperature.

So now when I change from a Bilinear Interpolation to a Triangular Interpolation, my Bilinear Class remains untouched, I write my Triangular Interpolation and Unit Tests, and if it turns out that they can each implement a Surface Interpolation interface, happy days.

Nothing in designing software stands on it's own. That's why it's easy to write a program, but it's hard to engineer one.

Without Single Responsibility and Dependency Inversion, Unit testing is staggeringly difficult.
Without The Open/Closed Principle, you will spend all your time changing tests.
Without Interface segregation, you won't understand what you need to mock out for a given test, and the test will be overly complex.

Good design can only come from understanding why.



* yes, I did make those up from thin air

No comments:

Post a Comment