Power over new()!

In this blog post I’ll show two examples of programming languages that has a different take on new(). As mentioned in an earlier blog post the standard implementation has several problems including hindering testability. The problems are rooted in the lack of flexibility caused by new() pointing to a specific concrete class. A wellknown pattern for alleviating this inflexibility, that requires a little upfront planning, is the Factory Method design pattern. An example:

public Foo Create()

At first glance this might seem indistinguishable from creating Foo directly, but the method allows us to return a cached version of Foo, a singleton, or perhaps a proxy or even a subclass of Foo. In other words, we’ve avoided settling on the instantiation of a specific concrete class.

The programming language Dart has built-in support for this pattern and doesn’t require any preplanning for realising it:

 
var foo = new Foo()

class Foo
{
  factory Foo()
  {
    // return cached version of Foo etc..
  }
}

In the example new() actually invokes the factory method. The factory method can be introduced at any point during the lifetime of Foo. This means we can implement the pattern without changing all the places new Foo() is called.

The next language gives us even more power over new(). Let’s imagine we are heavy users of a webframework for which we don’t have access to the source code. A critical part of our application needs to change and to be confident about the changes we need tests. Unfortunately our code is a mess and uses framework classes directly that depends on state from a webrequest. How do we realize the test without introducing wrappers of the framework classes and restructuring our application?

This is possible in the newspeak programming language:

	
class Module = Foo ()(
   class Foo = super FooMock 
   // implementation of FooMock folllows
)

The code above extends and overrides part of the class Foo from the webframework library with FooMock in the containing Module. All uses of Foo will now use FooMock instead. In this case an implementation could count calls to Foo and examine input values for assertion of behaviour in our newly created unit tests. Note that this extends and overrides Foo without changing existing code in our application, we only need to add the new definition. No dependency injection needed which requires preplanning!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s