software solutions / project leadership / agile coaching and training

JSView: Readable, object-oriented JavaScript TDD

Posted on October 25, 2010

If you’ve tried to write JavaScript using TDD and your JavaScript deals with DOM elements, I’m guessing you’ve felt some pain. The toughest thing about writing tests against JavaScript is separating the HTML elements and the page from the JavaScript code. In the past when I’ve done this, I’ve created JavaScript classes and either passed UI elements into the constructor or by calling a method. So in the real page, I’ll have code that looks like this:

$(document).ready(function()
{
var myClass = new MyClass(document.getElementById('blah'));
});

Then in my test class, I do something like this:

module("MyClass tests");

test("Test something", function()
{
var element = new Object();
var myClass = new MyClass(element);
});

This works fine… since JavaScript is a dynamic language, I can put any property on the “element” variable and then write tests against it, checking various properties that I know will get set on the real element (like “innerHTML”, for example).

Here’s the problem with this: if you’re writing tests first, you’re not sure what kind of elements you are going to have in the UI. Maybe “innerHTML” will get set on my element, or maybe “value”, or maybe something else. I just don’t know because I haven’t written the UI yet.

What I need it something that wraps the HTML element so that I can just call a function like getValue() and get the value, which may come from “value” in some cases, “innerHTML” in other cases, etc., depending on what kind of UI element I have.

jQuery to the rescue!

It turns out that we already have something that will wrap UI elements – jQuery. Using jQuery, we can search for elements by type (e.g. DIV, A, TR, etc.), class, or id. This works something like this:

var elements = $(‘.MyCssClass’);

This returns all elements that have the MyCssClass class applied to them. But it doesn’t return the actual elements, it returns a wrapper around the HTML element. It also turns out that said wrapper has functions like val(), html(), and text() that I can use to get the values! Just what I needed.

But I still have a problem. If I’m trying to test code that deals with 20 different UI elements, that means that I am going to have to inject 20 UI elements or test doubles into my JavaScript code. This is both ugly and painful.

A simpler abstraction

JSView is an abstraction layer that sits between your JavaScript code and jQuery/HTML so that you can write tests for your JavaScript code without having the actual page and the DOM available in a test. Instead of calling jQuery methods directly, you will call methods that will interact with jQuery in your app, but will interact with a fake replacement for jQuery in your tests. Not only that, JSView will generate methods for you so that you can easily access values and events in a readable fashion. This will allow you to truly TDD your object-oriented JavaScript before the actual page even exists!

Now I can write object-oriented JavaScript classes that look something like this:

function Calculator(element, view)
{
if (view == null)
view = new jQueryView('Calculator', element);

registerObjectProperties(this, view, ['FirstValue', 'SecondValue', 'Result', 'AddButton']);

this.whenAddButtonIsClicked(function()
{
this.addValues();
});

this.addValues = function()
{
this.setResult(Number(this.getFirstValue()) + Number(this.getSecondValue()));
}
}

Now I can write JavaScript unit tests that look like this (and without the DOM in place!):

module('When the Add button is clicked',
{
setup: function()
{
calculator = new Calculator(null, new ViewTestDouble());
calculator.setFirstValue(2);
calculator.setSecondValue(3.5);
calculator.clickAddButton();
}
});

test('Then it should add the values in the first two textboxes and put the result in the third textbox', function()
{
equals(calculator.getResult(), 5.5);
});

More details can be found here. The source code is up on github. I’ve been using and refining this for two years and I’m really liking how it’s turned out. I’m very interested in any feedback that you all might have, I’ve done a lot of JavaScript over the years but I’m not quite the JavaScript ninja that some other people are.

So get busy and write some tests!





Ruby on Rails vs. .NET: Don’t take it personally

Posted on October 22, 2010

As I’ve written these Ruby on Rails vs. .NET posts, I was not expecting some of the comments that I got. Not that the comments I got were not bringing up valid points, but I felt a tension in some of them. The same is true about other similar RoR/.NET posts (like this one — read the comments).

I feel like this is disintegrating into a religious us vs. them debate. I had no intention of it ever being this way, nor should it be in my opinion. I’ve just been stating my preference and explaining the reasons why.

