Showing posts with label patterns. Show all posts
Showing posts with label patterns. Show all posts

Sunday, April 07, 2013

Javascript Conditionals

As we all know, Javascript is a very flexible language. In the article I will show different ways to execute conditional code by using some common idioms from Javascript and general object-oriented techniques.

Default values

Javascript does not support default values for arguments and it is common to use an if statement or a conditional expression to set default values.

function swim(direction, speed, technique) {
  // Default value with if statement
  if (!direction) direction = 'downstream';

  // Default value with conditional operator
  var speedInMph = speed ? speed : 2;
}

I usually prefer to use an or-expression instead. The short-circuiting or, ||, avoids the repetition of the conditional operator and is, in my opinion, more readable. Another advantage of avoiding repetition is that a slow executing function condition such as fastestSwimmer() will avoid the performance penalty of calling the function twice.

  // Default value with or.
  var swimTechnique = technique || 'crawl';

  // Function is only invoked once
  var siwmmer = fastestSwimmer() || 'Michael Phelps';
}

Naturally, this technique is not limited to default arguments, it can be used to set default values from object literals too.

options = { kind: 'Mountain Tapir', }
var kind = options['kind'] || 'Baird Tapir';

A simple, yet useful, technique.

Update 2013-04-13, as Jeffery mentions in a comment, the technique only works for values that are not falsy. If values such as 0 or false are acceptable values, you will have to explicitly test for undefined instead.

Call callback if present

Another idiom in Javascript, especially in Node, is passing callbacks to other functions. But, sometimes the callbacks past in are optional. In this case we can use short-circuiting and, &&, instead.

function updateStatistics(data, callback) {
  var result = doSomethingWithData(data);
  // Call the callback if it is defined
  if (callback) return callback(result);
}

function (data, callback) {
  var result = doSomethingWithData(data);
  // The last evaluated value of the `&&` is returned
  return callback && callback(result);
}

I, personally, prefer the first form with the explicit if because I think it communicates my intent better but, it is good to know about the technique anyway.

Update 2013-04-13, A better use for the technique is for testing for the presence of objects before getting their properties.

function callService(url, options) {
  ajaxCall(url, options && options.callback);
}

Lookup Tables

If you have code that behaves differently based on the value of a property, it can often result in conditional statements with multiple else ifs or a switch cases.

if (kind === 'baird')
  bairdBehavior();
else if (kind === 'malayan')
  malayanBehavior();
else if (kind === 'mountain')
  mountainBehavior();
else if (kind === 'lowland')
  lowlandBehavior();
else
  throw new Error('Invalid kind ' + kind);

I find this kind of code ugly and I don't think it looks any better with a switch statement. I prefer to use a lookup table if there is more than two options.

var kinds = {
  baird: bairdBehavior,
  malayan: malayanBehavior,
  mountain: mountainBehavior,
  lowland: lowlandBehavior
};

var func = kinds[kind];
if (!func)
  throw new Error('Invalid kind ' + kind);
func();

I find this code a lot clearer since makes it clear that the else clause handles an exceptional case and that the normal cases works similarly.

Missing Objects

If similar conditionals appear in multiple places in my code, it is a sign that I am missing an object somewhere. Since Javascript is duck typed I can use the same technique as above to create objects instead of just functions.

var kinds = {
  baird: { act: bairdBehavior, info: bairdInfo },
  malayan: { act: malayanBehavior, info: malayanInfo },
  mountain: { act: mountainBehavior, info: mountainInfo },
  lowland: { act: lowlandBehavior, info: lowlandInfo },
};

var tapir = kinds[kind];
if (!tapir)
  throw new Error('Invalid kind of tapir ' + kind);

I prefer to have this kind of code on the borders of my application. That way the code inside my core domain doesn't have to deal with complicated conditional logic. Polymorphism for the win!

Null Objects

If I notice that in many places I have to check fornulls, it is usually a sign that I haven't handled the special null case properly. In the example above I have handled it properly since I throw an Error if the kind of tapir does not exist. But sometimes it is not an error when the value is missing.

