Archive for category Developer

Rule 4: Use Only One Dot Per Line

This is the fourth part of a series of articles starting here.

The fourth rule of the exercise is to only use one dot per line. Why is that important? Well apart from the apparent readability increase, many dots one one line can signify that an activity is happening in the wrong place. Or maybe your object is dealing with two other objects at the same time.

In both these cases you are not fully implementing the object oriented paradigm. Objects are supposed to know something about their immediate “friends” but not about their friend’s friends.

This is an example of a quite broken implementation.

public class TimeLineObject extends UIComponent {
    ....
    public function redraw():void {
        TimeLineDrawer.theInstance.drawTimeLine(TimeLineDrawer.theInstance.timeLineCanvas);
    }
}

To follow the rule of this exercise you might be tempted to remove the number of dots per line by doing something like this:

public class TimeLineObject extends UIComponent {
    ....
    public function redraw():void {
        var timeLineDrawerSingleton:TimeLineDrawer = TimeLineDrawer.theInstance;
        var canvas:Canvas = timeLineDrawerSingleton.timeLineCanvas;
        timeLineDrawerSingleton.drawTimeLine(canvas);
    }
}

But this is hardly the point. It is very apparent in the above example that the activity as a whole is not in the correct place. In the TimeLineObject we are suddenly telling some remote singleton static object to carry out things for us. Our object knows to much and the architecture has in fact failed at some earlier point.

The example from the Thoughtworks book is excellent. It shows the correct way to think about the exercise, namely to put activities in its right place. I will quote it below. First the “erroneous” example:

class Board {
  ...
  class Piece {
     ...
     String representation;
  }
  class Location {
      ...
      Piece current;
  }
  String boardRepresentation() {
      StringBuffer buf = new StringBuffer();
      for(Location l : squares())
      {
          // Oh lord lots of dots here... :)
          buf.append(l.current.representation.substring(0, 1));
      }
      return buf.toString();
  }
}

Applying the rules of having one dot per line here actually means REAL refactoring. I.e putting stuff where it belongs. And that is usually in other classes. Here’s the refactored example:

class Board {
   ...
   class Piece {
      ...
      private String representation;
 
      String character() {
          return representation.substring(0, 1);
      }
      void addTo(StringBuffer buf) {
          buf.append(character());
      }
   }
 
   class Location {
      ...
      private Piece current;
 
      void addTo(StringBuffer buf) {
          current.addTo(buf);
      }
   }
 
   String boardRepresentation() {
       StringBuffer buf = new StringBuffer();
       for(Location l : squares())
           l.addTo(buf);
       return buf.toString();
   }
}

So, the lesson from this exercise is that you should put activities where they belong. Avoid using static utility classes and other “middleman” objects. And make sure that the object you are working in does not now to much about other object’s activities. Couple this with the previous rules and you have gone far in a sturdy, nice looking design.

Previous « Rule 3: Wrap All Primitives and Strings
Next » Rule 5: Don’t Abbreviate

  • Share/Bookmark

3 Comments

Rule 3: Wrap All Primitives and Strings

This is the third part of a series of articles starting here.

Wrapping primitives (ints, floats etc) and strings is an easy way to increase maintainability and readability of your code. Also, as Abinesh TD has commented below, wrapping expresses intent of data, preventing misuse. Consider for example the following pseudo-javacode:

public class Contact {
    private String emailAddress;
 
    public void setEmail(String emailAddress) throws InvalidEmailException {
        if (! validateEmail(emailAddress)) {
            throw new InvalidEmailException("Uhm, that's not a valid mail address...");
        }
 
        this.emailAddress = emailAddress;
    }
 
    public String getEmail() {
        return emailAddress;
    }
 
    private Boolean validateEmail(String emailAddress) {
        // TODO: validation regexp etc
    }
}

A very simple class, containing a single field intended to hold an email address. It looks good enough, but imagine that you have other places where you would need to validate and store email addresses. You would have a tendency for code duplication right there.

Worst case would be that you would have a validation function in every email container class. It would be better to wrap the string intended to hold the email address in its own class, even if it only holds one field, the potential for code reuse increases exponentially.

A better implementation could look like this:

public class Contact {
    private EmailAddress emailAddress;
 