If you prefer .NET over Ruby on Rails, I have no problem with that! If you’re better at .NET or it’s a better fit than RoR for what you’re doing, I’m not saying you’re wrong. I personally think that RoR is a better web development platform than ASP.NET, but that’s just my opinion. I also don’t think that ASP.NET MVC sucks or anything like that, I’ve had a lot of success with it and it’s still getting better.

I think as software developers we need to at least consider other languages and platforms that we don’t use regularly because there might be something better out there. If anything, you’ll learn something that you can take back to your platform and make it better. You might not like what you find, and that’s fine, at least you can know that you checked it out. Not everything you try will be worth using.

You are not your language or development platform. You are a software developer who happens to have expertise in a certain language or platform. If someone even were to deride your platform (which I have no intention of doing), don’t take that as a personal attack. There are a lot of ignorant people out there in all walks of life, don’t let them ruin your day. Just because someone likes Ruby on Rails doesn’t mean that you are any less of a developer for choosing .NET.

At the same time, I’ve found a platform I like and I’m going to talk about why I like it, because on this blog I talk about things I like. Some people find this “proselytizing” to be annoying, and I’m sorry that you feel that way. I’m only doing the same thing that .NET developers did when they proclaimed that Silverlight is better than Flash and that Windows Phone 7 is the next big thing. There is nothing wrong with being excited about a platform, technology, or framework that you like. That doesn’t mean that you have to think the same as me or agree with me, and I welcome the discussion. But let’s try and be polite about it.





Ruby on Rails vs. NET: The Active Record Pattern, is it OK?

Posted on October 21, 2010

Persistence in Ruby on Rails is done by most people through the ActiveRecord ORM, which follows and is named after the Active Record pattern. There are other Ruby ORMs (like DataMapper) that don’t follow the Active Record pattern, but they aren’t used nearly as much.

Some .NET people seem to sneer at Ruby’s use of Active Record. There is a .NET implementation of the Active Record pattern (Castle ActiveRecord, which is a layer on top of NHibernate). In .NET and Java, the Active Record pattern is somewhat frowned upon and is usually considered not as good as a more robust, flexible ORM like NHibernate or the Entity Framework where your database tables don’t have to look just like your objects.

Some people would say that the Active Record pattern violates separation of concerns because the entity objects know how to load and save themselves. One big problem in the .NET world is that since an entity object can load itself, it has to do so with static methods (e.g. User.Load(3)), which means that now you can’t stub that out in a test (if you’re in a static-typed language). In a dynamic language like Ruby you don’t have the testability problem because you can stub out class methods (analogous to static methods in .NET).

There are still more concerns posed about the Active Record pattern. Is it maintainable in the long term? What if you don’t want your database tables to look like your objects? What if I would rather have separate domain service classes to do the persistence? What about the repository pattern?

If you’re a .NET person, you have to think about life in a truly dynamic world, where you don’t have the testability issues. Are any of those other things really a concern? If you’re starting a new app, what are the chances that your database tables won’t look like your objects? In most cases, I would say slim to none! If you have an application where you have some data concerns that would require to make your data model have a different shape than your objects, then you can’t use ActiveRecord. If you want to use an object database like MongoDB, then you use an ORM that works with MongoDB (like Mongoid). If you’re building a new app on top of an existing database, you may need something that will allow you to do different kinds of custom mappings (although you might be able to shoehorn it somewhat). But for the large majority of everyone else, what is the real concern?

The added flexibility that something like NHibernate or DataMapper gives you comes with a price — added complexity. Fluent NHibernate and some of the new Entity Framework stuff allow you to do convention based mapping so that it takes away a lot of this pain. If your domain model objects have a different shape than your database tables, you could have performance concerns (although not always).

What you get from ActiveRecord is simplicity, and simplicity is worth something. When you use ActiveRecord, you are essentially saying that your database and codebase are under your control, so you can have your database tables match the domain model objects using certain conventions. Your database becomes a very thin layer that does nothing more than store and retrieve data, and all of the business logic is in the business layer (where it should be in my opinion, regardless of your ORM). If you have to change your domain model objects for some reason, you change the database too. So I’m not constrained by my database because all of my logic is in the business layer, which allows me to easily change either layer whenever I need to. The benefit to this is that you don’t need to write any code to map your objects to your database and you don’t need as much hand-rolled SQL (you’re always going to have hand-written SQL for some queries no matter what).

