The lego metaphor is often made in reference to software construction because it models how software should be build so well. Unfortunately, as software developers, building modular software is the last thing on our minds while building line-of-business software.
What does it mean to build modular software? While it could mean many things to many different developers in my experience it means the following:
1. Classes should not have dependencies on other classes (there are obvious exceptions to this). However they should and will have dependencies on abstractions that are passed in to the class.
2. Code that accesses external resources (databases, services, the force, etc) should be abstracted away from the "core" operations of the program.
3. Classes should be small. If you have a class that has more than 5 methods in it, look at it closely to make sure that ALL methods in the class are behaving within the same context. If you have a class that is updating the database and reading from the database, this isn't the same context.
4. Methods should be small. If you exceed more than 15 lines of code in a method, you need to check to make sure that another method or better yet another class isn't hidden in there.
5. There should be clear separation of concerns. In browser based apps html belongs on the presentation layer (html pages), not the "core" part of the program, the same goes for classes that will be accessing external resources.
Not following these guidelines have often led to the Bubba Codebase
In order to make your life easier when you have to come back and change the code, there are some obvious techniques that are life savers. In a later post I will go over these techniques such as Test Driven Development, Consume First class creation and Functional Programming.
Going back to the metaphor, we work with the inter-connection parts on the lego brick. The nubs on the lego brick are what you will be interacting with, not the brick itself (coding to abstractions).
An over-simplistic C# example would be:
public class BrickLayingMachine
{
public bool Connect(IFourStuds firstBrick, ITwoStuds secondBrick )
{
//Code to connect the bricks goes here
return true;
}
}
public interface IFourStuds { bool FaceUp(); }
public interface ITwoStuds { bool FaceSideways(); }
What does this buy you? The ability to pass in any brick you want later, no matter what color it is as long as it has the right number of Studs. If you passed in a concrete class, you would be forced to change how that class works which could be used in 20 other places in your code base. In a future post, I will associate the names (dependency injection, Liskov, SRP, polymorphism, etc) of principles/patterns to this overly simple metaphor/example.
No comments:
Post a Comment