// If a non existant kind is used, tapir will become null
var tapir = kinds[kind];

// In other places of the code
if (tapir)
  tapir.act();

// Somewhere else
if (tapir)
  return tapir.info();

This type of code is rather unpleasant and it is time to break out the Null Object.

var tapir = kinds[kind];
// If a non existant kind is used I use a Null Object
if (!tapir)
  tapir = { act: doNothing, info: unknownTapirInfo }

// In other places of the code the conditionals are gone.
tapir.act();

// Somewhere else, no special case here.
return tapir.info();

Null Objects are not appropriate everywhere but, I often find it very enlightening to have them in mind when I write code.

Summary

There are a lot of elegant ways to deal with conditional code in Javascript. I didn't even mention inheritance since it works similarly to the object approach I showed above. But if I need multiple instances of something I would of course use polymorphism through inheritance instead.

Sunday, June 05, 2011

Tips from Rails Anti-Patterns

Another good Ruby book is out, Rails Anti-Patterns. The book is loaded with good tips on everything from following the Law of Demeter to cleaning up your views with the use of helper methods.

Here are some things I picked up from the book.

delegate can take a :prefix argument

The delegate method from active_support is used for delegating calls to another object without having to write out the full delegating methods. It can take a prefix option to customize the name of the delegating methods.

class Address
  @attr_accessors :street, :zip
end

class Person
  attr_reader :address
  # prefix => true, results in the model name being used as prefix
  delegate :street, :zip, :to => :address, :prefix => true
  #@person.address_street, @person.address_zip
end

class Person
  attr_reader :billing_address, :delivery_address
  # prefix => string, uses the string as prefix
  delegate :street, :zip, :to => :address, :prefix => delivery
  #@person.delivery_street, @person.delivery_zip
  delegate :street, :zip, :to => :address, :prefix => billing
  #@person.billing_street, @person.billing_zip
end

Transaction Scope

The code executed in the ActiveRecord callbacks execute in the same transaction as the actual call to save, create, update, or delete. Knowing this helps to eliminate unneccessary explicit transactions.

# Using a before filter
class Drink
  before_create :remove_ingredients_from_bar

  def remove_ingredients
    ingredients.each do |ingredient|
      Bar.remove(ingredient)
    end
  end
end

# Is better than using an explicit transaction
class Drink
  def create_drink
    transaction do
      remove_ingredients
      create
    end
  end

  def remove_ingredients
    ingredients.each do |ingredient|
      Bar.remove(ingredient)
    end
  end
end

Association Methods

It is possible to add methods directly on the activerecord associations. This is especially handy if the method uses information from both sides of the relation.

class Drink
  #has_field :minimum_drinking_age
end

class Customer
  #has_field :age

  has_many :drinks do
    def allowed
      # proxy_owner is the object defining the relation, Customer
      where(['minimum_drinking_age < ?', proxy_owner.age])
    end
  end
end

When to make a model active

If there is no user interface for adding, removing, or managing data, there is no need for an active model. A denormalized column populated by a hash or array of possible values is fine.

This is really just the application of the KISS principle, Keep It Simple Stupid, but I have never seen it as clearly described before reading this book.

Haml []

A nice feature of Haml that I didn’t know about, is the [] operator. When given an object, such as [record], [] acts as a combination of div_for and content_for, outputting a tag with the id and class attributes set appropriately.

-# This Haml
%span[@team]
<!-- Results in this HTML -->
<span class='team' id='team_1'></span>

RESTful actions

When using resources in Rails there are seven methods that are used.

index, create, show, update, delete, edit, and new. The first five naturally map to get(collection), post(collection), get(singular), put(singular), and delete(singular), but what isn’t as obvious is that.

The new and edit actions are really just different ways of representing the show action.

This is of course obvious when you think about it, but once again Chad and Tammer has written it down in plain simple English.

Rake Tasks

How should you treat your application specific Rake tasks on order to test them easily. Once again the solution is very simple.

Write the domain specific code as a class method on the appropriate model associated with the task.

Then all you have to do is call the method from the task.

task :fill_bar_with_ingredients do
  Bar.fill_with_ingredients