The Rails project that I’m currently on is four years old. We use ActiveRecord as our ORM. I don’t see any situations where it really constrains us at all or makes our code less maintainable. I think it makes things simpler because it is assumed that the database tables and domain model objects look the same (you can override some of that if you need to). I feel like there is a lot of fear and uncertainty in the .NET world over ActiveRecord because the pattern isn’t really accepted in the .NET world (for good reasons). But that doesn’t mean that it doesn’t fit well in a dynamic language like Ruby, where I think it works quite well.

So if you’re a .NET person who is skeptical about ActiveRecord in Ruby, I would encourage you to have an open mind. There are other alternatives if it doesn’t fit your application, but in most cases I think it gets the job done quite well.





Ruby on Rails and the Single Responsibility Principle

Posted on October 19, 2010

Several people took issue with my last post about Ruby on Rails saying that my example violates the Single Responsibility Principle. Here’s where I stand on this.

The SOLID principles are principles, not hard and fast laws of software development. When applying the SOLID principles, common sense should rule. There are times when violating the textbook definition of the principles is OK (regardless of what language you are using). The ultimate goal of all design principles should be reducing the cost of change. Reducing the cost of change comes in many forms:

  • Being able to get things done faster because you have to write less code
  • Being able to get things done faster because it’s easier to figure out code and what you need to change
  • Being able to get things done faster because code is wrapped in tests so you can change it and not worry about breaking things
  • Being able to get things done faster because you have automated tests which decrease the amount of manual testing that you or your QA team needs to do
  • Being able to get things done safer by having abstraction layers in place so that changing code in one place doesn’t break something else
  • Having well defined requirements so that you don’t waste time on rework
  • Having business sponsors available to answer questions quickly
  • Many more reasons that I’m not thinking of

With this in mind, all of my design decisions, including how I apply the SOLID principles, need to reduce the cost of change.

Also, keep in mind that the SOLID principles were written with static-typed languages in mind (C++, Java, .NET). While a lot of the same principles apply in dynamic languages, you can’t assume that everything is the same. In fact, the “I” and “D” of the SOLID principles arguably don’t apply to dynamic languages at all.

Several people said that my Ruby class violated SRP because it mixed class behavior, database mapping, and validation all in one class. Again, this is where I would take issue with your application of SRP. Here is the Ruby class in question:

class User < ActiveRecord::Base
belongs_to :user_status
has_many :roles, :through => :user_roles
validates_length_of :name, :maximum => 100
named_scope :active, :conditions => ["user_status.id = ?", UserStatus::ACTIVE]
end

On my last .NET project, I had domain model classes like this:

public class User : Entity
{
public virtual long Id { get; set; }
[Required("Name"), Length(50)]
public virtual string Name { get; set; }
public virtual IList UserRoles { get; set; }

public virtual bool IsInRole(string role)
{
// code here
}
}

I was using Fluent NHibernate as my ORM on this project, so I had a database table that looked like this object. So in this case, I have class behavior (IsInRole method), validation (the attributes on the Name property), and implied database mapping (using Fluent NHibernate conventions). How is this any different than my Ruby class?

Some people might argue that the textbook definition of SRP would say that I shouldn’t put validation attributes on properties like that. What is your other alternative? Write a line of custom code in an IsValid method or in another validator class, I assume. Is that reducing the cost of change? If I write custom code, I have to write a test for it. If I write boilerplate stuff like “[Required("Name")]” or “validates_presence_of :name”, that is so simple that I’m not going to write a test for it because I don’t think I gain anything from doing so. If I can add a whole bunch of behavior in just one line of code, then potentially violating the textbook definition of SRP is OK with me because it’s way easier to do it that way and it just makes sense.

Back to my Ruby class. My class knows how to load, save, and delete itself. In .NET, I would say this is a bad thing. First of all, I wouldn’t be able to stub out the database in a test (which I can in Ruby because I can stub out anything). Second, if you have multiple entities that do things a certain way (e.g. multiple entities that need to be cached when loading, saving, or deleting them), you would have no easy way to do that without duplicating some code (in Ruby, I can create a module and include it in a class, and in that way I could override a method like “save”). Third, I would have a direct dependence on the database, which violates the Dependency Inversion Principle (which doesn’t apply in Ruby, because all I’m depending on is some class out there with a method with a certain name, as opposed to .NET where I’m depending on a method in a class in an assembly in a .dll with a specific version). So as you can see, your domain model takes on a much different shape in Ruby vs. .NET. Both ways have their pluses and minuses, but each way is the best way for the language that you’re using.

