Sunday, June 20, 2010

Ruby and Rails Summer Reading

If you ask a Ruby programmer why he is using Ruby, you will probably get several answers like: It is dynamic. I allows me too keep my code DRY. I get results faster. Aside from all these statements, there is one statement that almost always comes up.

I use Ruby because it makes me happy!

If you search Amazon for Ruby you get 8,829 Results and if you search for Rails you get 14,113 Results. What books should you get?

Here are the books I recommend:

Ruby

Beginning Ruby is a superb book for people coming new to Ruby.

If you are not a complete novice, you should instead go for The Well Grounded Rybyist.

When you have finished the Well Grounded Rubyist, you are ready for Metaprogramming Ruby where you learn metaprogramming techniques to help you keep your code DRY and readable.

Rails

Since Rails is currently being updated to version 3, there are not that many books available. I can recommend The Rails3 Way, currently only available as a Rough-Cut.

The lack of updated books is not a problem. The The Ruby on Rails Guides are excellent. Make sure you select the edge version.

Even more information is available through the videos from Railsconf, subscribe to them in iTunes. The first videos where published, the day after they were filmed. Fantastic!

Have a happy Ruby-red summer.

Tuesday, June 08, 2010

Seamless Web Development

Do you remember the time before 9/11 when you could arrive to the airport 10 minutes before the plane's departure and just walk on to the plane. Now, you have to arrive at least an hour before the plane departs and you have to strip to get through a security.

The security is just for show. I don't know how many times I have forgotten a bottle in my carry-on and I haven't noticed it until I unpacked the bag at home. There a number of ways to get a big bang for your bucks, that aren't checked at security

XKCD Bag Check

So what does this have to do with web development? Web development in a compiled language is like traveling after the terrorist attacks. You have to go through a lot of time consuming controls that are, mostly, for show. This dramatically slows down your development speed.

Since I did my comparison between Rails and .NET MVC I have done a lot of coding in both environments, and my conclusion is that Rails is a lot faster to develop with than .NET MVC.

The reason for this is that .NET MVC puts up a lot of seams that hinders development.

Seam #1, Runtime Development

When I'm using Rails for development I very rarely restart the server. When I make a change to the view, controller, model or database, the changes are visible on the next request. Immediate feedback!

In Visual Studio, there is something called "Edit and Continue", that you can set to allow you to make changes to the code while you are debugging. Mooah ha ha ha ha ha ha ha haaaaaaa! This sucks so bad that I cannot help bursting out in a crazy laughter. The flow disappears.

Edit and Continue

If I make changes to the view I can continue, unless I make changes to the I18N resources, because these are obviously not mutable. WTF!

Sometimes it is actually possible to make changes to the code, but when you try to save the changes "Edit and Continue"'s big brother appears and smacks you in the head, and the flow is gone again!

Edit and Continue2

There is really no good reason for this. I'm sure there are a number of technical reasons having to do with type safety and class reloading, but I don't care. Just reload everything, do it fast and unnoticeable!

Seam #2, The Javascript Impedance Mismatch

Hopefully everyone has realized that Javascript is the hottest thing in web development! A language that has been spat on, and laughed at, has become the most wide spread programming language in the world. It's available in every browser and on every programming platform.

I have been talking about the greatness of Javascript for a few years now and it is great to see when someone finally get it.

"Its great, I just change this little thing, then click reload, and it works immediately!" -- A collegue, seeing the coolness of Javascript.

Javascript is Lisp in C-clothing and Lisp is the language that God used to create the world.

Lisp

OK, Javascript is cool, and we all use it, but what is this impedance mumbo jumbo? Since a large part of a modern web application will be developed in Javascript, when we move over to the server side and everything is static and compiled, we are in for a lot of frustration.

Common Development Flow

  • Make a change to the GUI, in Javascript.
  • Reload
  • Make another change
  • Reload
  • Realizing that you need to change the controller for the next change.
  • Aaaaaaaaaarrrrrrrrrrrggggghhhhhhhh, I have to restart the application.
  • What was it that I was working on again? I'll go for a cup of coffee!

