You are viewing the Articles in the TDD / BDD Category

Circumventing Conditional Comparisons

Often during the course of my day I come across code which evaluates the same conditional comparisons in multiple contexts. Understandably, this is rather typical of most software systems, and while it may only introduce a negligible amount of technical dept (in the form of redundancy) for smaller systems, that dept can grow considerably in more complex, large scale applications. From a design perspective, this issue is applicable to nearly every language.

For example, consider a simple Compass class which defines just one public property, “direction” and, four constants representing each cardinal direction: North, East, South and West, respectively. In JavaScript, this could be defined simply as follows:

Technically, there is nothing problematic with the above class signature; the defined constants certainly provide a much better design than conditional comparisons against literal strings throughout implementation code. That being said, this design does lead to redundancy as every instance of Compass which needs to evaluate the state of direction requires conditional comparisons.

For example, to test for Compass.North, typically, client code must be implemented as follows:

Likewise, simular comparisons would need to be implemented for each cardinal direction. And, while this may seem trivial for a class as simple as the Compass example, it does become a maintenance issue for more complex implementations.

With this in mind, we can simplify client code by defining each state as a specific method of Compass. In doing so, we afford our code the benefit of exercising (unit testing) Compass exclusively. This alone improves maintainability while also simplifying client code which depends on Compass. As such, Compass could be refactored to:

Based on the above implementation of Compass, the previous conditional comparison can be refactored as follows:

Comparator API

To simplify implementing conditional comparisons, I have provided a simple Comparator API that defines a single static method: Comparator.each, which allows for augmenting existing objects with comparison methods. Comparator.each can be invoked with three arguments as follows:

type

The Class to which the comparison methods are to be added.
property
The property against which the comparisons are to be made. If the property has not been defined it, too, will be added.
values
An Array of constants where each value will be used to create a new comparison method (prefixed with “is”). If the constants specified are Strings, typically an Array containing each constant should suffice. For example, passing [Foo.BAR] where BAR equals “Bar” would result in an isBar() method being created. To specify custom comparison method names, an Object of name/value pairs can be used where each name defines the name of the method added and the value is the constant evaluated by the method. This is useful for constants which are not strings. For example, {isIOS421: DeviceVersion.IOS_4_2_1} where IOS_4_2_1 equals 4.2.1 would result in an isIOS421() method being created.

Taking the Compass example, the previous comparison methods could be augmented without the need to explicitly define them via Comparator.each:

The above results in the comparison methods isNorth, isEast, isSouth and isWest being added to the Compass type.

Comparator: source | min | test (run)

Test Driven Javascript with QUnit

For the past year I have been using jQuery Mobile for developing web based mobile applications leveraging HTML5, CSS3 and JavaScript. Like all UI implementations, meaningful test coverage is essential to ensuring requirements have been met and refactoring can be achieved with confidence. Building applications for the Mobile Web is no different in this respect. And so, a high quality Unit Testing framework is as essential to the success of Mobile Web Applications as it is to their Desktop counterparts.

Why QUnit?

While there are quite a few good JavaScript Unit Testing Frameworks available, Jasmine in particular, I have found QUnit to best suit my particular needs for implementing Test Driven Development in JavaScript based on it’s clean design and practical implementation.

A Simple, Powerful API

The power of QUnit lies in it’s simple and a rather unique approach to Test Driven Development in JavaScript. The QUnit API introduces a few slightly different test implementation concepts when compared to the more traditional xUnit style of TDD. In doing so, QUnit succeeds in simplifying some of the tedium of writing tests by leveraging the language features of JavaScript as opposed to strictly adhering to the more traditional xUnit conventions, the design of which is based on an fundamentally different language idiom – that is, Java.

For example, consider the follow which tests for a custom data namespace attribute in jQuery Mobile:

Figure 1 (run) (source)

The above test may appear quite straightforward, yet it serves as a good example by illustrating how each test in QUnit is implemented by the QUnit test fixture. The first argument is simply a String which describes the test case. This is quite convenient in that the intent of a particular test case can be expressed more naturally in textual form as opposed to using a long, descriptive test method name. The Second argument contains the actual test implementation itself, which is defined as an anonymous function and passed as an argument to QUnit.test.

