Tuesday, March 29, 2016

F# Yield Keyword

The yield keyword in F# is similar to the Return keyword in that it returns a value. The difference is yield is used within a sequence (or an enumeration) and it does not stop the enumeration.

Here is an example of filtering a list and returning a list of lists.
[3; 6; 8; 9]
|> List.filter(fun x -> x > 5)
|> List.map(fun x -> [x + 1])
val it : int list list = [[7]; [9]; [10]]

To accomplish this task with for..in and yield we could do the following:
[for x in [3; 6; 8; 9] do
  if x > 5 then
    yield [x + 1]]
val it : int list list = [[7]; [9]; [10]]

yield is similar to Return in that they both have counterparts like ReturnFrom (return!) and YieldFrom (yield!). Yield bang will do a collect and flatten the returned sequence. Here is the example using yield bang.
[for x in [3; 6; 8; 9] do
  if x > 5 then
    yield! [x + 1]]
val it : int list = [7; 9; 10]

Tuesday, March 22, 2016

What are Fluent Interfaces?

What are they?
A fluent interface is an API facade that uses method chaining that preserves state throughout the method calls. This type of API can lead to more readable OO code because each method call returns a new class that contains the new state. Meaning the result of each call does not have to be stored in a variable and can be chained together.

When to use?
Functional programming has pipelining and higher order functions to achieve the readability win that fluent interfaces provide in OO languages. So, I think fluent interfaces are unnecessary in functional languages. Fluent interfaces can provide more readable code using method chaining in OO languages. Use them when your API needs to be simplified and you want it to read well.

Take this LINQ example:
[1; 2; 4]
  .Select(fun x -> x + 1)
  .Where(fun y -> y < 4)

There is a lot going on under the hood, but by simply looking at this code it is easy to tell what is supposed to happen.

How to implement?
To implement method chaining each method must return a new instance of a class taking into account the current state. A fluent interface is not necessarily just method chaining, so how to implement a fluent interface is specific to the domain space. We'll use a simple method chaining example here.

Here is a class with two actions.
type Counter = { Count: int } with
  member this.Increment : Counter = 
    { Count = this.Count + 1 }
  member this.Print : Counter = 
    printfn "Current Count = %i" this.Count
    { Count = this.Count }

Each action returns a new instance of the class and the method calls can be chained together.
{ Count = 3 }

The output of the above statement would be:
Current Count = 4
Current Count = 6
This example is trivial but this method can be used with complicated scenarios resulting in more readable code.

Tuesday, March 15, 2016

My Favorite F# Feature - Creating an Anonymous Class from an Interface

There are a lot of delightful F# language features and the best may be the ability to create an anonymous class implementing an interface. When I first discovered this feature I jumped out of my chair with excitement. Let's walk through a simple scenario.

Here we have a simple interface:
type SomeRecord = { 
    ID : int 
    Name : string 
type IDatabase =
    abstract member Get: int -> SomeRecord
    abstract member Save: SomeRecord -> bool

Here is the normal way to implement an interface:
type RealDatabase() =
    interface IDatabase with 
        member this.Save x = // database get implementation
        member this.Get record = // database save implementation

This could be used in code as follows (admittedly a rather contrived example):
let Service (db:IDatabase) id = db.Get id

When writing a unit test for this function we could create a test class implementing the interface. But, using F# allows creating an instance of the interface on the fly which makes testing really easy like so:
let ``Some unit test``() =
    let fakeDb = { new IDatabase with 
                       member this.Save record = true 
                       member this.Get id = {ID = id; Name = "Test"} } 

    (Service fakeDb 2) |> should equal {ID = 2; Name = "Test"}

This is much easier than using a moq library. The ability to easily create classes implementing an interface without much code is another reason I really like F#. The language doesn't get in the way when trying to accomplish a task.

Tuesday, March 8, 2016

The Search Wars - grep vs ack vs ag

Developers should be constantly searching and refining their toolkit. Knowing the right tool to use for the job is an important aspect of being productive. Here are three competing ways to search using the command line.


grep is a tried and true UNIX command that has been around for decades. It's lightweight, fast, and successfully does the job of quickly searching. grep is a command line utility that every developer should become familiar with. While grep is great, there are a few alternatives that offer some advantages.


Why use it?

For one, ack has 25% fewer characters than grep, typing win! ack is designed for developers and is best suited for searching code files. It is faster than grep because it will ignore common source control files like .git and subversion source control directories.

How to install for OSX?

Use homebrew:
    brew install ack
How to use?

Here is a simple usage. The results are very clean and even come with highlighting.

Why use it?

Ag contains 33% fewer characters than ack! It's also an order of magnitude faster than ack because of it's written in C and is able to take advantage of multiple CPU cores. This as well as a number of other performance enhancements described on the GitHub page.

How to install for OSX?

Use homebrew:
    brew install the_silver_searcher
How to use?

Very similar usage as ack.
I have to admit sometimes I still use sublime for regex pattern matching, but the above utilities are good, reliable, and fast options that every developer should have in their toolkit.

Wednesday, March 2, 2016

Book Review: Dependency Injection in .NET

Dependency Injection in .NET changed the way I think about software development. Dependency injection is a topic that is easy to describe, but not until reading this book did I feel it in my bones as I was writing code. It's a powerful topic. Here are my main takeaways from reading this excellent book.

Use constructor injection - not setter injection. Constructor injection is the cleanest way of passing dependencies. This way, it is known when you have an instance of that class the dependency has been specified. Otherwise with setter injection guard clauses must be added to ensure the dependency has been set (besides as we know, mutation is the devil!)

Make your code testable - unit tests help ensure correctness. A side benefit of writing testable code is loose coupling where components have no knowledge of how the surrounding system works. This enables changing the program easier in the future. If you start with this principle when designing your application you will end up with much cleaner design resulting in fewer defects.

.NET Containers - the last part of the book goes over the most popular .NET dependency injection containers. I'm not going to go over them in detail here, but castle windsor, structuremap, and spring .NET are among the containers covered in the book. Good patterns and anti-patterns when using these containers are discussed with clear examples. I was surprised at the extensive features provided by these libraries.

Even non OO and non .NET programmers can benefit from the ideas in this book. These patterns remind me of good functional code, where the program is made up of mostly pure functions that are easily testable. Passing dependencies and settings into functions instead of defining them within the function is a great way to write applications.