end

It is not always appropriate to add this functionality to the existing models. This is a clue that another model is needed in your domain.

task :fill_bar_with_ingredients do
  LiquorStore.order_ingredients
end

Database Index

Since most applications have far more reads than writes, you should add indexes to every field that appears in a WHERE clause or an ORDER clause. You should also add indexes for every combination of fields that are used that are combined with AND.

As always, don’t follow this advice blindely, if a table only has three rows then perhaps the index is overkill…

Conclusion

Apart from these tips, there are tons of other useful information, making this book a must-read if you are doing Rails development.

Tuesday, November 10, 2009

Adrenaline Junkies and Template Zombies

Since I had plenty of time to read on my flights back and forth to OOPSLA, I managed to read through a few books. One of them was Adrenaline Junkies and Template Zombies by Tom DeMarco et al. Being the sceptic that I am, my attitude when starting to read this book was: "Yeah, I know a lot of people has praised this book and I know that Tom DeMarco has written Peopleware, but what the hell do these bozos know anyway!" ;)

I figured that the six of them could probably scrape together a few decent people patterns, but I am a bit fed up with the whole pattern template style, so my expectations were not as high as they should have been.

Anyway, the book is amazing, the pattern template is really lightweight, basically, a name, an image, a statement, and a story. And the stories, are good. The authors have a remarkable ability to observe human nature and also the ability to write about what they see.

Some Patterns

The book contains 86 patterns, most of them are negative since they are funnier, as one of the authors said on a podcast.

Dead Fish

A dead fish is a project, that every one knows is impossible to start out with, but nobody says anything since the culture in the company is that way. If you say something you may get responses like,

Prove it! Prove that it is not feasible that this project will succeed!

Or,

Are you a weenie or a layabout?

Projects like this are usually worked on until it is inevitable that they will be late, and then everybody acts surprised.

Nanny

A nanny is a project manager that is aware of the capabilities of her staff and nurtures them and lets them at their peek. The nanny is responsible for improving her staff and make responsible project citizen of them. A nanny enables workers to do their job.

Eye Contact

If your life depended on a project, would you want them working close together or in different corners of the world? Human communication goes way beyond words, and it is foolish to think that it is possible to work at full speed with people who don't know each other and live in different places.

Dashboards

A dashboard is a highly visible board, that enable the project members and others to get an instant view of the status of the project. It can be a web page or a board on the wall. What is significant with a dashboard is that it is updated as soon as anything important happens in the project. All project members care for the dashboard since that is the place where they can find out how they are doing. Dashboards contain just the right amount of data.

Film Critics

A film critic is a project member or someone related to the project who thinks that they can succeed even if the project is a failure. They may often have good points, but usually when it is too late to do something about it. It is no use to have a person like this on the team, since they are not really on the team if they don't go down with the ship.

Natural Authority

The word authority have several meanings. The meaning of an authority is a person who knows a great deal about something. Another meaning, in authority, is a person who is in charge. A person who is an authority and in authority is a natural authority. This is the healthy pattern.

The White Line

The white line is the line on a tennis court. The line is a clear signal if the ball is in or out. Occasional dispute may arise over a questionable judgment call, but the line is respected by everyone. Most projects don't have this line. Create a white line for your project so that you know what is inside the project scope and what is not.

Silence Gives Consent

If someone don't oppose an idea, it is, usually, taken as consent. Especially from people who come from different working areas, like management and programmers. Silent consent is not good for anyone, because nobody is sure what has been decided and what has not. A way to remedy this problem is to keep a list of commitments where it is written down who has promised who what. The Scrum sprint backlog is similar to such a list.

Time Removes Cards from Your Hand

The earlier a decision can be made, the better. If you know that a project will not make a deadline, the decision to change the scope should be made as early as possible, since that will allow the team to work on the most important features first. If a decision is delayed until it is too late, the decision is made implicitly by time.

Rhythm

Instead of being daunted by overwhelming tasks, projects with rhythm take small, regular steps thus establishing a regular beat that carries them toward their goal.

