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])
Returns:
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]]
Returns:
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]]
Returns:
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 }
  .Increment
  .Print
  .Increment
  .Increment
  .Print

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:
[<fact>]
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

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.

ack

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.
ag

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.

Tuesday, February 23, 2016

How to Format Code in a Blog Post?

There are quite a few ways to easily format code in HTML, I'll walk you through the steps I took.

Step 1 - Find a good CSS library for code formatting

The best HTML syntax highlighter library I found was PrismJs. It's free, incredibly thorough the languages it supports, and it provides a professional look. You simply choose the language support you like and download the CSS and Javascript files.

Here is a before look:
let items = [1; 3; 4]
items |> List.map(fun x -> x + 1)
Here is the code after formatting with PrismJs:
let items = [1; 3; 4]
items |> List.map(fun x -> x + 1)

Step 2 - Move from Wordpress to Google Blogger

I originally had the blog on Wordpress using a free template but I decided to move it to Google Blogger. The reason for moving was Google Blogger provided free template editing. Wordpress has other advantages but for my purpose I simply needed to tweak the template to include the Prism CSS and Javascript files. Since I only had a few posts this was not a difficult move.

Step 3 - Host PrismJs CSS and Javascript files in DropBox
I used the instructions in this article to host the files in DropBox so they can be referenced publicly.

Step 4 - Update template HTML to include CSS and Javascript files

In Google Blogger I went to Template -> Edit HTML and added this piece in the header.
<link href='https://dl.dropboxusercontent.com/s/wvc7y6gckrru3ex/prism.css' rel='stylesheet'/>
<script src='https://dl.dropboxusercontent.com/s/sy0k7bc7ixl6xan/prism.js' type='text/javascript'/>
It was that easy! Now my blogging code looks much nicer.

Saturday, February 20, 2016

CORS for security

What is it? 

Cross-Origin Resource Sharing is a W3C spec that allows resource sharing across domains. Some resources are allowed to come from any domain, but web fonts and AJAX requests are limited to accessing the same domain as the parent web page. This presents a problem if an AJAX request from www.example1.com wants to request a resource from www.example2.com. In order to fulfill that request a CORS security header will have to be added to the response.

Why? 

All modern browsers implement the same-origin policy as a preventative measure to keep attackers from redirecting users to malicious websites. This is a bit unfortunate for development teams implementing APIs to be used across distributed environments. It can be perfectly valid for an API to serve AJAX requests to multiple domains. This is why the CORS spec was introduced and is necessary for teams with environments spanning multiple domains.

How to use it? 

To successfully serve a cross-origin request the server side must specify the Access-Control-Allow-Origin and Access-Control-Allow-Methods headers. The Allow-Origin header specifics the domains allowed to access the resource and the Allow-Methods specifies the HTTP methods allowed (GET, PUT, etc). To specify all origins allowed the Allow-Origin header could just specify '*'.