Isolate CSS

(crosspost from my apprenticeship blog)

Hiding details is generally a desirable goal when developing software.

The purpose of hiding details is to increase the cohesion of parts in our software, as well as to decouple them better from each other via well defined interfaces or boundaries.

This is a well known approach when it comes to isolating ourselves from external dependencies in our code. But why only apply it for code we write for the back-end? The same abstraction principles apply no matter what external dependency we want to isolate ourselves from.

So it can and should be applied to any CSS framework we use. No matter whether we’re using Bootstrap, Pure, Less, Blueprint, 960, …

Our applications should not have any direct coupling to an external framework. There should be no CSS classes directly used that were not defined by us for our project.

For the example code I will use Yahoo!’s Pure framework. But the principles apply for any framework.

Pure provides pure-g classes to create a grid, and several pure-u-* classes as units/columns within these grids.

A grid with two buttons next to each other can be defined like this:

<div class="pure-g">
  <div class="pure-u-1-2">
    <a class="pure-button" href="/">Back</a>
  </div>
  <div class="pure-u-1-2">
    <a class="pure-button" href="/game/restart">Restart</a>
  </div>
</div>

As we can see there are many references to the classes defined by Pure. By that we have coupled the view directly to the framework we use.

Directly coupling to a framework is not always a good approach. Sounds familiar? Maybe that’s because whenever something like this happens in for example Ruby code, many developers immediately react with some sort of hesitation by introducing such a tight coupling. But even for CSS the same abstraction and isolation principles apply.

The view belongs to our application. And therefore we should isolate any external dependency from that.

It would be better if we could write the previous code in a manner that we are in charge of what CSS classes the elements use.

Something like this:

<div class="grid-container">
  <div class="half-width">
    <a class="button" href="/">Back</a>
  </div>
  <div class="half-width">
    <a class="button" href="/game/restart">Restart</a>
  </div>
</div>

This does a better job at expressing the intent of what the HTML is supposed to do.

  • Instead of pure-g we use grid-container, because that’s what pure-g really is.
  • Instead of pure-u-1-2 we use half-width, because pure-u-1-2 is really just a div that spans half of the width of its parent element.
  • And instead of pure-button we use just button, because … well it’s just a button.

How to achieve CSS isolation?

I used Sass to be able to use the CSS classes just shown. Using Sass allows to “extend” new selectors from existing selectors.

With this we can create new selectors for our views that match the domain of the application we’re developing.

The definition for the classes of the last example look like this:

div.grid-container {
  @extend .pure-g;
}

div.half-width {
  @extend .pure-u-1-2;
}

a.button {
  @extend .pure-button;
}

Sass will create the classes with the appropriate content for us. So div.grid-container will have the same declarations as .pure-g has.

This is not only possible for single classes, though. Also multiple usages of classes can be merged together.

A button that is coloured in Pure’s primary colour is declared like that for example:

<button type="submit" class="pure-button pure-input-1 pure-button-primary">Play!</button>

With a SCSS declaration like this:

button.play-game {
  @extend .pure-button, .pure-input-1, .pure-button-primary;
}

We are now able to declare the button with better expressed intent:

<button type="submit" class="play-game">Play!</button>

What does that tell us?

By isolating from the CSS framework we do not couple our views to any specific framework anymore.

When we want to switch to another framework, we do not have to update all the views. We only have to update the abstraction layer between our views and the framework. And in this case, the abstraction layer is the SCSS file. It’s likely to be easier to maintain just that file instead of finding all usages of framework specific CSS classes across all existing views.

If there’s one thing to take away from that: Isolation principles are valid for every area in our applications.

(apprenticeship)

(crosspost from my apprenticeship blog)

To support the ideas from my last post about inversion of control, I want to demonstrate some of the things mentioned with code examples.

Hidden Assumptions

One thing that were subtly hidden in my Game implementation was, that it had the inherent assumption of blocking players. So the game loop didn’t run endlessly but blocked naturally whenever a move from a human player was requested.

Imagine something like the following setup:

class Game
  # other parts left out for brevity

  def play_next_round
    place_move_of(next_player)
    switch_players
  end
end

And a client of Game could implement a game loop like this:

while game.is_ongoing?
  game.play_next_round
end

At this abstraction level the flaw isn’t directly visible. Looking more into place_move_of() though, reveals more information:

def place_move_of(player)
  move = player.next_move(board)
  board.set_move(move, player.mark)
end

The interesting part is the call to player.next_move(board) here. Imagine now player being an object of class HumanPlayer that is defined as follows:

