Tuesday, October 25, 2011

I need closure in life....

One of my favorite techiques is using functional programming (in both C# and ruby) to "template out" code with anonymous delegation. It's perfect for those situations where you don't want to create an interface (in C#) for the sole purpose of reusing code inside of classes. There are many other situations where the technique provides some elegance to reuse, but reusing it within classes makse it a very approachable technique.

A very simple example would be as follows :

[TestMethod]
public void ExecuteFunctionalTechnique()
{
    TryCatchTemplate(() => { new Babolat().StringRacquet(); });
}

private void TryCatchTemplate(Action body){
    try
    {
        body();
    }
    catch (Exception)
    {
        throw;
    }
  
}

It gets more fun when you have to return a value from the anonymous delegate and you don't want to commit  to a type (yay, generics). A simple example is as follows:

 BindSelect<IList<Role>>( selRoles, "ID""Name"Role.GetAllRoles );

private void BindSelect<T>(HtmlSelect securityDropDown, 
    string dataMemberName, 
    string dataText, 
    Func<T> collectionToBind)
{
    securityDropDown.DataSource = collectionToBind();
    securityDropDown.DataValueField = dataMemberName;
    securityDropDown.DataTextField = dataText;
    securityDropDown.DataBind();
}

Have fun!

Friday, September 23, 2011

The "Bubba" Codebase

Two fisherman are  fishing in a small lake sitting in a boat having a pleasant conversation while drinking beer and the following coversation ensues:

John: You brought your tacklebox right?
Bubba: Sure did.
John: Do you have a bass fishing lure?
Bubba: I believe so, here take a look.
John: Bubba...... that's not a tacklebox, that's  a friggin bucket with a bunch of damn lures in it.
Bubba: You call it a bucket, I call it a tacklebox. Trust me the lure is in there
*John reaches in the bucket and starts moving lures around and immediately pulls is had out*
John: Ouch.. damn.... cut myself on a lure..... this is rediculous, how do you find anything in here?
Bubba: It takes a long time to find what I'm looking for, and the more lures I get the longer it takes to find something.
John: You need to get a real tackle box Bubba,  this is just stupid that you call this organization let alone risk getting cut by rusty hooks everytime you reach in this bucket.
Bubba: Stop being a punk, you just have to move stuff around carefully.
*John reaches down to his side and lifts up a real tacklebox*
John: See how all of my lures are in nice neat compartments? I can find any lure I want in seconds, plus if I want to get rid of a certain kind of lure, I just dump all of them out of the drawer and put in the new ones. And, I makes sure that I have similar lures in each drawer.
Bubba: Uh huh......

As developers we have all had to work with the "Bubba Codebase".

It's that codebase that is infested with tight class coupling, god objects, crappy cohesion and no separation of concerns. As soon as you stick your hands in it you instantly start bleeding and spend hours looking for something. The reality is that if don't start your code by putting functionality in some cohesive compartments (small classes and functions), it is unlikely you will ever do it while working on the project.

Sometimes, your only option is to throw the bucket out and start over with new lures and a shiny industrial size tacklebox.

The Lego Metaphor....

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.