This journey of a thousand miles begins with a single step --Lao Tzu

False Quality Gates

False quality gates are quality checks that don't do anything to promote the quality of the project. It is a sign that more attention is concentrated on format, rather than content. It can be a glossary of terms with the wrong content or a word template where most of the sections are filled in with the words "This section must contain text to fulfill company guidelines".

Testing Before Testing

Testing before testing refers to the practice of thinking about how to test a feature at the same time you think about how to implement it. If it cannot be tested how can you know that it does what you say?

Cider House Rules

Cider house rules are rules written by someone unconnected to the project. Rules like this, that give no apparent value, are a burden to the project and therefore often ignored.

Nobody pays attention to them rules. Every year Olive writes them up and every year nobody pays any attention to them. -- John Irving, The Cider House Rules

Talk Then Write

The team makes decisions during conversation, and then immediately communicates the decisions in writing. This is a really important pattern that it is easy to forget!. A common place where this kind of decisions are written down is very helpful.

Practicing the End Game

A team that does not release often and regularly will often take a long time to make a release. The act of releasing a product should be practiced often so that is becomes a natural part of the project.

Data Quality

Data quality often sucks! A common solution is often to attack the problem with technology instead of putting in the manpower that is actually needed to improve the quality of the data. Company web-sites are the prime example of this. They are often full of completely useless information.

Undivided Attention

Complex work is hard and it requires undivided attention to be performed properly. Splitting people's attention over multiple project will severely hinder their performance.

By doing two things at once, you've cut your IQ in half, and believe me, those 40 points can really make a difference. -- Dale Dauden, The New York Times

Orphaned Deliverables

Orphaned deliverables are deliverables that no-one values enough to pay for. Always make sure that there is a sponsor for every artifact that you are developing.

Hidden Beauty

Hidden beauty inside a program, that little extra thing, that may seem unnecessary, is what shows that the creator cares about his work. It is not unnecessary! This caring is what separates a quality product from garbage.

I Don't Know

If you are afraid of saying the words, "I don't know!", you are probably working in an organization where saying it means that you will be taken for a fool. In a healthy organization, "I don't know!", means that you don't know, but you will in a while, if it is important enough.

Loud and Clear

Having a clear goal, that everyone agrees to, is vital to a project. Clear goals allows you to focus the project activity if it starts to move away from its purpose. A PAM statement, that contains the Purpose, Advantage, and Measurements of a project is very helpful.

Conclusion

The patterns described above are just my short summaries, and I don't do them justice, but hopefully I have awoken your interest in this wonderful book.

It made my top-ten list and I recommend it to everyone from programmer to president. I like that the authors don't always provide a solution, but instead just describe the way they see it, it is up to you to figure out a solution to the problem yourself.

Saturday, October 25, 2008

TDD and LINQ to SQL

Microsoft has made the unfortunate mistake of not making System.Data.Linq.Table<T> implement an interface. If they had only done this it would have been easy to mock out the Persistence Layer when using LINQ to SQL.

Since it is a class and a sealed one at that, this is not an available path for TDD. What to do? If we can’t implement it we can adapt it. What is required for this to work is two interfaces: IUnitOfWork and ITable<T>, two classes LinqToSqlUnitOfWork and LinqToSqTable<T> and for testing purposes two additional classes InMemoryUnitOfWork and InMemoryTable<T>.

ITable<T> looks like this. I usually only include the methods that I need and add more by need.


   public interface ITable<T> : IQueryable<T> where T : class
    {
        void Attach(object entity);
        IQueryable<TElement> CreateQuery<TElement>(Expression expression);
        IQueryable CreateQuery(Expression expression);
        void DeleteAllOnSubmit(IEnumerable entities);
        void DeleteOnSubmit(T entity);
        object Execute(Expression expression);
        TResult Execute<TResult>(Expression expression);
        void InsertAllOnSubmit(IEnumerable entities);
        void InsertOnSubmit(T entity);
    }