As you may have also noticed from the above example, there are some, perhaps subtle, differences between the QUnit style of testing and the traditional xUnit style. Specifically, whereas in xUnit assertions expected values are specified first and preceded by actuals, in QUnit actuals are specified first followed by expected values. This may feel a bit odd at first however, after a few tests it’s easy to get used to. Additionally, where an assertion message is specified before any arguments in xUnit, in QUnit assertion messages are specified after all arguments. With regard to test descriptions, this is a difference I prefer as, a test message is always optional so passing this value last make sense. While somewhat subtle differences, these are worth noting.

A Complete Example

As code can typically convey much more information than any lengthy article could ever hope to achieve, I have provided a simple, yet complete, example which demonstrates a basic qUnit test implementation. (run) (source).

Multiple Form Factor Software Design

I have been giving a lot of thought lately about designing software in a Multi-Form Factor paradigm and felt I would share some initial thoughts on the subject. Keep in mind much of this is still quite new and subject to change; however, I have made an attempt to isolate what I feel will remain constant moving forward.

First, User Experience Design

My initial thoughts on the implications of what an ever growing Multi-Form Factor paradigm will have on the way we think about the design of software are primarily concerned with User Experience Design. While using CSS3 media queries to facilitate dynamic layouts will be needed for most Web Applications, I do not believe these types of solutions alone will allow for the kinds of compelling experiences users have come to expect, especially as they will likely compare Mobile Web Application experiences to their native counterparts. Sure some basic solutions will be needed, and for some simple websites they may suffice. However, in the context Web Applications, as well as just about every application developed specifically for a PC, too, I believe UX Design will need to leverage the unique opportunities presented by each particular form factor, be it a PC, smartphone, tablet or TV. Likewise, UX will need to account for the constraints of each form-factor as well. Architecturally, all of the above presents both opportunity and challenge.

To further illustrate this point, consider the fact that it is arguably quite rare that a UX Design intended for users of a PC will easily translate directly to a Mobile or Tablet User Experience. The interactions of a traditional physical keyboard and mouse do not always equate to those of soft keys, virtual keyboards and touch gesture interactions. Moreover, the navigation and transitions between different views and even certain concepts and metaphors are completely different. In simplest terms; it’s not “Apples to Apples”, as the expression goes.

With this in mind, as always, UX Design will need to remain at the forefront of Software Design.

Second, Architecture

Multi-Form Factor design obviously poses some new Architectural challenges considering the growing number of form factors which will need to be taken into account. The good news is, most existing, well designed software architectures may have been designed with this in mind to a certain degree. That is, the key factor in managing this complexity I believe will be code reuse; specifically, generalization and abstraction. A common theme amongst many of my posts, code reuse has many obvious benefits, and in the context of Multi-Form Factor concerns it will allow for different device specific applications to leverage general, well defined and well tested APIs. A good example being a well designed RESTful JSON service.

Code reuse will certainly be of tremendous value when considering the complexities encountered with Multi-Form Factor design. Such shared libraries, APIs and Services can be reused across applications which are designed for particular Form-Factors or extended to provide screen / device specific implementations.

Some Concluding Thoughts

In short, I believe both users and developers alike will be best served by providing unique User Experiences for specific Form Factors as opposed to attempting to adapt the same application across Multiple Form Factors. One of the easiest ways of managing this complexity will inevitably be code reuse.

I also believe the main point of focus should be on the medium and small form factors; i.e. Tablets and Smart phones. Not only for the more common reasons but, also because I believe PCs and Laptops will eventually be used almost exclusively for developing the applications which run on the other form factors. In fact, I can say this from my own experiences already.

While there is still much to learn in the area of Multi-Form Factor Design, I feel the ideas I’ve expressed here will remain relevant. Over the course of the coming months I plan to dedicate much of my time towards further exploration of this topic and will certainly continue to share my findings.

Practices of an Agile Developer

Of the many software engineering books I have read over the years, Practices of an Agile Developer in particular continues to be one book I find myself turning to time and time again for inspiration.

Written by two of my favorite technical authors, Andy Hunt and Venkat Subramaniam, and published as part of the Pragmatic Bookshelf, Practices of an Agile Developer provides invaluable, practical and highly inspirational solutions to the most common challenges we as software engineers face project after project.