class HumanPlayer
  attr_reader :mark, :input

  def initialize(mark, input = $stdin)
    @mark = mark
    @input = input
  end

  def next_move(board)
    input.gets.to_i
  end
end

There is a small abstraction for what can be treated as an input for the human player. At the time of writing that, I only had a terminal UI in mind, therefore using $stdin as the default input mechanism seemed reasonable. Any input object that responds to gets could be used. Injecting this dependency made it easier to test. But that’s not the most interesting thing about it.

Remembering the while game.is_ongoing? game loop from earlier shows that the loop will be naturally stepwise executed due to the blocking nature of $stdin.gets.

Everything was fine until a new UI has been introduced. An event based GUI.

Blocking IO and event based GUIs

Most graphical user interfaces are event driven. Controls/widgets emit events and other parts “listen” to these events. An example for that would be when a user clicks on a button. This click emits an event (e.g. click, or buttonClicked, or whatever the framework calls an event like that). Anyone/anything that wants to do something when that particular button has been clicked needs to register itself as a listener for that event. How that is done is different for every framework. Qt for example uses signal and slots for that, where an event is a signal, and a slot is a piece of code that gets executed when that signal is emitted. You connect a slot to a signal by calling connect() and passing the appropriate parameters of what slot will be executed by which signal. Java has event listeners that can be added to an object that is capable of emitting events. For a button object that can be done with attachActionListener().

All of these events can happen asynchronously. So there is not a real order or sequence going on when a listener will be executed. (Well, technically there is some sort of scheduling going on, but I’ll skip that for the sake of this blog post.)

Blocking IO and responsive UIs

What does that mean for the Tic Tac Toe game loop?

Having the existing HumanPlayer implementation in mind, a GUI can not (read: should not) wait until a human player clicks a button to place a move. Not even mentioning how you would need to bend a fake $stdin version to respond to gets and inject it into HumanPlayer. Even if you would introduce a fake $stdin to handle gets, there’s still the question from where do you get the actual move the player wants to play?

By the nature of how GUIs work, if the call to gets is a blocking call, you are not able to click a button to actually provide a new move. Sounds not like a valuable approach.

A Way Out

One way out of this is to not constantly keep asking a player to provide the next move. So the game loop in the GUI can still look like we’ve seen before:

while game.is_playable?
  game.play_next_round
end

The one thing that changed is a call to is_playable? instead of is_ongoing?. At that time I’m not interested anymore if the game is ongoing, but whether it can be actually played (i.e. the next player can provide a move).

So is_playable? looks like that:

def is_playable?
  is_ongoing? && is_ready?
end

def is_ready?
  next_player.ready?
end

A player object can now be asked whether it is ready or not (the HumanPlayer class has been extended at this point). Ready means if it can provide a new move. If the object can not provide a move the game loop ends.

So when the game loop asks the human player if it is ready, it will return false from that method, because the user has not clicked a button to choose a move yet. The game loop does not block on that call anymore and because the player is not ready the loop itself ends too. This leaves a fully responsive GUI.

But how do we get into the game again? Because the game is not over yet (just in a paused state), it is the user who triggers the next round by clicking on a button. Then this button click sets the value of the next move in the human player object. After that, it triggers the game loop again, which asks the player object if it is ready again. And this time it is, because the value has been set just before. So the game loop can run again just fine. Until the next move of a human player is requested. I left out the details of the HumanPlayer class by intention. How the value for the next move is not as important as the concept itself (for example in my implementation there is even another object involved that the HumanPlayer asks for the next move).

This cycle is done until the game is over (by having a draw or a winner).

Conclusion

All code examples aside, what I wanted to demonstrate is the inversion of control that happened between the game and its players.

Instead of having the Game as the main object responsible for program control, this control has been given to “the outside world” of a game.

In the first version the game asked a player for the next move and waited until that player has made a decision. It was always the game that was in charge.

This has been changed now to as soon as the game realises it can not go on any further (i.e. a player has to provide a move), it gives up the control and leaves it up to its client to trigger the next round(s) again. The client in this case is for example either the command line runtime or a Qt application.

(apprenticeship)

(crosspost from my apprenticeship blog)

One task I had in my last iteration was to decouple my Tic Tac Toe game from any UI specific behaviour. The general game rules should apply for whatever interface you’re playing the game through.

Rules of the Game

Thinking about it, it’s not that hard:

1. As long as the game is not over
2. ask the next player for its next move
3. place the move on the board
4. switch players
5. goto 1.

I call these the Four Rules of Simple Gameplay. Just kidding.