IUnitOfWork looks like this with one accessor method for every aggregate in my domain model. I have only included SubmitChanges in the interface but it is entirely possible to include all the methods of DataContext here if you have the need for it.


   public interface IUnitOfWork
   {
       ITable<Player> Players { get; }
       ITable<Round> Rounds { get; }
       void SubmitChanges();
   }

LinqToSqlUnitOfWork looks like this. Every method wraps the sealed Table<T> in a LinqToSqlTable<T>.


public class LinqToSqlUnitOfWork : IUnitOfWork
{
     private readonly LinqToSqlDataContext dataContext;

     public LinqToSqlUnitOfWork(LinqToSqlDataContext dataContext)
     {
         this.dataContext = dataContext;
     }

     public ITable<Player> Players
     {
         get { return new LinqToSqlTable<Player>(dataContext.GetTable<Player>()); }
     }

     public ITable<Round> Rounds
     {
         get { return new LinqToSqlTable<Round>(dataContext.GetTable<Round>()); }
     }

     public void SubmitChanges()
     {
         dataContext.SubmitChanges();
     }

 }

The next class need is LinqToSqlTable<T>. As shown above the constructor takes a Table<T> as a parameter. All actual work is delegated to the Table<T>.


public class LinqToSqlTable<T> : ITable<T> where T : class
{
    private readonly Table<T> table;

    public LinqToSqlTable(Table<T> table)
    {
        this.table = table;
    }


    public void Attach(T entity)
    {
        table.Attach(entity);
    }

    public IQueryable<TElement> CreateQuery<TElement>(Expression expression)
    {
        return ((IQueryProvider) table).CreateQuery<TElement>(expression);
    }

    public IQueryable CreateQuery(Expression expression)
    {
        return ((IQueryProvider) table).CreateQuery(expression);
    }

    public void DeleteOnSubmit(T entity)
    {
        table.DeleteOnSubmit(entity);
    }
    ...

Finally we have the InMemory classes. InMemoryUnitOfWork works similarly to SqlToLinqUnitOfWork creating InMemoryTables that implement the ITable<T> Interface. The SubmitChanges method is left as an interesting exercise for the reader :)


public class InMemoryUnitOfWork : IUnitOfWork
{
    private readonly ITable<Player> players;
    private readonly ITable<Round> rounds;

    public InMemoryUnitOfWork()
    {
        players = new InMemoryTable<Player>();
        rounds = new InMemoryTable<Round>();
    }

    public ITable<Player> Players
    {
        get { return players; }
    }

    public ITable<Round> Rounds
    {
        get { return rounds; }
    }

    public void SubmitChanges()
    {
        //TODO
    }
}

In its simplest form the InMemoryTable<T> just uses a List<T> as storage, delegating all possible functionality to the list. A lot of methods are left out for brevity.


    public class InMemoryTable<T> : ITable<T> where T : class 
    {
        private readonly IList<T> list;
 
        public InMemoryTable() : this(new List<T>())
        {
        }

        public InMemoryTable(IList<T> aList)
        {
            list = aList;
        }

        public IEnumerator<T> GetEnumerator()
        {
            return list.GetEnumerator();
        }

        public Expression Expression
        {
            get { return list.AsQueryable().Expression; }
        }
   ...


This simple wrapper gives me the ability to create repositories for my classes that work for both LingToSql and with in memory collections. Here is an example:


public class RoundRepository
 {
     private readonly IUnitOfWork unitOfWork;

     public RoundRepository(IUnitOfWork unitOfWork)
     {
         this.unitOfWork = unitOfWork;
     }

     public IQueryable<Round> Rounds
     {
         get { return unitOfWork.Rounds; }
     }

     public void AddRound(Round round)
     {
         unitOfWork.Rounds.InsertOnSubmit(round);
     }

     public void ClearRounds()
     {
         unitOfWork.Rounds.DeleteAllOnSubmit(unitOfWork.Rounds);
     }

     public IEnumerable<Round> ByYear(int year)
     {
         var rounds = from round in Rounds
                      where round.PlayDate.Year == year
                      select round;
         return rounds;
     }
 }


This gives me the ability to test my domain classes at the relatively small cost of six new classes and interfaces. It also allows me to use the same test code for both unit testing and integration testing. Not bad for a days work :)