    public void setEmail(EmailAddress emailAddress) {
        this.emailAddress = emailAddress;
    }
 
    public void setEmail(String emailAddress) {
    try {
        this.emailAddress = new EmailAddress(emailAddress);
    } catch (InvalidEmailException e) {
        // Oh lord something went wrong here... :)
    }
 
    public String getEmail() {
        return emailAddress;
    }
}

The benefits should be immediately clear. Suddenly the class EmailAddress requires the email address string to be valid to be instantiated at all. This would make it much easier to quickly zero in on bugs and also increases the potential reuse of your code.

Pretty much any variable you want to store, whether it is a primitive or a string – WILL need some sort of validation. This is a major reason for wrapping them. But other than that, consistently wrapping gives your object oriented code a higher degree of encapsulation.

Previous « Rule 2: Don’t Use the Else Keyword
Next » Rule 4: Only Use One Dot Per Line

  • Share/Bookmark

,

5 Comments

Rule 2: Don’t Use the Else Keyword

This is the second part of a series of articles starting here.

The second rule of the “Nine Ways to Better Software Today” is to stop using

else

This builds on top of rule 1, to decrease the level on indentation by again focusing on minimizing complex conditionals. Within the object oriented paradigm, polymorphism is a powerful model to handle this. Regardless of programming model,  this exercise forces you as developer to find alternatives to using the else keyword and thus considerably beautifying your code.

Consider the following Python code

def set_member_status(member, status):
    """ Spot the else keyword """
 
    if is_active(member):
        do_something(member, status)
    else:
        do_something_else(member, status)

There are several ways to simplify this method. For simple cases use early returns, as below. Early returns only work in methods which are short and lacking in complexity (keeping down the level of indentation helps with this). Once a method is long and contains many levels of abstraction, early returns can of course not be used. But by then you’ve failed at this exercise anyway.

def set_member_status(member, status):
    """ Example of using early returns """
 
    if is_active(member):
        do_something(member, status)
        return # here is the early return :)
 
    do_something_else(member, status)

In many languages it is possible to use the ternary operator. That would look something like this (in javascript):

/** Wrong */
function drowned() {
  if (boatIsFloating()) {
    return false;
  } else {
    return true;
  }
}
 
/** Right */
function drowned() {
   return boatIsFloating() ? false : true;
}

Guard clauses is another way of increasing readability. The following example is taken from here

double getPayAmount() {
    double result;
    if (_isDead) result = deadAmount();
    else {
        if (_isSeparated) result = separatedAmount();
        else {
            if (_isRetired) result = retiredAmount();
	    else result = normalPayAmount();
        };
    }
    return result;
};	
 
double getPayAmount() {
	if (_isDead) return deadAmount();
	if (_isSeparated) return separatedAmount();
	if (_isRetired) return retiredAmount();
	return normalPayAmount();
};

Previous « Rule 1: Only Use One Level of Indentation
Next » Rule 3: Wrap All Primitives and Strings

  • Share/Bookmark

,

5 Comments

Nine Steps to Better Software Design Today: Thoughtworks Exercise

There are few companies out there more exiting to me than Thoughtworks. They sport a fantastic set of values, and have some of todays most brilliant programmers and software thinkers on board. But what strikes me as most wonderful about them is the way they communicate with programmers around the world. They really have an interest in good software, whether it is their own, or somebody else’s.

On reading their book, the Thoughtworks Anthology there was one chapter (Object Calisthenics by Jeff Bay) which struck me as extremely fun to read, it contained an exercise called “Nine Steps to Better Software Design Today”. An exercise completely focused on object oriented design quality with all that that entails, like encapsulation and appropriate use of polymorphism.

It is really a very simple exercise in many aspects, it simply provides nine rules, and asks me as a developer to do my absolute best to abide by those rules. What Thoughtworks does is so ingenious. Instead of just preaching the holy grail of object oriented programming, they ask me to be a part of the sermon. On reading the whole exercise I was instantly revving my engine to actually do the exercise. So I started up a small GWT project and forced myself to actually try and comply with the nine rules.

I’ve never had so much fun programming! And the process truly changed the way I will write code from now, whether it is in a purely object oriented language or not.

Said and done. I will start with the first rule:

Rule 1 : Use only one level of indentation per method

No matter which language you are working with, this is something that is very important. Check out the class, that thoughtworks uses as an example, below. It contains one function with several levels of indentation.

class Board {
  String board() {
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < 10; i++) {
      for (int j = 0; j < 10; j++)
        buf.append(data[i][j]);
      buf.append("\n");
    }
    return buf.toString();
  }
}