There is one area where I see an interesting clash of Ruby and SRP. Because I don’t have to use dependency injection and because I can stub out any method in a test, it makes sense to put all methods relating to an entity object into the entity class itself. This just makes sense, and TDD would lead you in that direction. Doing this will lead you into having some really big domain model classes though.

Would this violate the textbook definition of SRP? I would say yes. You run into some of the issues that you have with big classes (harder to read). In .NET, we would argue that we should move a lot of this behavior into domain service classes, which would be smaller and easier to use in other classes (by taking the interface into the constructor of the class that was going to use it). In .NET, you have to pull things out of the entity object in order to be able to stub it out in a test, so at that point you might as well go the rest of the way and make small classes. But if you had the flexibility of being able to stub out anything in a test and you had Ruby-style mixins in .NET, would you really do it this way? One could argue that the .NET way of doing things in domain services is an example of Martin Fowler’s anemic domain model anti-pattern.

In both languages, you are making a tradeoff. In .NET, we are saying that testability is more important that potentially having an anemic domain model and having model behavior scattered around in domain services. In Ruby, we are saying that we would rather have all of the behavior in the entity class itself because it makes sense to have it there (we don’t have to worry about testability because everything is testable), even though we could end up with some big classes. Neither way is necessarily wrong, it just depends on the language you’re working in. In some cases, the .NET and Ruby communities have generally agreed on their own “best practices” and ways of doing things, and that’s just how people do things in those languages, often because the languages and frameworks make it easier to do it that way.

In summary, it depends, and use common sense. Remember what your goal is — to deliver working software. Your architecture is not the deliverable, and it’s not what makes money for the business. Flexibility, design patterns, abstraction layers, and the like often come at varying levels of cost. It’s up to you decide if it’s worth it in your situation.





Ruby on Rails vs. .NET: Doing more with less

Posted on

One thing that I quickly noticed about Ruby on Rails is that you can do a lot more with less code. This is one of the benefits of working in a dynamic language like Ruby that does not have as many restrictions as a static typed language. The end result is that you have smaller methods, more descriptive code, fewer chances to create bugs, and it becomes easier to get things done. Let me show you what I mean.

Let’s say that I have a database table that looks like this:

create table Users
(
id int,
name varchar(100),
user_status_id int,
created_at datetime,
updated_at datetime
)

My Ruby class looks like this:

class User < ActiveRecord::Base
belongs_to :user_status
has_many :roles, :through => :user_roles
validates_length_of :name, :maximum => 100
named_scope :active, :conditions => ["user_status.id = ?", UserStatus::ACTIVE]
end

My class only has 6 lines, but it does an awful lot. Let’s go through it line by line:

class User < ActiveRecord::Base

Because I have a table in the database called "Users", I now have the following methods on my User class:

  • id, id=, name, name=, user_status_id, user_status_id=, created_at, created_at=, updated_at, updated_at=
  • find, find_by_id, find_by_name, find_by_user_status_id, find_by_name_and_user_status_id, find_by_id_and_name_and_user_status_id, and any other combination of columns I might want to query on

Because I derive from ActiveRecord::Base, I inherit a lot of data access methods like save, delete, destroy, and many more.

All I've done so far is made my class declaration! Look at everything I'm getting for free.

belongs_to :user_status