This is the Javascript impedance mismatch. If you are developing in a dynamic language you expect it to work like this all the time. You get used to it. It is better!

With Rails and Ruby, you get the same flow on the backend as you do on the client. The static-dynamic mismatch is gone. (There is still a language mismatch, between Javascript and Ruby, but it is minuscule by comparison.)

Seam #3, Cruft

Compare the following two partials

<!-- BookedCustomer.aspx partial in .NET MVC-->
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Bergqvists.Models.Booking>" %>

<div class="view">
    <div class="customer title"><%= Html.ActionLink(Model.Customer.Fullname, "Details", "Customers", new { Id = Model.CustomerID}, null) %></div >
    <div class="status"><%= Html.Encode(Model.BookingStatus.Name) %></div >
    <div class="booking-date"><%=ViewRes.BookingStrings.BookedOn %>
    <%= string.Format("{0:D}", Model.BookingDate) %></div>

</div>
<% Html.RenderPartial("BookingStatusLinks", Model);%>

<!-- _booked_customer.html.erb partial -->
<div class="view">
    <div class="customer title"><%= link_to customer.fullname, customer_path(customer)</div >
    <div class="status"><%= customer.booking_status.name %></div >
    <div class="booking-date"><%=t :booked_on %>
    <%= customer.booking_date, :format => :short %> %></div>

</div>
<%= render :booking_status_links, :locals => {:customer => customer} %>

As you can see the corresponding ERB is not much different, but at least everything in the code is meaningful. And what customer value does the first line bring?

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Bergqvists.Models.Booking>" %>

Nada! Zilch! It is only there to please the compiler. Cruft!

Now, most Ruby programmers I know use HAML instead of ERB and this cleans the view up considerably.

.view
  .customer.title= link_to customer.fullname, customer_path(customer)
  .status= customer.booking_status.name
  .booking-date
    = t :booked_on
    = customer.booking_date, :format => :short

= render :booking_status_links, :locals => {:customer => customer}

Beautiful!

Comparing Haml with ASP is not really fair, since it is possible to use NHaml instead of ASP in .NET MVC, but no one I know does that, maybe I hang with the wrong .Net people. NHAML is great, please switch it to the default for .NET MVC.

The example above is in the view layer. But the cruft spreads all over the stack.

Seam #4, Testing

Testing is always an interesting topic. The number one reason testing is not done is that it is to cumbersome. In .NET MVC I find it painful to test the controller and view layers, to the extent that I don't do it. With Rails on the other hand, you are setup for test from the start.

I always try to put as much code as possible into the model layer, but some code belongs in the controller. I want it to be easily tested too.

It is also worth noting that the Ruby community is driving the testing profession forward, with tools like RSpec, Capybara, Webkit and Cucumber.

Yes, I know that there are several implementation languages for Cucumber. It's possible to write your steps, in C# or Java or almost any other language. My advice is, don't do it! There is compilation, waiting, pain and suffering down that road. Use a dynamic language to test your code.

Conclusion

So what's my point? It's time to stop compiling and quit slacking off.

XKCD Compiling

Rails should be the default choice for web development. You should have a very good reason for not choosing Rails on your next web project.

I know it may feel tough to have invested many years in something else, but as the turks say.

No matter how far down the wrong path you've gone, turn back! --- Turkish Proverb

Don't take my word for it. Check out this interview and this presentation

Thursday, May 20, 2010

>Making Windows Keyboard Feel like OS X

I have been unfortunate enough to have to start working with Windows on my Mac. I am using Bootcamp and VMWare Fusion. If I only need to make minor changes I can boot the Bootcamp partition via VMWare so I don’t have to reboot the computer every time I have to use Windows. VMWare allows me to customize my mappings to send the keys that I am used to using, so if this was the only way I was using Windows, that would be quite alright.