But they really are relatively simple rules. Not a single one of them mentions any specific behaviour depending on whether the game is played via a terminal, a GUI, a web interface or any other “delivery mechanism”.

That’s the way it should be. Unfortunately, my last version of the game wasn’t designed like that at all.

Terminal specific game behaviour

I thought, I had abstracted away from the actual display of the game, but in reality I hadn’t (at least I got rid of the blocking loop in the game itself a long time ago).

Due to the nature of a terminal UI, there is blocking IO going on when playing the game. So it pauses naturally when asking for the next move by waiting for user input. That eases the initial development of the game loop itself, yes. But it also hides an important fact about the game logic itself.

It basically relies on actively blocking the whole game until a user has made a move. That’s not that bad in general. But with an UI agnostic design in mind it just doesn’t cut it. Event driven UIs (as is Qt for example) don’t work like that. You can’t just block the whole UI process until the user may click somewhere in the UI. Well, technically you could, but that’s not the point. Nobody like non-responsive UIs.

Getting out of the loop (no pun intended)

One way to get around that is actively polling the user for its next move. So there’s still some looping going on, but the UI could still be responsive. The whole concept of polling in an UI environment doesn’t really appeal to me (who likes burning CPU cycles?), so I won’t dive further into that.

Just give up! (pun intended)

By “give up” I mean giving up the control. (In the game. Don’t get me wrong.)

So when the game comes to the point where it needs to request something from a user, it should give up the control of “being the active part of the game and requesting things”. By just accepting the fact that the game can’t do anything until the user is ready for it, we invert the control of the gameplay. The game is done at that point, and when a user has some input for the game, it’s the user who will trigger the next round with its move.

I call this Hakuna matata driven development. Again, just kidding.

But there is some truth in it. It is not the more widely known idea of Inversion of Control as in the sense of the Hollywood Principle, but it is still an inversion of program flow control.

It’s the user who triggers the next round, not the game asking for the next round.

Food for thought

I wonder, though, if all of this would have been easier if you would just assume an event driven UI from the beginning of a project. I could imagine – though, haven’t tested it – that it’s easier to adapt a terminal UI to an application that has isolated itself from any UI specific eventing, than it is to adapt an application that started with an abstraction of a terminal like UI.

(apprenticeship)

Creating a Ruby Gem

(crosspost from my apprenticeship blog)

Today I extracted a separate gem for the core Tic Tac Toe game logic. Up to now, the game itself with all its logic and collaborators was inside one project together with the terminal UI as well as the Qt UI.

Now there is a gem with the core logic, and that gem is used by the existing project that contains the different UI implementations only.

Creating the gem itself was relatively easy. Just executing bundle gem tictactoe and moving the existing files into the appropriate folders. Adjust tictactoe.gemspec with some description values. Done. Well… almost. It also forced me to finally use a proper namespace/module hierarchy for the game. Which is a good thing anyway, as I clearly should have done that earlier. There was just no real need for it yet.

Having the overall game(s) now split into two parts lead to another issue: shared examples were not directly available anymore for the UI project.

There are some ways to configure the gem accordingly. I came up with three possible ways:

1. Put everything needed under lib

This could be done relatively easy. But it felt wrong placing test specific classes into lib. After the gem would have been required in another project, the difference is not noticeable, whether the exported artifacts were placed in lib from the beginning or not.

An example .gemspec file would then just include the regular lib directory:

Gem::Specification.new do |spec|
  # ... other settings left out for brevity
  spec.require_paths = ["lib"]
end

But the very idea of placing code from spec into lib scared me enough to not do it this way.

2. Export whole the spec directory

Another way would be to just include the spec directory in the require_path setting of the gem.

Gem::Specification.new do |spec|
  # ... other settings left out for brevity
  spec.require_paths = ["lib", "spec"]
end

The drawback of this is, that all test files and classes from the spec directory will be available for every client of the gem. Even when you ignore the fact that this would increase the total file size of your gem, it also just pushes unnecessary code to every client of the gem.

3. Export parts of spec

The third option includes adding just enough additional files to require_paths so that clients of the gem get what they’re really interested in.

Gem::Specification.new do |spec|
  # ... other settings left out for brevity
  spec.require_paths = ["lib", "spec/helpers"]
end

I placed the shared examples and helper class in spec/helpers/tictactoe. To keep the namespacing behaviour intact the tictactoe subdirectory is needed. Since require_paths includes spec/helpers now, everything below that should have the proper namespace to not pollute any client’s load path.

This makes it possible that, as a client of the gem, you do not need to be aware that these files are loaded from a directory that is not the gem’s lib directory originally.

