November 10, 2012

Arguments for developing low quality software

In a recent discussion about the quality of software I was confronted with the following question:

"Picture a developer writing mediocre software. His product is published on the App-store and is an instant hit. Another guy develops an application and the internal quality is second to none. After publishing his application, he sells one license per week. Which of these two guys is the smart one?"

Obviously the first developer was more able to identify the needs of his potential customers. At least better than his competitor. But the discussion was not about marketing, it was about quality of software.

Making money developing software is the worst argument for delivering mediocre code.

October 02, 2012

Notification pattern vs. Observer

In a previous article I wrote about the Notification pattern and it's implementation in Javascript, the language I've been using the last couple of months to implement an application allowing users to design greeting cards online using a web browser.

From a technical point of view the application would best have been based on SVG or the HTML5 CANVAS element, but that's a different story altogether. The application uses HTML and CSS and every trick -even those not in the books- to perform it's job. These tricks mostly relate to CSS-magic and a lot of Javascript to make IE perform tasks that do not require programming for other browsers. Sigh!

But enough on that, let's get back to the main subject of this blogpost, comparing the Notification-pattern to the Observer pattern.

Observer pattern

Observer is a design pattern where observers can register with a subject that implements the observable interface. The interface defines methods for registering and unregistering as observer. The subject is responsible for keeping track of observers.

The goal of this pattern to allow observers to be notified of a state-change in the subject, allowing the observers to take appropriate action and keep in sync with the state of the subject. This sounds like an ideal solution applicable in many situations. And in some situations it indeed is. But there are major drawbacks to the pattern.

Object life-cycle

During application execution, objects come and go. In interactive applications mostly because of user interaction. Let's consider a simple drawing application with a canvas like area. The application allows the user to create objects (Images, text etc.) and manipulate these. The application has a tools palette whose contents depends on the currently selected object. The contents of the tools palette is determined by the type of object currently selected and the state of the object.