Since I need to develop in Visual Studio, using VMWare is only an option for very small projects, or the whole experience will become painfully slow.

Bootcamp does not support remapping the keys. Agony! Well, I found a solution.

Remapping Keys

I am using a US keyboard layout, your key mappings may be different.

SharpKeys is a tool that helps you perform some registry hacks, to allow me to remap the keys that I want to change.

I use it to remap the Alt and Windows keys, since they are reversed on the Mac. I also move the “`~” down to the bottom left corner where “|" usually are on Windows. “|" are in two different places on a US layout, I don’t know why.

Now that I have finished remapping the keys, I am done using SharpKeys. Now all I have to do is to get the Windows key to behave the way they do on the Mac on not like Windows keys.

Setting up the Shortcuts

The first thing to do is to disable the normal WindowKey functions. Here is a guide.

AutoHotKey is a tool the lets you remap the functions that are sent when a key is pressed. It can do a whole lot of other cool stuff too, so I encourage you to check it out even if you are not using a Mac. It is a great automation tool.

Here is my shortcuts.ahk file. I remap all my CMD-actions to the WinKey, and I also remap the Win- Left, Right, Up and Down to the corresponding Mac shortcuts.

#SingleInstance force
#a::Send ^a
#b::Send ^b
#c::Send ^c
#f::Send ^f
#n::Send ^n
#o::Send ^o
#p::Send ^p
#q::Send !{f4}
#r::Send ^r
#s::Send ^s
#t::Send ^t
#v::Send ^v
#w::Send ^{f4}
#x::Send ^x
#y::Send ^y
#z::Send ^z

#Left::Send {Home}
#Right::Send {End}
#Up::Send {PgUp}
#Down::Send {PgDn}

After this is done it is OK, almost, to start working. The sad part is that this configuration only works with an external keyboard. I couldn’t get the internal keys mapped properly on my Macbook Pro. But at least it is working.

Friday, April 23, 2010

ASP.NET MVC vs. Rails3

I recently was contacted to implement an ASP.NET MVC application and I saw this as a great opportunity to compare it with Rails3.
What immediately strikes you when you start with ASP.NET MVC is how similar it is to Rails. No one can steal ideas like Microsoft!
Rails ASP.NET MVC Purpose (if not obvious)
/app/models /Models
/app/controllers /Controllers
/app/views /Views
/public/javascript /Scripts
/public /Content
/db /App_Data Database data, such as migrations, and models.
/test (unit, functional, fixtures, performance) Separate VS projects
/config /Global.asax, /Properties, Web.config Configuration

Project Generation

Both Rails and ASP.NET MVC relies on code generation to get you started, but the methods they use are different.
Rails uses the command line, which is natural since the Rails approach is to not rely on anything but a good programming editor and the command line.
$ rails tapir
      create  .gitignore
   ...
      create  app/controllers/application_controller.rb
      ...
      create  app/views/layouts
      create  config/database.yml
      create  db/seeds.rb
   ...
      create  public/javascripts/application.js
   ...
      create  test/unit
   ...
ASP.NET MVC uses Wizards inside Visual Studio, which is also expected since Microsoft has a long history of IDE-centric application building.
Worth noting is that I didn't really want to use VS Unit Test, since I normally prefer NUnit, but after one hour of googling and testing I gave up and went with VS Unit Test anyway.

Environment

When Rails is installed it comes pre-configured with three different environment, development, test and production. It is as easy as writing RAILS_ENV=test to switch from the default development environment to the test environment. In this area Rails really shines. There is nothing similar in ASP.NET MVC.

The Model

Rails Model

Rails comes pre-configured with an ActiveRecord model, if you don't write otherwise. If you want to use something else it is very easy. Supported frameworks are among others, Neo4J, MongoDB, and DataMapper.
To create a model in Rails3 you use a command line generator. The generator generates a model, a migration and tests. And you can, of course, choose what kind of model you wish to generate (-o), as well as what kind of testing framework you want to use (-t). Here I just go with the default:
$ rails g model customer name:string email:string
      invoke  active_record
      create    db/migrate/20100419094010_create_customers.rb
      create    app/models/customer.rb
      invoke    test_unit
      create      test/unit/customer_test.rb
      create      test/fixtures/customers.yml

Rails comes preconfigured with Sqlite3, and you don't have to do anything to configure the default database. Moreover, the configuration is set up to use three different databases, one for each environment.
Rails, performs all database changes through scripts, migrations. This is invaluable when you want to upgrade a database that is in production, or when multiple developers are changing the same database model. The migration scripts allow seamless migrations between the different databases.
# An example of a migration
class CreateCustomers < ActiveRecord::Migration

  # Called when migrating up to this version
  def self.up
    create_table :customers do |t|
      t.string :name
      t.string :email
      t.timestamps
    end
  end
  
  # Called when migrating down from this version
  def self.down
    drop_table :customers
  end
end

To move between the different versions of the database we use the rake db:migrate command.
# Migrate to the latest version
$ rake db:migrate 

# Migrate to a specific version
$ rake db:migrate VERSION=20080906120000 

# Rollback one version
$ rake db:rollback 

# Rollback three versions
$ rake db:rollback STEP=3

Read more about migrations in the Migrations Guide

ASP.NET MVC Model

ASP.NET MVC is not a full stack framework and it does not come preconfigured with a model. It is possible to choose between many solutions, such as NHibernate, Entity Framework or LINQ-to-SQL. I choose LINQ-to-SQL because I think it is an elegant, lightweight OR-Mapper, that is easy to work with. Too bad, it isn't prioritized by Microsoft.
Unfortunately, there is nothing like migrations in LINQ-to-SQL. So I use the LINQ-to-SQL design tool to design the classes.

You can then create the database from the model. It is also possible to do it the opposite way, to create the database first and then generate the model, but I prefer this way.
// Creating a database from a LINQ-to-SQL DataContext
public void CreateDatabase(bool force)
{
    var db = new TapirDataContext(@"c:\tapirdb.mdf");
    if (db.DatabaseExists() || force)
    {
        Console.WriteLine("Deleting old database...");
        db.DeleteDatabase();
    }
    db.CreateDatabase();
}

As you understand this is not a viable solution for migrating a production database, but it is good enough (almost) for development and testing, since I can allow myself to recreate the database every time. Once I get a larger database, the time it takes to set it up will force me to go with a better way. The lack of migrations hurts.

Query Language

Rails3 uses AREL, Active Record Relations, and LINQ-to-SQL uses LINQ (surprise!). They are both beautiful solutions and remarkably similar. Both solutions create lazy, composable queries, that are not executed until the latest possible time, when a result is needed. In LINQ, you can see Eric Meijer's Haskell shining through like magic, and in AREL, the beauty of Ruby.
# A simple query with AREL
User.where(users[:name].eq('Anders')).order('users.id DESC').limit(20)

// The same with C#
// Lambda Syntax
db.Users.where(u => u.Name == "Anders").orderBy(u => u.Id).Take(20)

// LINQ Syntax
(from u in db.Users
where u.Name == "Anders"
orderby u.Id descending
select u).Take(20);

One thing that you don't get with LINQ-to-SQL is all the methods that are dynamically created, by need, in Rails, such as find_by_name, find_by_name_and_age, etc.

The Controller

In ASP.NET MVC, it is easy to create a controller, you just right-click on the controllers folder and select Add > Controller. You then get a dialog where you can type in the name of the controller and, optionally, if you like to create default methods for the standard CRUD scenario, just select the checkbox.


public class CustomersController : Controller {
      // GET: /Customers/
      public ActionResult Index() {
          return View();
      }

      // GET: /Customers/Details/5
      public ActionResult Details(int id) {
          return View();
      }

      // GET: /Customers/Create
      public ActionResult Create() {
          return View();
      }

      // POST: /Customers/Create
      [HttpPost]
      public ActionResult Create(FormCollection collection) {
          try {
              // TODO: Add insert logic here
              return RedirectToAction("Index");
          } catch {
              return View();
          }
      }
}

As you can see the code generated is simple and clear. That is the benefit of MVC, simpler models, views, and controllers.
The automatic generation of code, that will probably be changed later is commonly known as scaffolding.
Scaffolding is a temporary structure used to support people and material in the construction or repair of buildings and other large structures. --Wikipedia
Scaffolding is not meant to be used as is. It is meant to get you started!
In Rails3 you add controllers with a generator. You have a lot more options, below are just a few of them.
$ rails g controller
Usage:
  rails generate controller NAME [action action] [options]

Options:
  -e, [--template-engine=NAME]  # Template engine to be invoked
                                # Default: erb
  -t, [--test-framework=NAME]   # Test framework to be invoked
                                # Default: test_unit

As you can see it is possible to choose what template-engine you want to use, and exactly what actions you want to create, the view templates are created automatically with every action you create.
$ rails g controller Customer index create
    conflict  app/controllers/customer_controller.rb
      create  app/controllers/customer_controller.rb
       route  get "customer/create"
       route  get "customer/index"
      invoke  erb
      create    app/views/customer
      create    app/views/customer/index.html.erb
      create    app/views/customer/create.html.erb
      invoke  test_unit
    create    test/functional/customer_controller_test.rb
      invoke  helper
    create    app/helpers/customer_helper.rb
      invoke    test_unit
    create      test/unit/helpers/customer_helper_test.rb


If you want to create all the default actions you should instead invoke the scaffold_generator.

$ rails g scaffold_controller
Usage:
  rails generate scaffold_controller NAME [options]

It will create all the default actions and the views that go with them.
The generated code is shown below. Again, you see the similarity between the two solutions. Rails, automatically generates support for both HTML and XML, making it easy to consume the data from other clients.
class FishController < ApplicationController
  # GET /fish
  # GET /fish.xml
  def index
    @fish = Fish.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @fish }
    end
  end

  # GET /fish/1
  # GET /fish/1.xml
  def show
    @fish = Fish.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @fish }
    end
  end

  # GET /fish/new
  # GET /fish/new.xml
  def new
    @fish = Fish.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @fish }
    end
  end

  # GET /fish/1/edit
  def edit
    @fish = Fish.find(params[:id])
  end

  # POST /fish
  # POST /fish.xml
  def create
    @fish = Fish.new(params[:fish])

    respond_to do |format|
      if @fish.save
        format.html { redirect_to(@fish, :notice => 'Fish was successfully created.') }
        format.xml  { render :xml => @fish, :status => :created, :location => @fish }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @fish.errors, :status => :unprocessable_entity }
      end
    end
  end
...
end

Filters

In Rails it is easy to create filters, that can be applied to specific actions.
class ItemsController < ApplicationController
  before_filter :require_user_admin, :only => [ :destroy, :update ]
  before_filter :require_user, :only => [ :new, :create]
end

In ASP.NET MVC, the same thing can be accomplished by overriding OnActionExecuting, in the controller.
override void OnActionExecuting(ActionExecutingContext filterContext)
{
    var action = filterContext.ActionDescriptor.ActionName;
    if (new List<string>{"Delete", "Edit"}.Contains(action)) {
        RequireUserAdmin();
    }
    if ("Create".Equals(action)) {
        RequireUserAdmin();
    }
}

The functionality may also be extracted into an ActionFilter, which can be applied to the controller or an individual method via an Attribute.
[RequireUserAdmin("Delete", "Edit")]
[RequireUser("Create")]
public class CustomersController : Controller

This is a pattern that can be seen everywhere, when Rails uses Class Macros, a term from Meta-Programming Ruby, ASP.NET MVC uses attributes. And this is appropriate since it usually constitutes meta-data.

Routing

The Routing in both Rails and ASP.NET MVC is incredibly flexible.

Rails Routing

In Rails it is possible to put constraints right in the routing table on just about anything.
# config/routes.rb
Tapir::Application.routes.draw do |map|
  resources :animals

  get "customer/index"
  get "customer/create"
  
  match "/:year(/:month(/:day))" => "info#about", 
 :constraints => { :year => /\d{4}/, 
  :month => /\d{2}/, 
  :day => /\d{2}/ }  
  match "/secret" => "info#about", 
 :constraints => { :user_agent => /Firefox/ }     
end


As you can see Rails comes pre-configures with RESTful routing, and it is indeed the recommended way to set up your routes in Rails. To see what the routing result is is easy:
$ rake routes
                GET    /animals(.:format)          {:action=>"index", :controller=>"animals"}
        animals POST   /animals(.:format)          {:action=>"create", :controller=>"animals"}
     new_animal GET    /animals/new(.:format)      {:action=>"new", :controller=>"animals"}
                GET    /animals/:id(.:format)      {:action=>"show", :controller=>"animals"}
                PUT    /animals/:id(.:format)      {:action=>"update", :controller=>"animals"}
         animal DELETE /animals/:id(.:format)      {:action=>"destroy", :controller=>"animals"}
    edit_animal GET    /animals/:id/edit(.:format) {:action=>"edit", :controller=>"animals"}
 customer_index GET    /customer/index             {:controller=>"customer", :action=>"index"}
customer_create GET    /customer/create            {:controller=>"customer", :action=>"create"}
                       /:year(/:month(/:day))      {:year=>/\d{4}/, :month=>/\d{2}/, :day=>/\d{2}/, :controller=>"info", :action=>"about"}
                       /secret                     {:user_agent=>/Firefox/, :controller=>"info", :action=>"about"}


ASP.NET MVC Routing

ASP.NET MVC Routing is not quite as easy, but everything is possible. The standard routing with paths and parameters works easily out of the box.
// Global.asax.cs
 public class MvcApplication : System.Web.HttpApplication { 
 public static void RegisterRoutes(RouteCollection routes) {  
  routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
  
  // Constrained route
  routes.MapRoute( "Product", "Product/{productId}", 
   new {controller="Product", action="Details"}, 
   new {productId = @"\d+" } ); // Constraint
  
  // Route with custom constraint, defined below 
  routes.MapRoute( "Admin", "Admin/{action}", 
   new {controller="Admin"}, 
   new {isLocal=new LocalhostConstraint()} ); 
 }
...
}

public class LocalhostConstraint : IRouteConstraint { 
 public bool Match ( HttpContextBase httpContext, Route route,
   string parameterName, RouteValueDictionary values,
   RouteDirection routeDirection ) 
 { 
  return httpContext.Request.IsLocal; 
 } 
} 

As you can see, you have the same power in the ASP.NET MVC Routing, but it requires you to add constraints separately.

Views

In both Rails and ASP.NET MVC, the views are automatically matched in the directory with the same name as the controller, and the file name is named by the action.
app/controllers/customer_controller.rb
app/views/customer
app/views/customer/create.html.erb
app/views/customer/index.html.erb

In Visual Studio it is possible to scaffold a view based on a model, just as it is in Rails. Rails is, of course, more flexible, allowing me to scaffold all or some actions at once. In Visual Studio, it is only possible to do one at a time.

Partials

In both Rails and ASP.NET MVC, a partial is a file that contains a part of a HTML file. The file is written in ASP in ASP.NET MVC and in Rails it is possible to pick the templating language of your choice. Default is ERB, but HAML is also a popular choice.
<!-- Rails -->
<%= render 'form' %>

<!-- ASP.NET MVC -->
<% Html.RenderPartial("Form", Model);%>

In ASP.NET MVC version 2, the preferred way is actually to use two alternate methods to generate the code. They have the advantage that they are type-safe (if that gives you pleasure) and they keep track of nesting.
<%= DisplayFor("Address", m => m.Address ) %>

<%= EditorFor("Address", m => m.Address ) %>

(For Rubyist, the m => m.Address is not a hash key-value expression, but an anonymous function.)

Helpers

A helper is similar to a partial, but it is not a template, it's a method that generates code.
In Rails you create a helper by creating a simple method.
module ApplicationHelper
   def label target, text
     "<label for='#{target}'>#{text}</label>"
   end
 end

And so you can in ASP.NET MVC.
public class LabelHelper {
    public static string Label(string target, string text) {
        return String.Format("<label for='{0}'>{1}</label>", target, text);
    }
}

Conclusion

All in all, ASP.NET MVC with LINQ-to-SQL, is not a bad experience. Eric Meijer and friends have managed to overcome a lot of the hurdles of static typing. They also, let go of it in cases, where dynamic typing is obviously better, such as in the routing and when populating objects from forms. The lambda expressions and the type inference also removes a lot of the boilerplate common in statically typed languages.
Rails is of course a lot more flexible, and faster to work with. The scaffolding is faster and more flexible, the migrations are, as I said before, invaluable when it comes to move between versions.
But, if I'm thrown out of the dynamic Garden of Eden, I'd rather pick my static apples in Redmond, than in California.

Wednesday, April 14, 2010

Static Typing is the Root of All Evil

I can't take credit for this statement, since I am only drawing the logical conclusion from a statement said by a man far smarter than I.

Donald Knuth wrote in his famous paper Structured Programming with go to Statements (PDF):

We should forget about small efficiencies, say about 97% of the time: pre-mature optimization is the root of all evil

Since compilation is premature optimization, it is therefore, the root of all evil. Simple!

Static typing, weak typing, dynamic typing, strong typing, WTF?

There are a number of misconceptions concerning typing.

The meaning of weak and strong typing, is not clearly defined but is mostly interpreted like this.

In a weakly typed language, such as C, the types of the variables can be automatically converted from one representation to another, while in a strongly typed language an explict conversion is required.

This is not what I am writing about here. I am referring to static vs. dynamic typing and the definition I am using is:

  • Static typing, the type checking is performed at compile-time.
  • Dynamic typing, the type ckecking is performed at run-time.

Development Mode

Every time I build my code, my entire code base is type-checked. EVERY TIME! When I am working in development mode, I only care about the method and class that I am currently working on. As long as my tests pass I am happy, type-safe or not.

In development mode it is actually more accurate to call static typing pre-mature de-optimization than pre-mature optimization.

Production Mode

The only reason, to ever use static typing, is because the code may be optimized better, to give better performance.

So, the strategy should be:

  • Use a dynamically typed language during development. It gives you faster feedback, turn-around time, and development speed.
  • If you ever get lucky enough to have performance problems, which cannot be solved with caching or algorithmic optimization, rewrite the problematic code in a statically typed language.

This is what Twitter did, and it has worked well for them.

Other Misconceptions

Proponents of Java often have the misconception that dynamically typed languages are unsafe, yet they use frameworks, like Spring, and Qi4J, that are littered with reflective code, and without the so-called safety net that static typing is believed to give. The reason these frameworks are popular is because they allow us to be more productive. The reason they are more productive is because they use dynamic programming techniques.

Anyone, who has worked seriously with a modern dynamically typed language like Ruby or Smalltalk, know that they are more productive. Working with waterfall languages after working with agile languages is just painful. (Thanks to Andreas Ronge for coining the term Waterfall Language.)

Sunday, February 14, 2010

Why not Maven

This blog post is in reply to a comment by Jason van Zyl on my previous post. It is written as a post since blogger does not allow me write syntax highlighting in comments.

Jason, you are probably right about me making assumptions about what Maven is, or at least what I think that it should be. But the fact is that, my main use of Maven is as a build tool!

And don't misunderstand me, I really like a lot of what Maven has brought to the community. The standardized repositories and the standardized project layouts being the main contributions.

I also like the fact of the one-click build, or one-click development environment setup, even though I don't think that these are an invention of Maven. I know that at least Joel Spolsky wrote about this years ago.

But what I don't like is that, whenever I want to do something that is not part of the standard Maven toolset, I have to invoke the Google Gods, and hope that someone has written a halfway decent plugin that does the work I want done. Most of the time, the plugin is OK and I end up using it. But, with every little thing I add, the project setup gets a lot more complicated and inconstant.

Below is an example of a configuration for generating documentation with asciidoc. I really think that the readability of the Maven part obscures what I want to do. And being obscure is one of the primary sins of programming and building in my book.

<!-- Generating a file with asciidoc and Maven -->
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.1.1</version>
    <configuration>
        <executable>asciidoc</executable>
    </configuration>
    <executions>
        <execution>
            <id>generate-deployment</id>
            <configuration>
                <commandlineArgs>
 --unsafe --out-file
${project.build.outputDirectory}/deployment.html
${project.build.directory}/deployment.txt
  </commandlineArgs>
            </configuration>
            <goals>
                <goal>exec</goal>
            </goals>
            <phase>compile</phase>
        </execution>
    </executions>
</plugin>


# Generating a file with asciidoc and Rake or Buildr
file ${project.build.outputDirectory}/deployment.html => 
 ${project.build.directory}/deployment.txt do
 sh "asciidoc --unsafe --out-file=#{to} #{from}"
end

The example above is just one, of many, that I have run into, during my years of dealing with build systems.

I took a look at Polyglot, and it is not the answer to my annoyances. My main annoyance is not the XML, it is that I cannot do simple things without having to resort to third party plugins that don't work the way I want them to. I want precision and Maven does not give me that. (Perhaps because I did not write it.)

I'm also sorry if I sounded like I thought it was easy to do what you are trying to do. I don't! I have tremendous admiration for your abilities and for what you are trying to do, but as I said in the blog post. I think you are wrong when trying to create a build system that does not include the ability to use programming abstractions. The abstractions lets me do simple thing easily.

Perhaps the problem is that Maven is trying to do to much. Perhaps there should be two parts, Maven-Project for generating nice project information about the status of a project, and Maven- Build for dealing with the part that is doing the building. In my opinion Maven-Build should be more like Rake and Buildr and less like what Maven is at the time of writing.

But you don't have to agree with me, you obviously have a different experience than I do. In the mean time I will continue to use Rake and Buildr, and continue to use the paved road that Maven has provided with its standardized repositories and layouts.

Saturday, January 23, 2010

Maven, the new Elephant on the Block

Some of you may remember the article, by Bruce Tate, Don't Make Me Eat the Elephant Again.
It was an article about EJB, and Bruce was begging Sun not to make the same mistakes with EJB3 as they had done with EJB, and EJB2. They didn't, Spring came along as better alternative and forced EJB3 to become slimmer and better. If not for Spring, EJB3 would probably look very different from what it looks like today.
Well, guess what, there is a new elephant on the block and its name Maven2.


Just like EJB2, Maven2 was born out of something so unbearable that anything else was bliss. Jelly anyone!


But just as EJB was fundamentally flawed, so is Maven2. Build systems, even advanced ones like Maven is fundamentally about two things.
  1. Check if something that something else depends on has changed
  2. If so, do something.
That's it, that is what is important.
The checking may contain various sophisticated methods for detecting if files, subsets of files, all files, web pages, twitter feeds, etc, has changed, but that is really it.
And the doing can be anything, Copy files, commit files, build websites, run tests, generate code, launch missiles, whatever!
But the key to doing this efficiently is a programming language with easy access to system commands and the ability to create simple abstractions, with methods, variables, and objects. The language should also, preferably, be one without a lot of ceremony, like Ruby, Javascript or Python.
There are already build systems like this out there, Buildr, SCons, and Rake come to mind, but they do not have the momentum of Maven, so a merger between Maven and Buildr would be wonderful.



So, Jason, hear my plea, Don't make me eat the elephant again!