It’s sufficient to require the shared examples like this:

require 'tictactoe/shared_examples'

So for any client the world is good now.

There is one downside though. In the specs for the gem itself, the path for require can not be written like in the example above. In the specs of the gem, you need to be aware that the file comes from a directory called helpers. The require calls in the gem’s spec_helper show that:

require 'helpers/tictactoe/board_helper'
require 'helpers/tictactoe/shared_examples'

You could probably get around that with some $LOAD_PATH adjustments, but for the moment it didn’t felt so bad to leave it as it is. It’s a relatively focussed place where the path is specified like that – only in the spec_helper. If I find myself having the need to specify that path in multiple places in the future, I might change the path handling then.

(apprenticeship)

Sprinkling Some Coaching

(crosspost from my apprenticeship blog)

I had the chance to join my mentor for some coaching sessions at a clients site for three days. It was good getting out of our office and be in a completely different environment for a few days. Not that I don’t like our office… but still.

The client uses Java, and even though it’s been a while since I used Java in a professional environment the last time, coming back to it wasn’t as hard as I thought it would be. Admittedly, I practiced some Katas before we went there, just so that I get more familiar with the language again.

During the days we were there, I paired with one of the developers there on a very focused/isolated problem. Which was good, because I’m not fully aware of all the moving parts of their architecture. And Java architectures can be intimidating.

However, being able to focus on a relatively narrow problem helped to concentrate on the problem itself, without worrying too much about the environment it will be used later on. It was also helpful so I could help the developer explain general OO and testing practices and not have the need to bring in too much framework dependencies.

For the first two days we spent most of the time developing a few small classes that have limited responsibilities, but therefore were easy to test.

While writing the acceptance criteria for the complete feature we realised we missed one detail in the implementation of one class. So we paused the acceptance test definition, wrote another unit test, made it green and went back to the acceptance test again.

Then, when we had all the little parts ready, we put them together and our final acceptance test was green without the need to “fix” any implementation.

Seeing it coming all together at the end and just work never gets old.

(apprenticeship)

Rails Project Retrospective

(crosspost from my apprenticeship blog)

For about five weeks now I’m working together with another apprentice on an internal Rails application. Being tasked with a completely new framework and working environment, I wanted to share some of the experiences I made during that time.

That application was the first project I’ve done at 8th Light that was not a personal apprenticeship application. Like Tic Tac Toe for example, where we may pair on some stories with other apprentices but working just in our personal codebase/repository.

So being together with other apprentices on the same codebase felt really good. We had good conversations about the features we need to implement. And with the comments in the pull requests I definitely learned a lot. It’s great having a completely fresh pair of eyes looking at the changes you committed. Sometimes there are things that just slip through while pairing on a feature. So this is definitely a plus.

Having a six hour time zone difference between the team members is unfortunately something that can be hard at times. Communications between team members can take a while with a time difference like that. That’s something every team member needs to be aware of and try to not waste too much time during discussions.

That’s especially true for situations where a discussion needs to be settled. I prefer talking directly to my colleagues when I feel there’s something that needs to be resolved. Asynchronous communication via e-mail or instant messengers just don’t help at all. So I’ll keep that in mind for me should it happen the next time. Then I’ll probably just call the person directly and discuss the matter – if the local time of both persons allow it, of course. I didn’t run into problems where I would have needed to call someone in the middle of their night to hit the red button…

The transition phase into the new project was a bit rough for me though. Having never worked with Rails before, I felt lost in the codebase at least for the first two iterations. Granted, it’s not rocket science working with Rails (I know that now). But having a feature where you need to add a new view and controller and don’t know how to add and wire it up correctly is just frustrating at the beginning. You somehow know what you want to do, but you just don’t know how. But it’s all part of the learning process.

Another thing I learned is, that you shouldn’t take the existing structure of the codebase as a best practice for new features. I don’t mean that everything has to be bad that already exists, but maybe there’s a better way to do certain things. Even if similar things have been done in the application already in a certain way. The discussions in the pull requests we’re a great learning experience for that.

I’m looking forward to introduce new apprentices to the application, now that I know what is going on in the codebase.

(apprenticeship)

Counting Rails Associations

(crosspost from my apprenticeship blog)

With Rails and ActiveRecord it’s relatively easy to forget that you’re interacting with a database in the background. There are many convenience methods available to help a developer “focussing on the important things”.

Unfortunately these conveniences introduced by ActiveRecord often come with a cost – if you’re not aware of what is going on behind the scenes.

For this example I’m using ActiveRecord associations in a blogging application. There’s one table Users and one Posts.