My User object has a many-to-one relationship to the User_Status table (and it's corresponding UserStatus object). I now have the "user_status" and "user_status=" methods on my object. The user status will be lazy loaded, so it won't do any database queries to get the user status until I actually need it.

has_many :roles, :through => :user_roles

My User object has a many-to-many relationship with the roles table, and in the database there is a user_roles table that serves as a mapping table. I now have a "roles" method on my User class that will give me the list of roles, and I can add new roles to the collection without having to worry about creating anything for the mapping table.

validates_length_of :name, :maximum => 100

Name is required and cannot be longer than 100 characters.

named_scope :active, :conditions => ["user_status.id = ?", UserStatus::ACTIVE]

Now I can write "User.active", which will return all active users. This is equivalent to User.find_by_user_status_id(UserStatus::ACTIVE), but now I've abstracted away that concept of an active user so that other classes don't have to know how the internals work.

end

OK, well, every language has to have some ceremony.

I haven't created any methods yet! Already my object has all of the data access methods that it needs, it will validate the object before it saves, it knows about related objects, and I abstracted away the concept of an active user.

Note that not only have I been able to do all of this with very few lines of code, the code that I did write was very simple and readable. Since the code is so simple, I'm not going to write unit tests for it either (the tests would basically be the same one line of code as the implementation code in most cases).

All of this means that I can do things much easier than before. In .NET, I would've had to create finder methods by hand. I would've had to add all of the properties that match up to my database columns by hand. I don't know how I would duplicate named_scope in a .NET ORM, maybe it's possible somehow. I've never found a way to do it. Maybe I would have to write a stored procedure.

To sum it up, all of the boring crap is done for me and I can pretty much immediately start writing code that provides business value, which is what we're getting paid to do. No ADO.NET, no more mapping my database table to my entity object, no more modifying several files just to create the same kinds of methods that I have to create for every new entity object that I create.

All of this is helping me to achieve what I've always wanted in software development: the ability to write code that says what I want to do and does it without having to do lots of typing.





A matter of perspective

Posted on October 18, 2010

There are lots of difficult situations in life. However, it is up to you to decide how difficult they are going to be.

As of last Thursday I have a newborn living in my house. While this is awesome, it will probably be several months until I can sleep all the way through the night again and I’m often awake at 2:00 AM rocking a baby to (hopefully) sleep. There are more or less two ways that I can deal with this:

  • Stupid kid, why won’t he just go to sleep??!?!??
  • God has blessed me with this cute little addition to our family and I get the honor and privilege of teaching him how to sleep, eat, play, and live.

Regardless of which of those two viewpoints I take, the reality doesn’t change: he’s going to keep me up at night. There’s really nothing I can do to change that, that’s just how newborns are. But I can change the way I look at it and the attitude that I take towards the situation. As a result, I’m now smiling at 2:00 AM as I look at our little youngster instead of being bitter about having to roll out of bed yet again in the middle of the night.

The same idea can apply to any difficult situation in life, including your career. Maybe you’re stuck doing boring maintenance work, working with less than stimulating technologies, or just not doing what you’d really like to do. While this can certainly be draining, try and take a new approach to it: in the morning when you get to work, choose to strive to be the best that you can be with whatever technology you’re using. Try and find new ways to get better and faster at it. Turn those hindrances and constraints into a challenge. Don’t let the situation determine your happiness or your motivation.

Every day you have a choice to be awesome at what you do or to find ways to be negative and let things tear you down. It’s much more fun to be awesome!





My life as a Rubyist: a 4-week checkpoint

Posted on October 11, 2010

I’m 4 weeks into my Ruby on Rails gig and so far I’m loving it. Ruby on Rails is an awesome platform for developing web applications and it allows you to do things really easily. The Ruby language itself is extremely flexible. It has far fewer restrictions compared to static-typed languages, which enables to do things that you would’ve never thought of doing before. (If you’re curious, watch these screencasts on the Ruby object model and metaprogrammming, it’s some real mind-bending stuff).

The app that I’m working on is 4 years old, yet the codebase is probably the cleanest brownfield app I’ve ever worked on. The team puts a lot of emphasis on writing clean code and doing things right. I’m excited to work in a place where this is valued so much.

I noticed really quickly that there were very few really long methods in the codebase. The more I thought about it, I realized that this is not just because the team is making a concerted effort to write small methods (although that is part of it). You can do a lot in Ruby with not a lot of code, so you don’t need to write as much code. This leads to smaller methods, more readable code, and less code that needs to be written.

TDD is much more valued in the Ruby community. At JRubyConf last weekend, when they asked how many people in the audience practiced TDD, at least half of the people raised their hands. Everyone on my team knows how to do TDD. JRubyConf had three sessions on advanced TDD topics. None of them felt the need to convince people why TDD is good.

There are many more reasons why I like the Ruby on Rails platform (much more on this later). When you can do things using less code, there are countless open source packages that you can take advantage of, and when all of the tools you need to run tests, deploy your app, and migrate your database are already taken care of, you’ve drastically reduced the cost of change and developing applications (and don’t just take my word for it).

I’m not leaving the .NET world forever, but the Ruby on Rails world is more aligned with how I feel software development should be done (particularly when it comes to Agile, TDD, and software craftmanship). This doesn’t mean that .NET is bad by any means. But when it comes to developing web applications, Ruby on Rails has been quite an enjoyable experience.





NuPack = win

Posted on October 8, 2010

If you’re a .NET developer, you probably heard that Microsoft announced NuPack this week. This will allow you to easily find open source projects and pull them directly into your project.

Here’s why I think this is really awesome — this is going to enable all kinds of open source development. Sure, it’ll be easy to pull in the big open source projects like NHibernate, but you already knew about NHibernate. I’m talking about the small, more specific open source projects that do more specific things like pagination of tables in web sites, OpenID authentication, manipulating Word documents, and such. There are lots of these sort of things in the Ruby world, and it makes development really easy because I can pull in all kinds of open source libraries from rubygems with one command from a command line.

Not only will it be easier for people to find open source, it makes developing open source cool. People out there will be trying to be the one who develops everyone’s favorite table pagination plugin for ASP.NET MVC, or a .NET wrapper for the jqGrid, and any number of other things.

I’m excited that Microsoft is putting their effort, developers, and money behind something like this and I hope that this will have a real and lasting effect on the .NET ecosystem.





JRubyConf recap

Posted on October 4, 2010

When I started at my Ruby gig last month, my co-workers encouraged me to attend JRubyConf. I am really glad they did.

This conference was exactly what I’ve wanted from conferences in the past:

  • Primarily expert level talks on technologies that we already use (or new versions of technologies that we already use)
  • A good amount of inspirational or non-technical talks
  • Three talks in a row on testing! (and none of them were intro-level)
  • Most of the room raised their hand when someone asked how many people do TDD

The Ruby community is very willing to learn new and better ways to do things, and learning is encouraged and appreciated. This is very clear from the way this conference has been run, and it’s not being done in a condescending way. The bar for conferences that I attend has been raised quite a bit now.

Jim Holmes has been promoting JRubyConf (which has been known as eRubyCon in prior years) for awhile now, even for people who didn’t do Ruby. I would definitely second that, a .NET or Java person could learn a lot from seeing how things are done in Ruby (and the less technical talks apply to anyone). However, you may leave frustrated if you’re not currently able to use Ruby at your day job!





SERVICES
SOFTWARE SOLUTIONS
I have over 10 years of software development experience on several different platforms (mostly Ruby and .NET). I recognize that software is expensive, so I'm always trying to find ways to speed up the software development process, but at the same time remembering that high quality is essential to building software that stands the test of time.
PROJECT LEADERSHIP
I have experience leading and architecting large Agile software projects and coordinating all aspects of a project's lifecycle. Whether you're looking for technical expertise or someone to lead all aspects of an Agile project, I have proven experience from multiple projects in different environments that can help make your project a success.
AGILE COACHING
I believe that Agile processes and tools should be applied with common sense. I've spent the last 6 years working on Agile projects as a consultant in many different environments, both in leadership roles and as a practitioner doing the work. I can help you find out how Agile can work best in your organization, not just apply a prescriptive process.
TEST DRIVEN DEVELOPMENT TRAINING
TDD Boot Camp is a hands-on, three day, comprehensive training course that will teach you all of the skills, tools, frameworks that you will need to use test-driven development to develop real world .NET applications. If you're not looking for something that intensive, check out the the half-day version.
Have any questions? Contact me for more information.
PRESENTATIONS
The Business of You: 10 Steps For Running Your Career Like a Business
From CONDG 2012, Stir Trek 2014
From Stir Trek 2013, DogFoodCon 2013
From Stir Trek 2012, QA or the Highway 2014
(presented with Brandon Childers, Chris Hoover, Laurel Odronic, and Lan Bloch from IGS Energy) from Path to Agility 2012
(presented with Paul Bahler and Kevin Chivington from IGS Energy)
From CodeMash 2011
An idea of how to make JavaScript testable, presented at Stir Trek 2011. The world of JavaScript frameworks has changed greatly since then, but I still agree with the concepts.
A description of how test-driven development works along with some hands-on examples.
From CodeMash 2010
From CodeMash 2010