Sunday, December 27, 2015

Why I love Pattern Matching in Functional Languages Part 1

As I have embarked on this journey of learning functional first programming languages, I completely fell in love with pattern matching but it wasn't till recently that I understood why. If you are new to pattern matching this post (Stack Overflow pattern matching) gives a better explanation, but in my own words, I would describe it like this: The ability for your program to destructure or "pluck" the information needed from a data structure so that your program can "act" on this subset of data.

Why is this good? In my own opinion, this provides several benefits that makes it easier to program but specifically in elixir it can be used to determine the flow of your program from the function definition.

In a functional first language, you have one CENTRAL location that holds the state of your program that your program can act on. In object oriented languages, you typically would break this state up into different objects to "model" your program. This means you will typically have state in several locations and you have to "ask" questions about that state in one or more location before acting in your program. As an example in C#:


var ironMan = new IronMan();
var hulk = new Hulk();

if (ironMan.IsFlying == hulk.IsJumping)
    new Thor().StartFlying();

In Elixir the same code would look like this:


defmodule Marvel do
	@marvel %{ 
		:ironman => %{ :is_flying => true }, 
		:hulk => %{ :is_jumping => true}}

	def fight(), do: start_flying(@marvel)
	def start_flying(
		%{ :ironman => %{ :is_flying => true }, 
		   :hulk => %{ :is_jumping => true}}), do: fly
	def fly(), do: IO.puts "flying"
end

In elixir, the function only executes when the data set "looks" like the data that is passed into the start_flying function. I love this language feature because it communicates to someone reading my code what I want to happen (the name of the function) when the data is shaped a certain way. This means that the reader ONLY has to look at the function definition to determine the flow of the program. In an imperative language, the reader is forced to read the body of the function to determine the flow of the program.

Even though I have been programming in imperative languages my entire career, I find it much harder to program in an imperative way. It's like having to ask your wife, son, mother, and father a question before you run an errand instead of just having your wife telling you everything you need to know up front before you leave the house to run an errand.

Using this analogy, it means that if you have a "question" later, you have to call one of the 4 people to ask your question in the imperative approach as opposed to using pattern matching and "plucking" the information you need out of the original information given to you by your wife before you left the house :)  

Sunday, July 29, 2012

My C# feature wish list

With C# 4.5 going RTM in the next few months, I'm looking forward to the new features (particularly async and await). There are a few small features that I really wish they had added even though It would  be safe to say at this point C# is "baked".

1. String interpolation
       //this is much cleaner than the hideous string.format()
       var stringWithVariableInit = "some variable in of the @( variableSetSomePlaceElse )";

2. Implicit typing on return values
      public var Fly(){
             return new List<RecordedPoints>();
      }

      This would be a minor feature and can still be done with generics, but as great as generics are, they    can make the code quite noisy (implicit casting has improved this greatly)

Maybe we will see some of these features when project Roslyn is complete and MS or someone else will extend the compiler to support them. Project Roslyn will likely bring some other really nice features like metaprogramming

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.