To get the number of post of a user, ActiveRecord provides three ways to get the result.

Users.comments.count
Users.comments.length
Users.comments.size

They all return the same result but the way they are getting the result differ from each other.

Calling .count on the association triggers an execution of a SELECT COUNT... statement on the database.

Calling .length falls back to the implementation on a collection of things (like Array#length). Which means that all comments are loaded/read and then the resulting collection is asked about its .length.

When using .size the implementation used depends on whether all entries of that association have been requested before (e.g. with a call to .length or .all). If this is the case, that value will be used as the return value of .size – it will not trigger a new call to .length. If not, it will call .count.

At a first glance I thought .count would be the preferable way no matter what. A simple SELECT COUNT... will probably always be more performant than counting the elements of a list that needs to be loaded from a database.

After I had a second look though, I realised that it’s not that simple.

For cases where ActiveRecord knows the number of elements in an association already, calling .size will probably be faster than issuing a new statement to the database. Because it will just return an “already known” value.

Currently .size looks like a good tradeoff to me, because it gives you the best of both worlds. When the association has already been read completely, it uses the value that is already known. If not, a SELECT COUNT... will be executed to get the size (i.e. the count) of the association.

(apprenticeship)

Rails (Anti) Patterns

(crosspost from my apprenticeship blog)

Rails enables you to set up and develop new applications real quick.

Unfortunately, over time this speed can decrease. Not necessarily to a screaching halt, but often times the “Rails way” of putting code into certain places or folders is not the best way to keep a codebase healthy.

ActiveRecord (or models in general) all over the place

One thing that is very common to see, is that models of the applications are used in every corner and on every layer of an application. Controllers load, update and save models. Views are querying models… There’s no clear separation between what makes a domain object a domain object, and what the controller and the persistency do with it.

That also means that all components directly depend on the model implementation. It doesn’t really matter whether it’s ActiveRecord, Sequel, Lotus or whatever. Coupling your views and controllers directly to your model is not a good idea.

Abstracting away from these concrete implementations via a Repository, Data Mapper or just old fashioned factories, does help in that regard.

Too much logic in controllers

Another thing that adds up easily is controllers with too much knowledge about details of the application. A controller in Rails should be treated just as a first instance to communicate to with your application via a web-interface. Nothing more. So it handles all the web and HTTP related things that your application should be unaware of. Instead the controller just passes all the necessary information to another thing that is capable of the actual doing. Often times this thing is called an “interactor” or a “use-case implementation”. It doesn’t really matter how it is called, as long as the concept is applied. There’s a really good blog post on the 8th Light blog about that. Uncle Bob’s keynote “Architecture the Lost Years” at Ruby Midwest 2011 is also worth watching. One benefit (among many other) is that the actual application is testable without the need to test it via controller actions. The controllers should be tested though, but they are not responsible for any application- or doman-specific behaviour. That is done and tested via interactors – independant of any Rails controller.

What’s going on between controllers and views?

There’s some weird behaviour between controller and views where I do not have a better solution for yet (if there is any).

To pass data from the controller to the view, instance variables are created in the relevant controller action/method. These instance variables (yes I mean these things like @variable) are just available to the view. I don’t know why this is the best practice in Rails - maybe I don’t use it long enough yet to fully grasp it. But doesn’t that just breaks general OO concepts? Okay, these variables are not strictly private, but still. A controller is an object at runtime that has attributes. The view “just knows” about all these instance variables.

On the same note I still have to figure out why writing ERB templates is good in Ruby, but when people write templates for PHP and mix HTML and PHP code they will get cast out by society for their lack or morals… But this blog today is not about language comparison (I can already hear someone scream “What about Haml?”…)


So much for my first shot at some Rails assessments. Since I’m currently tasked with another apprentice to work further on an internal Rails application, this probably won’t be my last post about that topic.

(apprenticeship)

More Rails

(crosspost from my apprenticeship blog)

Today we were working on the second story. It included some database changes. At least we thought changes to the DB structure were needed. But while implementing the feature, we realized that we can code around the need of a “real” n:m mapping.

Which was great because the current solution is way simpler than dealing with mapping tables and all that just to support an n:m mapping for “just” two values.

(apprenticeship)

First Rails Story Finished

(crosspost from my apprenticeship blog)

After spiking our solution yesterday, Makis and I reimplemented the story again test driven. It’s way easier to TDD in Rails - even if you’re like me and have little knowledge about the framework - after you first saw and tried what you have to do. Once you know how your solution should look like, it gets easier to start with a test.

(apprenticeship)