What makes Practices of an Agile Developer something truly special is the simplicity and easy to digest format in which it is written; readers can jump in at any chapter, or practically any page for that matter, and easily learn something new and useful in a matter of minutes.

While covering many of the most common subjects on software development, as well as many particularly unique subjects, it is the manner in which the subjects are presented that makes the book itself quite unique. The chapters are formatted such that each provides an “Angel vs. Devil on your shoulders” perspective of each topic. This is quite useful as one can briefly reference any topic to take away something useful by simply reading the chapters title and the “Angel vs. Devil” advice, and from that come to a quick understanding of the solution. Moreover, each chapter also provides tips on “How it Feels” when following one of the prescribed approaches. The “How it feels” approach is very powerful in that it instantly draws readers in for more detailed explanations. Complimentary to this is the “Keeping your balance” suggestions which provide useful insights to many of the challenges one might face when trying to apply the learnings of a particular subject. “Keeping your Balance” tips answer questions which would otherwise be left to the reader to figure out.

I first read Practices of an Agile Developer almost 4 years ago, and to this day I regularly find myself returning to it time and time again for inspiration. A seminal text by all means, I highly recommend it as a must read for Software Developers of all levels and disciplines.

Context is key: Test Coverage

The notion that Test Coverage alone can provide an adequate metric for determining how well a particular piece of code or, an entire codebase, is being tested has always troubled me. In my experience this can be a very misleading assumption.

Like many of my previous themes, with Test Coverage context trully is key. The issue I find is that relying on a predetermined percentage threshold to provide a “true” measure of successful testing simply fails to take into account the numerous factors involved. For example, the preceived thoroughness of a systems tests can easily be increased – beit mistakenly or intentionally – by testing parts of the system which could be considered irrelevant, or provide very little tangible value; such as getters, setters and the like.

Personally, I advocate focusing first on testing the most critical behaviors and state of a particular piece of code. The tests should not be limited to just testing the expected cases but also, and of equal importance, the testing of exceptional and negative tests.

I could go on about this in great detail; however, I recently came across a really good post from googletesting (which I found via Mike Labriola) which I think pretty much sums it up.

Domain Models and Value Objects

The other day a friend asked me what is the difference between a Value Object and a Domain Model, and when I would suggest using one over the other?

Since I have been asked this very same question quite a few times, I thought it might prove useful to provide a brief definition in the context of a language agnostic idiom which could serve as a point of reference for others as well. Thus, below is general definition of each.

Domain Models

A Domain Model is anything of significance which represents a specific business concept within a problem domain. Domain Models are simply classes which represent such concepts by defining all of the state, behavior, constraints and relationships to other Domain Models needed to do so. Essentially, a Domain Model “models” a domain concept, such as a Product, a User, or anything which could be defined within a problem domain itself, outside of the context of code.

Domain Models promote reuse and eliminate redundancy by defining specific classes which encapsulate business logic, state, behaviors and relationships. As business domain concepts change, so to do the implementations of the Domain Models.

Value Objects

As the name implies, a Value Object, more commonly referred to as a VO, is an object which simply provides values, nothing more.

Value Objects are entirely immutable; that is, all properties are read-only and assignments to those properties are specified only during object creation; after which, properties can not be modified and, by design, should not require changes.

Value Objects are typically used to provide an aggregation of conceptually related properties whose values describe the initial state of the object when instantiated and do not require any real concept of identity or uniqueness. While there are some edge cases (such as validation), more commonly than not, Value Objects do not implement any specific behavior. Conceptually, think of a Value Objects as being nothing more than an object which holds a value, or series of related values, which describe something about the object when created.

It is important to make the distinction between Value Objects and Domain Models, as a Value Objects is not a Model, but rather, it is nothing more than an object which holds values and could be used to describe any particular context. Perhaps a good example of a Value Object could be a JSON object returned from the server. That is a Value Object. A Domain Model could then wrap the Value Object in order to provide state changes, validation and behaviors.

And that’s it

Hopefully the above descriptions of both Domain Models and Value Objects will clear up any confusion surrounding the two concepts; ideally, making it easier to understand when to use each.

The point to keep in mind is that Domain Models simply model a business concept, including it’s rules, constraints and behaviors, while Value Objects simply describe a contextual state.