Such a situation implies the tools palette (or more likely: it's controller) needs to be informed when new objects are instantiated. It needs to have access to each and every object capable of instantiating objects relevant to the tools palette. Next to that it needs to be registered as observer with all these objects.

This is the major drawback of the observer pattern. A shortcoming that can be remedied by introducing a third party: the Notifier.

Notification pattern

The notification pattern introduces a third party that decouples observer and observable. This decoupling has several implications. Observers need not register with each and every observable. They register with the notifier for the receipt of given notifications. Observers also aren't bothered anymore with the complications caused by instantiation of new objects. A final benefit is that observables are relieved of implementing the interface keeping track of all observers and distributing messages to these observers. In the notification pattern, these tasks are performed by the notifier.

Considering all these benefits, situations where use of the observer pattern is favorable over the notification pattern will be rare.

In the near future I will post a live example showing a use-case of the notification pattern.

Update- The example and extensive documentation is available: Notifier design pattern.

September 06, 2012

Erlang r15b02 released.

Today, Erlang R15B02 was released. I picked up the 64-bit Mac OS X release release from Erlang Solutions. Installation took only a few minutes. I'm now running tests on my code against the new Erlang version. So far everything looks good.

June 13, 2012

The Times They Are A Changing

I am currently working on a web-project that unavoidably makes use of transformations on HTML-elements. The first version allows the user to select an object on a webpage and rotate it. In future versions users will probably will be able to perform other transformations on the object (e.g. skew, scale or perspective). My current implementation uses a jQuery slider to allow the user to rotate the selected object.

I was happily programming along and the design and implementation took me about half a day. That was until I checked what my implementation looked like in Internet Explorer versions 8 and 7. That's where the horror kicked in.

Rotation in all browsers (including IE 9 to be fair) was around the center of the selected object. But with IE 7 and IE 8, the point of rotation seemed to change in an inimitable way.


The trouble with DXImageTransform.Microsoft.Matrix
Studying the documentation of this filter one is lead to expect that the top-left of the object is the point of the rotation. But this simply is not the case. Microsoft took the liberty to augment the transformation you perform with a free-of-charge transformation from the boys in Redmond themselves.

As far as I was able to check, the free-of-charge transformation makes sure that the top-left of the boundingbox after rotating an element gets the same position as the top-left of the original element. While this might sound plausible, it actually is nonsens. One executes a transformation on an object and does not expect a free-of-charge extra transformation to be part of the deal. MS's documentation does not mention the extra transformation, let alone that it explains how it can be undone.

Check this example to see the ugly effect of this transformation. Click "huwelijkskaartjes" and next click on the card showing the text "Wij gaan trouwen". Now click on an element on the card and play around with the slider labeled "Rotatie".

The example is the version of the application I am currently re-implementing. Whatever browser you're using, rotation of an object mimics the way IE rotates an element. After days of struggle my predecessors capitulated. Unable to fix the wrongdoings of DXImageTransform.Microsoft.Matrix they decided the simplest way to tackle this was to make other browsers behave like IE. And indeed it was!

Another Redmond-Monkey pulling my leg.
I refused to capitulate but it took me several days and a sleepless night to tackle this problem. The sad part is that my solution works with IE 7, not with IE 8. Some intellectual in Redmond decided that an inner HTML-element should not take the transformations of the parent-element into account if the position of the inner-element is "absolute". This is where I capitulated. I managed to trick IE into rotating around the center of the object and my solution did not work in IE-8. So I finally capitulated and decided to block IE-8 using the following construct:


<!--[if lt IE 9]>
<meta http-equiv="X-UA-Compatible" content="IE=7,9" >
<![endif]-->

This construct is ignored by non-MS browsers. But for Internet Explorer, this causes IE-8 to behave like IE-7.


History haunts Microsoft
The dominant position of Microsoft with a 90% marketshare is long gone. Thanks to open-source initiatives -Mozilla Firefox, KHTML (Webkit)- IE's marketshare is rapidly dwindling. A couple of years ago Microsoft's filters provided capabilities beyond any other browser. The filters also introduce idiosyncrasies that are very difficult to overcome.

In my current project it took me half a day to implement the rotation functionality for all modern browsers -Mozilla, Safari, Chrome, IE-9 and Opera. To get it working on IE-7 took me several days.

Until now my client is concerned about IE-7 and IE-8. My client wants me to deliver software that works on IE-7 and IE-8. He's a lot less concerned about older versions of Mozilla, Chrome, Safari and Opera. For those browsers my implementation only needs to support the latest stable release.

Turn of the tables
With MS's dwindling browser-share it becomes more and more difficult to justify the extra effort to make web-sites and web-applications work well with MS's legacy browsers. Most versions of Mozilla, Safari, Chrome and Opera all work perfectly on most versions of Windows.

In times long gone one would encounter websites that stated "This site is best viewed on Internet Explorer version xx.xx". It's about time we turned the tables and used our browser-sniffing to tell users they're using a sub-standard browser and should switch to a non-MS alternative.

Let's be fair to Microsoft
We must be fair to Microsoft and give them credit for what they've accomplished. So what did they accomplish? Let's compare MS to Opera. A couple of years ago about 1.000 people within Microsoft where involved with Internet Explorer and Microsoft spend around $100 million per annum on Internet Explorer.

Today, Opera as a company has a total of 700 employees, part of whom work on the Opera browser. Their budget doesn't even come close to the $100 million per annum MS invested in Internet Explorer. With their limited resources Opera produced a browser that with almost every release was far ahead of Microsoft's Internet Explorer.

So let's be fair indeed and conclude that a small company like Opera in each and every way surpassed Microsoft. Opera had -compared to Microsoft- hardly any resources. Only a few people and a very limited budget. But the browser they delivered beat IE in each and every version in each and every aspect.

What about the future, IE-9 and IE-10?
Frankly, I couldn't care less about IE-9 or IE-10. Microsoft's market share is dwindling and rightly so. I'll use any trick in the book to convince my clients to completely neglect Microsoft and IE. MS produces a browser that adheres to the W3C standards? Fine with me. But I actually couldn't care less and will do my utmost to convince my clients of the same. For the times they are a changing and MS no longer dictates the WWW.



May 12, 2012

Event notification pattern in Javascript

The event notification pattern is widely used in Model-View-Controller based applications but is also applicable in other situations. The pattern allows unrelated objects to communicate information without having any knowledge about each others functionality. The pattern obeys the law of Demeter, also known as the principle of least knowledge. Sensible use of the pattern helps developers avoid a lot of messy code.

The impementation I wrote has the following functions:
Notifier.instance()
Returns the singleton notifier instance. The notifier instance provides methods allowing objects to post notifications and register or unregister for the receipt of notifications.

The instance has the following methods:
registerObserver(anObserver, msg, aMethod)
  msg:        the messages the observer wants to receive.
  anObserver: the object that wants to observe.
  aMethod:    the function to invoke on the observer upon
              receiving the given message. The function is
              invoked with two arguments, the message (usually
              a string) and a notification object:
              {sender: aSender, userInfo: theUserInfo}. aSender
              and theUserInfo being the arguments given in the
              call to postNotification.

unregisterObserver(anObserver[, msg])
  anObserver: the observing object.
  msg:        the message the observer previously registered
              for. If msg is undefined the observer will be
              unregistered for any message it was registered.

postNotification(msg[, userParams])
  msg:        the message
  userParams: additional information possibly accompanying
              the message.

Now imagine having a user-interface element on a webpage. Let's say a delete button the user clicks when he wants to delete the currently selected record on display. Ideally the button should not be bothered with details on how to remove the record from the database, nor how to remove the visual representation of the record. It's sole responsibility is to inform others it was clicked. Here's an example of a delete button using the event notification pattern:
<INPUT TYPE=BUTTON
onclick="Notifier.instance().postNotification('Delete');" 
VALUE="delete">
If the button is clicked it performs its sole duty: notifying others it was clicked.

We'll write a controller class and make an instance of that class responsible for keeping track of the selected record and removing the visual representation when it receives a notification to do so. Keeping track of selection is simple. We display a selection of records in a table and supply a onclick attribute for each row in the table:
<tr id="4" onclick="Notifier.instance().postNotification('Select', this.id);">

We could have yet another class (a model class) being responsible for performing the magic of having the server-side application remove the record from the database.

Let's have a peek at the ViewController responsible for removing the visual representation of the record:
This code clearly shows the beauty of the event notification pattern. The tablerows have no knowledge of the controllers and the controllers have no knowledge of the user-interface elements.

I implemented this pattern on a project for one of my customers. So unfortunately I feel not at liberty to disclose the source-code. Thus I'll do the next best thing and publish the boilerplate for the Notifier:
I hope the boilerplate gives a good hint at how to implement this pattern. Remember, programming should be fun and in no way should lead to an uncoordinated mess of statements. This pattern is useful in many situations and will help you avoid messy code where objects unwillingly have knowledge of the functionality of a myriad of other objects.

Having problems implementing this pattern in whatever language? Give me a call at janwillem.luiten at gmail . com!

April 28, 2012

Study, choices and focus

Choices, choices, choices.

In the past few weeks I've been looking into a number of things I would like to study in the coming months. On the database side I had a look at NoSQL solutions. Notably CouchDB, CouchBase and MongoDB. I installed all of these on my Mac and experimented a couple of hours with each of them.

Programming languages.

I had a look at Scala and Erlang. Languages I never used before and that both present me with a few new concepts. I implemented one chore in Scala and multiple chores in Erlang. I published my Scala chore and the Erlang equivalent on this blog (Erlang chore here, Scala chore here).

On Rosetta Code I completed three simple tasks in Erlang. Count occurrences of a substring, HQ9+ and Ceasar cipher. These are, from a computer science point of view, simple chores. The idea behind implementing them was not they would present me with an intellectual challenge. The goal was to get familiar with the syntax. To get a feel for the beauty or ugliness and the possibilities and limitations of these languages.

Limitations.

Now it's about time to make up my mind what to study the coming months. I can't study all these things in parallel. Next to the intellectual challenge this would present, I've got a day-time job to attend. Besides that the missus and our children, while very patient, also deserve attention. Luckily my Mac is in the living room. That gives me, the missus and the kids a sense of togetherness while each doing our own thing. Here's a difference with my previous live where a subject would totally "suck me in". Completely unable to react or respond to events in my environment. Now I happily chat with the missus or the kids while figuring out map/reduce in CouchDB or hammering out some code in Erlang or Scala.

Choice of language.

Back to the choice of language to study. The fact I implemented more chores using Erlang already gives a hint. Perhaps I didn't do justice to Scala. Perhaps I should have implemented more chores to get more proficient in Scala. But the truth is that Erlangs syntax is really, really simple. Scala's syntax is  more elaborate but the advantages of this more complex syntax over Erlang remain unclear.

Martin Oderski was quite upset when someone stated Scala was about to become the next C++. In my view Martin and his team already set the first steps in making Scala the next C++. It's difficult to top the ugliness of C++'s syntax. And let's be fair, Scala currently doesn't come close, But for me, Scala comes close enough to keep away from it for the time being. That does not mean Scala isn't worth studying. It is. It's capabilities and the fact it produces code for the world's most popular runtime will make it a popular language. No doubts about that.

Erlang's syntax is very simple and elegant. Some minor points ignored (e.g. the ugly "if" construct, the use of which is by the way not mandatory), Erlang's syntax is the ultimate application of "Occam's razor" and stands in stark contrast with Scala's elaborate and sometimes incromprehensible language constructs.

So the coming months I'll be studying Erlang and especially OTP. I'm excited about Erlang as a language and OTP as a framework for designing massively parallel and fault tolerant systems. The elegance simply grabbed me and implementing simple chores like the Ceasar Cipher gave me a feel of true elegance. It convinced me that Erlang is a language that allows me to express my ideas in a very elegant manner. Not because of my programming-abilities or my proficiency in Erlang but because of the elegance of the language.

Perhaps I didn't do right to Scala by implementing only a single chore. But the beauty and elegance of Erlang simply grabbed my attention while Scala's syntax repelled me. While Erlang's language constructs feel natural, elegant and simple, Scala's constructs sometimes feel artificial.

My point of view is that Martin Oderski is desperately in need of Occam's razor and is well advised to take the remark that Scala will be the next C++ as a kind and very relevant advise.

Nagging aspects in language choice.

I see two nagging aspects in my choice for Erlang vs Scala. One is Scala's Akka framework which is relevant without any doubt and really looks like a thing of beauty. The other aspect is the Play framework which looks very promising.

Akka.

The fact that a small team is able to implement capabilities that rival Erlang's OTP framework is an accomplishment in itself. The relevant metrics in comparing Akka and OTP would be simplicity of use, performance and lines of code spent using Akka or OTP.

The concurrency provided by Akka and Erlang is based on Communicating Sequential Processes. In Erlang this is implemented as a language feature, while Akka is a framework written in Scala.

Erlang/OTP has a proven track record with respect to reliability and uptime. Many Erlang/OTP based systems showed uptimes of 5*9 or even better. In this respect Erlang is in a class of its own. It remains to be seen wether Scala/Akka will be able to deliver the same with equal or comparable cost in hardware or development effort .


Play framework.

Another compelling aspect of Scala is the "Play" framework. The value of such a framework is beyond imagination. Frameworks like Play and Akka will propell Scala, that's for sure. Just like Ruby on Rails and ActiveRecord propelled Ruby.

Truth is that the guys that implemented Play borrowed about 99% of their ideas from David Heinemeier Hanssons work on Ruby on Rails without adding significant new ideas. Play to me looks and feels like Rails. Been there, done that. In fact still doing it. So no real benefit in studying Play. That's not to say Play isn't worth studying. It is. Play's performance gain over frameworks like Ruby on Rails is tremendous.

Choice of database.

To be fair I must admit I have no experience with NoSQL databases like CouchDB, CouchBase, MongoDb or BigTable. A colleague of mine successfully used CouchDB in one of his projects saving him a ton of work.

My choice of NoSQL database has no foundation and is completely random. I picked MongoDB combined with Ruby to study for the coming months. Simply because the combination of MongoDB and Ruby could become relevant in my day-time job.

April 26, 2012

Making things more Erlangy

In a previous blogpost I wrote a little Erlang to find sequences n, n+1, ..., n+m that have a given sum:

seqwithsum(Goal) ->
  seqwithsum(1, 2, 3, Goal, []).

seqwithsum(Tail, Head, Sum, Goal, L) ->
  if
    Tail + Head > Goal ->
      L;
    Sum < Goal ->
%     advance head
      seqwithsum(Tail, Head+1, Sum+Head+1, Goal, L);
    Sum > Goal ->
%     advance tail
      seqwithsum(Tail+1, Head, Sum-Tail, Goal, L);
    true ->
%     Prepend matching sequence to list and advance tail
      seqwithsum(Tail+1,Head,Sum-Tail,Goal,[{Tail, Head}] ++ L)
end.


I now dislike the code I wrote because of the ugly if-construct. Now that I've read some more and experimented a little I come to the conclusion that this construct, while efficient, is not Erlangy. "If" looks like a language design after-thought. Guards simply have a better feel to them. So here we go:

seqwithsum(Goal) ->
  seqwithsum(1, 2, 3, Goal, []).

seqwithsum(Tail, Head, Sum, Goal, Results) when Sum < Goal ->
  % advance Head
  seqwithsum(Tail, Head+1, Sum+Head+1, Goal, Results);

seqwithsum(Tail, Head, _Sum, Goal, Results) when Tail + Head > Goal ->
  Results;

seqwithsum(Tail, Head, Sum, Goal, Results) when Sum > Goal ->
  %advance Tail
  seqwithsum(Tail+1, Head, Sum-Tail, Goal, Results);

seqwithsum(Tail, Head, Sum, Goal, Results)
  seqwithsum(Tail+1, Head, Sum- Tail, Goal, [{Tail, Head} | Results]).


That's more the way things are supposed to be in Erlang. At least that's my point of view. To me, this looks more elegant than the code using the if-construct.

Be aware that the guards are evaluated in the order in which they occur in the source. Moving the code guarded by Tail + Head > Goal further down will cause an infinite loop.