Now consider that after some refactoring the code could look like this:

class Board {
 String board() {
  StringBuffer buf = new StringBuffer();
  collectRows(buf);
  return buf.toString();
 }
 
 void collectRows(StringBuffer buf) {
  for (int i = 0; i < 10; i++)
   collectRow(buf, i);
 }
 
 void collectRow(StringBuffer buf, int row) {
  for (int i = 0; i < 10; i++)
   buf.append(data[row][i]);
  buf.append("\n");
 }
}

What basically has happened here is that methods have been extracted for each level of indentation. The whole class is so much more readable, unit testable, understandable… you name it. Or as the authors of the chapter puts it:

Try to ensure that each method does exactly one thing. One control structure, or one block of statements per method. [Heavy indentation] in a method [is] a signal that you’re working at multiple level of abstraction, and that means you’re doing more than one thing.

Working with methods that do exactly one thing, and classes doing exactly one thing, your code begins to change, [...] increasing exponentially the level of reuse.

Next time I will talk about rule 2: Don’t use the else keyword :)

  • Share/Bookmark

,

4 Comments

A search on search widget

I’ve been wishing for a Wordpress widget that would help visitors find more blog content relevant to the search engine terms that got them to the blog in the first place. Maybe I’m just bad at googling or something, because I haven’t found one.

Now I’m writing my own widget, called “Search on search”. If you arrive at this blog from a search engine link you might see a section for it in the sidebar. If, not, and you’re curious you could force it by trying this search:

And then in the Google results find a link going to this site. (The widget doesn’t appear if it can’t figure out the search engine terms.)

You can find the widget code as a gist on Github, namely here:

It’s not rocket surgery. The main job is about figuring out what search engine terms, if any, that the user used to find the blog. But I didn’t need to solve that one either. Istanto had already solved it for me. =)

I still have a bug to iron out: The links presented doesn’t get styled like the other lists. I can’t figure out why… Feel invited to help me!

Update 17 January: The plugin is now available in the Wordpress.org plugin directory:

  • Share/Bookmark

, ,

2 Comments

Flickr Searches in 3D

I’m experimenting with tying that 3D Album I mentioned earlier to Flickr Searches. Looks like this for now
ThreeDeeGallery.swf
Work in progress, both the app and this blog post.

  • Share/Bookmark

No Comments

So you wanna be a front end developer?

Back in the day when I was a young boy in the big IT-industry I wanted to become the greatest front end developer the web had seen. Due to circumstances, out of my hands of course, I did not reach my goal, but I did get to “know” some great ones along the way!

So I guess you possibly have some schooling to bring to the table, or you have been working with back-end stuff stuff for quite some time, you know what object oriented programming is or at least want to learn, and most importantly you have the will to learn!

When I started to become really interested in front end development back in the late 90’s, front end development was not looked upon as real programming, real programming was C++, Java and the likes. But now, we have job titles like Senior Front End Developer at for instance Yahoo and Google, so I guess that the understanding of the importance of good front end code has really elevated.

So my way of learning the craftsmanship, was to study the masters below, downloaded their code, read it, and then write my own! If it worked for me, I’m sure it will for you!

