You are viewing the Articles in the Design Patterns 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)

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.

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.

Misplaced Code

Often I come across what I like to call “Misplaced Code”, that is, code which should be refactored to a specific, independent concern rather than mistakenly being defined in an incorrect context.

For instance, consider the following example to get a better idea of what I mean:

Taking the above example into a broader context, it is quite common to see code such as this scattered throughout a codebase; particularly in the context of view concerns. At best this could become hard to maintain and, at worst, it will result in unexpected bugs down the road. In most cases (as in the above example) the actual code itself is not necessarily bad, however it is the context in which it is placed which is what I would like to highlight as it will almost certainly cause technical debt to some extent.

Considering the above example, should code such as this become redundantly implemented throughout a codebase it is quite easy to see how it can become a maintenance issue as, something as simple as a change to a hostname would require multiple refactorings. A much more appropriate solution would be to encapsulate this logic within a specific class whose purpose is to provide a facility from which this information can be determined. In this manner unnecessary redundancy would be eliminated (as well as risk) and valuable development time would be regained as the code would need only be tested and written once – in one place.

So again, using the above example, this could be refactored to a specific API and client code would leverage the API as in the following:

This may appear quite straightforward, however, I have seen examples (this one in particular) in numerous projects over the years and it is worth pointing out. Always take the context to which code is placed into consideration and you will reap the maintenance benefits in the long run.

Bindable Map

Recently I was going through some old drafts I had pending when I happened to notice I had never published this one, so I am finally doing so now…

Since first publishing an AS3 HashMap implementation back in December of 2006, much to my surprise the original post through which I released the API still yields a good amount of feedback each month.

In the time since I have extended the functionality of the HashMap to include a LocalPersistenceMap and ResourceMap in addition to the original HashMap; all of which implement the IMap interface and can be used interchangeably by client code.

The single most requested feature I have received has by far been to provide a Bindable HashMap implementation, and, just recently, I decided to implement one and share it with the community.

The implementation of the BindableMap is quite straightforward as it simply provides an API which wraps an IMap implementation in order to facilitate data binding capabilities to all read methods of the underlying Map.

Using the various IMap implementations with BindableMap yields some interesting possibilities; specifically when using BindableMap with LocalPersistenceMap as it essentially provides a bindable implementation of a LocalSharedObject, as can be seen in the following example (e.g. add some values and refresh the page):

[kml_flashembed publishmethod=”static” fversion=”10.0.0″ movie=”https://www.ericfeminella.com/blog/articles/assets/flex/BindableHashMapExample/BindableHashMapExample.swf” width=”400″ height=”400″ targetclass=”flashmovie”]

Get Adobe Flash player

[/kml_flashembed]

You can download the source, binary and example here.