Friday, May 16, 2008

Patterns of Software

Patterns of Software (PDF) is an essay collection written by Dick Gabriel. The collection is, like software patterns, based on the work of Christopher Alexander. It is more a thoughtful analysis of Alexanders work, with comments related to software, than a practical implementation of his ideas as in the GoF-book. Please note that this is not my analysis of Alexander, whom I haven't read yet, but simply notes of Gabriels analysis of Alexander. Gabriel identifies three important concepts in software systems:

Compression - the ability to describe something succinctly by using the surrounding context. Examples are subclassing and closures. The benefit of compression is the elegance of avoiding unnecessary words that distract from the main issue. The downside is that the reader must know the surrounding context.

Habitability - the characteristic of source code that enables programmers to understand and change the it comfortably and confidently. It is related to Alexanders organic order which is defined as... "the kind of order that is achieved when there is a perfect balance between the needs of the whole and the need of the parts". If the programmers lose the sense of responsibility for the environment they live in hoe can they feel any sense of purpose there. Habitability enables piecemeal growth, small incremental modifications, a reality in software. An interesting and controversial idea on habitability is: "Habitability is not clarity. The danger of clarity is it's uncompromised beauty; it's really tough to improve uncompromised beauty. Clarity is dangerous."

Abstraction - is the thought process wherein ideas are distanced from objects. In programming the implementor of an abstraction can ignore the exact uses and the user of the abstraction can forget the details of the abstraction. Abstraction especially when it is take too far may limit the habitability of the software. It is important to keep the abstractions clear and intuitive. Abstracting is difficult and should be handled with care. Abstractions are part of the context that makes compression possible but at the cost of knowing the abstractions. Sometimes, when no good abstraction can be found, it is better to just write the common code.

Patterns

Qwan- At the heart of Alexanders pattern language was his quest for the Quality without a name, Qwan. It is interesting to note that this central idea is not mentioned at all in the GoF-book. It is as if they found it to vague to be of any interest.

Gabriel does not claim to know what qwan is but mentions things about software that possesses it. Here are a few:

  • Its abstractions and modules are not too big. They make sense for themselves; they are whole.
  • If I look at any small part I can see what is going on, I don't need to look at other parts to understand it.
  • Everything about it seems familiar.
  • I can image changing it without fear of breaking it.
  • It is like a fractal in which every level of detail is locally coherent.
Patterns and Carpets - Alexander patterns contains people and their activities, this is because the buildings are meant to be lived in. This is also true for software; it is meant to be maintained. Another aspect of Alexander patterns was that their geometrical nature was fundamental.

Alexander also studied Turkish carpets since he found a beauty in them that he could not explain. He even published a book about them. In it he says:

  • The beauty of a structure comes from the fine detail at an almost microscopic level.
  • The beauty of the color of the carpet was due to the fact that the master dyer served a 15-year apprenticeship after which he was required to produce a color no one had seen before.
  • Fanatical precision is not required. It is only important to know what is important and what is not and to pay attention to what is important.
  • To get wholeness, you must leave things that don't matter rough and unimportant and give things that really matter deep attention.
  • Every successful center is made of a center surrounded by a boundary which is itself made by centers.
The solution to a large problem is a nested set of patterns.

Failure - Another interesting thing not mentioned in the software pattern literature is the fact that Alexander failed (his own words) when he tried to implement his ideas. The building that were built did not have the quality that he had expected.

Sunday, October 22, 2006

Mexican Burrito Breakfast

A filling breakfast with fried potatos and a burrito filled with scrambled eggs, peppers, onion and spicy meat.

Pattern Languages of Programming (PLoP) with Ward Cunningham, Guy Steele, Ralph Johnson, Linda Rising, ... We sat in a room and talked about patterns that people had sent in, giving emphasis to what was good and what could be improved. A great way to learn new things. The first pattern, Mutator, was a non-pattern that could be replaced by Iterator. But the other patterns about documenting frameworks where quite interesting. The discussion gave more than the patterns themselves though. Definitely worth looking into.