Scott Andrew LePera
What really got me started was a guy named Scott Andrew LePera(http://www.scottandrew.com/). He got me all warm and fuzzy talking about for instance event handlers in javascript and how event bubbles

Aaron Boodman
After that I stumbled over Aaron Boodman, the youngpup (and creator of Greasemonky among things) showed me all about how to create the menus that we love to have, how to make the Javascripts run smooth in animations, and how drag of elements shall be done. Back in the beginning of the 2000 he had the coolest UI on his blog, and nothing I have seen since has turned me on as much as viewing youngpup.net for the first time(except possibly 13thparallel)!

13thparallel
13thparallel made me think about coding for portability, introduced me to the concept of the Viewport among other things.

WebFX
Emil A Eklund and Erik Arvidsson at WebFX showed me that it was possible to create a forum on the web with outstanding functionality and speed(unfortunately it only looks good in MS IE), how to work with XML in advanced Javascript.

Peter-Paul Koch @Quirksmode
Quirksmode helped me really understand the differences between browsers and what do do about it. He also really introduced me to Unobtrusive JavaScript.

Remember that most of the examples above have been written back in 2001-2002, and they still work..What does this tell us, well to use the standards, and no browser specific hack, because browsers change and you will end up chasing your own tail to make things work in new browsers.

  • Share/Bookmark

No Comments

Rails deploy using sqlite3

I had a hard time figuring out why, when reading up on capistrano, I couldn’t find any info on how to deal with the database file. That was until I realized most people don’t deploy on sqlite3. With mysql and other databases you have a server and it’s automatically “shared” then.

The only information I found on deployment on sqlite3 was an excellent deploy script in this blog article. Basically, using sqlite3 you have to make sure the database is in a shared directory across releases. But the sqlite3 parts of that deploy script didn’t work for me as they were. I had to make sure I referenced the shared database path all the way or I risked overwriting my database with a symlink. Below are the sqlite3 parts of the resulting capistrano script.

Setting up the shared database path. NB: Lazy binding. Important if you’re using multistaging from capistrano-ext.

set(:shared_database_path) {"#{shared_path}/databases"}

Sqlite3 tasks.

namespace :sqlite3 do
  desc "Generate a database configuration file"
  task :build_configuration, :roles => :db do
    db_options = {
      "adapter"  => "sqlite3",
      "database" => "#{shared_database_path}/production.sqlite3"
    }
    config_options = {"production" => db_options}.to_yaml
    put config_options, "#{shared_config_path}/sqlite_config.yml"
  end
 
  desc "Links the configuration file"
  task :link_configuration_file, :roles => :db do
    run "ln -nsf #{shared_config_path}/sqlite_config.yml #{release_path}/config/database.yml"
  end
 
  desc "Make a shared database folder"
  task :make_shared_folder, :roles => :db do
    run "mkdir -p #{shared_database_path}"
  end
end

Hooks (or whatever they’re called, I’m new to all this).

after "deploy:setup", "sqlite3:make_shared_folder"
after "deploy:setup", "sqlite3:build_configuration"
 
before "deploy:migrate", "sqlite3:link_configuration_file"

Hope this helps someone. Please don’t hesitate to ask should something need more explaining. And of course suggest improvements. This is all the makings of a capistrano newbie.

  • Share/Bookmark

, , ,

1 Comment

Submitting iPhone app to App Store

Finally, after two bounces and three weeks of waiting, our first app on App Store is available!

I’ll keep this post really short!

Pros

  • Great testing by the App Store review team.
  • Good and thorough feedback.
  • Cons

  • Time consuming! But, reasonable considering the amount of apps that is submitted to the App Store.
  • iTunes Connect
  • Some good to knows!

  • It takes approximately 5 working days before you hear anything from the review team.
  • If you reject (developer reject) your application and post a new version when an app is undergoing a review, then you will have to wait another 5 more days.
  • Conclusion

    The App Store review process: 4 stars out of 5

    Projectplace for iPhone

    If you are curious about our iPhone application, please visit our app section @ App Store.

    • Share/Bookmark

    , , , , ,

    3 Comments

    Stopp Internet Explorer’s CTRL – MouseWheel

    As a Flex developer I come in contact with all sorts of problems when I run my applications in Internet Explorer 7. One of the most annoying ones is the one where CTRL – MouseWheel will resize the Flex application area itself, even when the application is scaled to 100% * 100% of your browser window and has focus. This is impossible to accept and here is the solution to the problem.

    Assuming that you’re working with Flex Builder, all you have to do is edit the index.template.html file a little bit. Such that it contains the following JavaScript.

    function catchCtrlMouseWheel()
    {
        if (window.event.type == "mousewheel" ) 
        {
            if (window.event && window.event.wheelDelta ) 
            {
                return window.event.ctrlKey ? false : true;
            }
        }
     
        return true;
    }

    And in the <body>-tag:

    <body onmousewheel="return catchCtrlMouseWheel()">
    • Share/Bookmark

    , , ,

    No Comments