Most recent posts...

Windows Key

2009-07-30 22:44:07

There are some programs that are launched more often than others. Some of these are launched so often that it would be great if there were key shortcuts for these. The problem with key shortcuts is that it's hard to find an easy one that isn't already used. Ctrl-V for Vim? Ctrl-N for Notepad? Those key combinations are used everywhere, especially the Ctrl-V for paste. What about Ctrl-Shift-N or Ctrl-Shift-V? Pretty sure some heavy programs such as Visual Studio find uses for those as well.

With current keyboards this issue is ironically limited to Windows. In Linux I haven't had any difficulties coming up with fast key shortcuts that aren't used anywhere else. The reason? Windows key! The key that has two every-day uses in Windows (Win, Win+R) has unlimited potential in Linux - and they still call it Windows key.

There are some ways to map shortcuts to Windows key in Windows but these are mainly some random third party apps that hog resources in the background. No thank you.

How many use Win+Pause/Break to show system information? Even now that I know there's a shortcut for that I really fail to see the use - there's no easy way to navigate around that dialog with the keyboard so most likely you're going to need mouse anyway. And since you're going to pick the mouse eventually, you can just as well start the dialog with it from the start menu.

Windows has support for key shortcuts, why must it be so half assed? :|

STAB!


Use libraries only when you don't need them

2009-06-24 00:28:51

I was reading through the Coding Horror RSS feed today on my way home and spotted a reference to an old article: Don't Reinvent The Wheel, Unless You Plan on Learning More About Wheels. While I believe Jeff was thinking professional developers while writing that article, it got me thinking of my early (earlier?:p) years as a programmer.

Some years ago I was going through a phase where all the stuff I did was already done and people kept reminding me of that. They kept recommending lots of different libraries or frameworks and I felt terrified by everything. I had just moved from C++ to Java and it was already feeling quite overwhelming, I certainly did not need dozen libraries on top of it.

I'm not saying that using libraries would have made it harder to reach some concrete implementation goal. Quite the opposite: If I had piled a heap of libraries on top of each other, I could have avoided the need to understand the core principles of the Java platform. While this might be okay in production environment with strict deadlines, it is not okay when trying to learn the new language.

Syntactic libraries are evil: They have a ready implementation for things the programmer should be able to write on their own. Most Object Relational Mapping libraries are nothing but database access code combined with reflection, both of which are core technologies in Java. While it might make sense in short term to use Hibernate for database access it will be better for long term to know about lower level database APIs and reflection.

I don't mean to claim one should never use syntactic1 libraries. They do have their place. I believe the correct time to use such libraries is when they aren't needed. When the developer can implement the functionality of the library without problems, there's no benefit in wasting time doing so. Just grab the existing implementation. If the question is between writing home brewn data access using low level APIs and using Hibernate, my answer is not doing either. Write high level data access using low level APIs and reflection - THEN use Hibernate.

This is more or less the point Jeff Atwood makes in his article with a slight variation. I'm not saying you should re-implement Hibernate to learn about the quirks of the object relational mapping, what I'm saying is that you should re-implement parts of Hibernate to learn about the platform.

[1] I divide libraries to two classes. Syntactic libraries add no functionality to the core platform, they only wrap existing functionality behind different syntax such as database access behind object mapping. Functional libraries add real functionality like 3D hardware acceleration. Functional libraries require knowledge about certain domain more than about the implementation language and so implementing a functional library doesn't carry the same benefits as implementing a suntactic library.


Enhancing the web programming experience

2009-06-08 01:17:51

When it comes to web applications, I am a huge fan of AJAX applications. Silverlight and Flex have no chance against a well written AJAX application in terms of usability or use of standards. The flipside is that well writing JavaScript is a horrible experience in itself.

I believe this to be one of the main reasons for the alternative RIA technologies like Silverlight and Flex. Short of multimedia capabilities these technologies don't really offer that much more for web development but they are still used in non-multimedia applications since programming in these platforms is more convenient for the developer not least because of the fixed environment.

The problem with JavaScript is not the language (which I find pretty decent) but the environment. Each browser has a slightly different implementation of the JavaScript engine which means that a large part of low level JavaScript is used to handle the browser differences. Fortunately programming experience is not just a sum of the language and the environment - if it was, we'd be in trouble. The third aspect that affects the programming experience are the available libraries. (Picture 1)

Picture 1: The aspects of programming experience

Fortunately JavaScript as a language is flexible enough so that it is possible to create quite seamless libraries that solve the problems with the environment. jQuery is an example of the libraries that remove the browser differences to a large extent and allow the programmers to concentrate on the actual logic. It should be noted that these libraries won't expand what JavaScript can do and for that reason there won't be a JavaScript library that allows for hardware accelerated 3D-rendering inside the browser. What these libraries can achieve is easier programming model for existing features such as UI logic.

Lately data binding has seen significant use as UI logic implementation. It is one of the driving forces behind Microsoft WPF/Silverlight and makes the UI synchronization a trivial issue in most cases. Picture 2 shows a system monitor UI done in Silverlight. The system monitor has one line written in C# that populates the UI with correct values, all the rest is done through databinding and templating in XAML.

Picture 2: UI created with databinding

XAML is also a weakness that JavaScript doesn't have. It is not easy to describe an UI in C# or similar languages. It is usually easier to just build it using for loops and similar control structures. This is why Microsoft has developed an XML derived language for UI design that allows descriptive UI building. JavaScript provides the JavaScript Object Notation (JSON) that allows describing tree-like structures in the code so there's no reason to come up with a separate language for this.

So how would data binding fit in JavaScript? Listing 1 contains some sample code which describes one way to implement data binding in JavaScript. The code also utilizes jQuery for DOM manipulation. The data binding functionality is provided by a library I'm working on currently.

Listing1: An example of JavaScript databinding
// A simple data structure
var dataStructure = bindable([
  {
    name: "Jubjub",
    importance: 600,
    items: [
      { name: "Red item", color: "red", value: 12 },
      { name: "Blue item", color: "blue", value: 8 },
    ]
  },
  {
    name: "Bandersnatch",
    importance: 400,
    items: [
      { name: "Red item", color: "red", value: 42 },
      { name: "Blue item", color: "blue", value: 314 },
      { name: "Green item", color: "green", value: 162 }
    ]
  }
])

$(function() {
  var lastValue = 0;

  // Bind all divs of class 'bound' to the above structure.
  bind($('div.bound'), {
    dataContext: dataStructure,
    items: {
    
      // The template which builds the first level items of the above structure
      template: function(item) {
        var template = $('<div class="parent">' +
                           '<div class="parentName" />' +
                           '<div style="margin-left:50px;display:none" ' +
                                 'class="items" />' +
                           '<button style="margin-left:50px" class="new">' +
                             'New item' +
                           '</button>' +
                         '</div>');
        template.click(function(event) {
          template.children('div.items').toggle("fast");
        });

        // The 'new' button adds a new item to the structure.
        // No UI logic in the click handler
        template.children("button.new").click(function(event) {
          template.children('div.items').show("fast");
          item.items.push({ 
            name: "New item", color: "purple", value: lastValue++ 
          });
          return false;
        });
        return template;
      },
      
      // The bindings for the template
      bindings: {
        "div.parentName": { 
          properties: { 
            "text" : "name",
            "css.font-weight" : "importance",
          }
        },
        
        // The subitems are bound in a similar way than the main items.
        // The largest difference is that now we're using relative context
        // with the "path" property instead of the absolute "dataContext".
        "div.items": {
          path: "items",
          items: {
            template: function(item) {
              var template = $('<div class="item">' +
                                 '<span class="name" />' +
                                 '<button class="value" />' +
                               '</div>');
              template.children("button.value").click(function(event) {
                item.value.set(item.value.get() + 1);
                return false;
              });
              return template;
            },
            bindings: {
              "div.item": {
                properties: { "css.color" : "color" }
              },
              "span.name": {
                properties: { "text" : "name" }
              },
              "button.value": {
                properties: { "text": "value" }
              }
            }
          }
        }
      }
    }
  });
});

While the structure might look complex to those new to data binding it is worth noting that it does nothing more than describe the UI as a tree and as such it should be clearer than code that builds the UI in the traditional way and keeps it synchronized with the underlying data structure. Live version is below:

The benefit of the data binding should become clear when considering the array.push(item) on lines 48-50 in the listing. This single statement is responsible for adding a new item to the data structure and then updating both of the two trees to show this new item.

The purpose of this example was to show that even the complex concepts can be implemented in JavaScript. It is an extremely flexible language that was held back by the fact that the code had to target several slightly different platforms at the same time. We now have great libraries like jQuery that take care of this problem for us so there really aren't any reasons for JavaScript to suffer from bad programming models as the language definitely is flexible enough for pretty much anything: It's all up to us to provide the required libraries.

There are also some frameworks that operate on higher level than jQuery. I consider Dojo an example of these frameworks. My experience with these frameworks is limited to browsing the documentation and not spotting any methods for raw DOM manipulation - providing UI widgets is great but having no methods for DOM operations means problems the moment the UI widgets are not enough and one has to operate on lower level. This is why I believe building layered libraries on top of jQuery or similar low level library is the way to go as these provide a soft fallback when the user has to do something outside the library scope.


Reducing complexity with hierarchial models

2009-05-29 09:23:35

The problem

When trying to break a large application to more manageable modules, the obvious separation is between the Model and the View but in most cases this is not enough. The Model is a well defined concept which means the View will quickly become bloated and unfortunately the problem of what to take away from the View is not a trivial one.

The Rails solution

During the last years there has been a huge influx of new web frameworks. The huge competition between frameworks has forced the frameworks to attempt solving the architectural problems in better ways. One of the most interesting solutions is that provided by Ruby on Rails framework. Rails promotes Convention over Configuration approach to web development by mapping views to the database if the database schema is close enough to the intended views.

At first tying the database schema to the views sounds like a step to the worse - this is what I thought for a long time at least; We have been trying to decrease the coupling between the View and the Model a while now by introducing different layers between these two concepts and now Ruby ties these together by mapping views to tables (Picture 1) and is proud of it.

Picture 1: Stereotyped Ruby on Rails application architecture

What makes this approach work for Ruby while resulting in unmaintainable mess in traditional software? A basic web site is relatively simple piece of software as long as it doesn't have to integrate with legacy systems. It's purpose is to display some information and perhaps allow modifications to the said information. Most importantly the information exists purely for the web server: no one cares where the information is stored or in what format as long as the web server is serving it over HTTP.

Rails minus HTTP = ?

If someone wants to create an alternative consumer for the web site data, they'll throw the server with few GET requests and be done with it. Desktop applications rarely host HTTP servers so this approach doesn't work for those. Usually the only (sensible) approach with desktop applications is to connect directly to the database at which point it's nice if the database is designed in such a way that it's readable (Hear this, SAP?). This means the database doesn't necessarily represent the GUI structure of the desktop application (Picture 2) which makes it harder for the framework to automate the GUI generation.

Picture 2: Model-View relationship in a desktop application

This is where the controllers, presenters, adapters and such come into the picture. These logic layers are put between the database and the views to centralize the logic and to allow the already complex UI logic to delegate the data related logic to another layer. While this resolves the immediate issue, it's not as simple as the solution Rails uses. These patterns offer little comfort to the actual UI synchronization; the patterns do provide some guidelines for where to place the UI synchronization code but they don't really help in implementing it.

Enter MVVM

Data binding would offer an elegant solution to the UI synchronization if only the general setup was similar to that of Rails; if the Model could be mapped to the Views, we could establish bindings between these two. But we just came to the conclusion that it can't be mapped in most cases. Actually we only stated that the primary model could not be mapped to the UI. But what about another? Did someone say we should have only one model in an application? Not the MVVM pattern at least.

Synchronizing a relatively normalized data structure with another is an order of magnitude simpler than synchronizing a redundant data structure such as a user interface with a normalized data structure like database. Mapping a data structure that mimics the structure of the UI to the actual UI is so trivial that it is possible to generalize the synchronization logic into a library and use it with any data structure and UI as long as they aren't too different. So let's break the original problem into these two parts! This should give us the following components (Picture 3).

Picture 3: MVVM architecture

View
Contains logic for drawing the user interface and maps elements to data in View Model
View Model
Data structure which contains all the data for a single view.
Controller
Traditional Controller which acts between View Model and the real Model. Fortunately the View Model is much simpler than the View so the Controller is significantly easier to implement than in MVC.
Model
The primary data source.

The View Model separating the View and the Controller has two large benefits over traditional models. The one we were aiming for is that the programmer who is responsible for the Controller doesn't have to care anything about the actual View. As long as he keeps the much simpler View Model up to date, the View should be able to do its job while the person who is implementing the View doesn't need to care about anything else than the View Model and how to pull the required information from there. The second benefit comes from testing. In general testing a graphical user interface is really difficult as there are no good ways to assert that the interface behaves like it should. Now that the View is really thin layer on top of the View Model, much of the testing can be done straight to the View Model which is a data structure that should be easy to test.

There is actually a third benefit to this. When I earlier referred to the person who was to implement the View, I intentionally didn't say programmer. In MVVM the View has very little actual program logic so it doesn't necessarily require a programmer to implement it. There are at least two high level user interface languages with data binding support: Macromedia XML (MXML) for Adobe Flex/Air and Extensible Application Markup Language (XAML) for Microsoft WPF/Silverlight. Both of these can be used to implement advanced graphical interfaces with little traditional programming required. Finally the crazy user interface design ideas can be delegated back to the designers who came up with them.

In the end MVVM is probably more complex to implement from ground up than MVC or MVP thanks to the dependency on data binding without which MVVM makes little sense. But if the data binding is provided by the framework such as WPF, MVVM makes it almost trivial to implement the synchronization of the View to the underlying data, simplifies the required middleware between the Model and the View/ViewModel and provides cleaner separation between the Model, View and the Controller/Presenter than either MVC or MVP.


Know your sugar

2009-05-29 01:41:51

This is probably something everyone else knows already, but here goes anyway.

Consider the following piece of C# code:

var numbers = new List<int>() { 1, 2, 3, 4, 5 };
var actions = new List<Func<int>>();
foreach (int number in numbers) {
    actions.Add(() => number);
}

foreach (Func<int> action in actions)
    Console.WriteLine(action());

Now the expected result would be a printout of 1, 2, 3, 4 and 5. The result I got when implementing a structure similar to this was a printout of 5, 5, 5, 5 and 5. This makes little sense while reading the original C# code. Fortunately I was able to figure out relatively fast that the closure for the lambda expression wasn't working. It seemed that the closure of the number was changing with the future iterations.

What was causing this? The problem is obvious when looking at the IL emitted by the compiler.

This IL corresponds to the following logic in C#

// Temporary list for the initialization. More syntactic sugar.
var temporary = List<int>();
temporary.Add(1);
// [.. Snip ..]
temporary.Add(5);

var numbers = temporary;  // numbers list from initialization.
var actions = new List<Func<int>>();  // actions list

// foreach is just syntactic sugar for a while loop. Here is the
// enumerator for that loop.
var numberEnumerator = numbers.GetEnumerator();

try {                        

  var func = null;  // Placeholder for Func<int> for some reason.

  // This is where the problems start. Lambda expressions are
  // compiled to separate classes and instantiated where required.
  // Here it is scoped OUTSIDE the while loop though which makes
  // it global to the iterations.
  var lambda = LambdaClass();

  while (numberEnumerator.MoveNext()) {

     // In the loop the compiler is assigning the current
     // enumerator value to the global lambda instance.
     lambda.number = numberEnumerator.Current;
                                               
     // I guess there is some optimization thing going on
     // here. Not important, though it is worth noting that
     // the Func<int> instance references the global lambda.
     if (func == null) {
        func = new Func<int>(lambda.method);
     }
    
     // And then the compiler adds an indirect REFERENCE to the
     // lambda which means that changes to the lambda will change
     // the stored actions.
     actions.Add(func);
  }
  
} finally {
  numberEnumerator.Dispose();
}

But.. but why? I believe this is caused by a mix of two C# syntactic features. Below is an analyzation of the two features without the other one interferencing. Without the lambda the foreach would most likely expand to the following:

// This is important. Most likely the number would be considered
// scoped outside the while loop though its declaration is not
// emitted to the IL.
int number;

while (enumerator.MoveNext()) {
    number = enumerator.Current;
    // do stuff.
}

This is hard to verify as the variables are declared on method level in the IL and not where they would be actually located. One way to verify this would be to print the memory address of the number variable inside the for loop but I was too lazy for now. Speculation is funner, right?

Closures with lambda are implemented by replacing the original variable with a field in the lambda instance. This can be demonstrated by reading the value of the number variable:

foreach (int number in numbers)
{
    int num = number;
    actions.Add(() => number);
    num = number + 1;
}

The IL emitted in this case shows two loads from the Lambda.number property which correspond to the two assignments from the number variable.

    [2] int32 num,

    // [..snip..]

    // int num = number;
    IL_0061:  ldloc.s    'CS$<>8__locals4'
    IL_0063:  ldfld      int32 Lambda.Class1/'<>c__DisplayClass3'::number
    IL_0068:  stloc.2

    // [..snip..]

    // num = number + 1;
    IL_0084:  ldloc.s    'CS$<>8__locals4'
    IL_0086:  ldfld      int32 Lambda.Class1/'<>c__DisplayClass3'::number
    IL_008b:  ldc.i4.1
    IL_008c:  add
    IL_008d:  stloc.2

So by default a normal foreach loop scopes the number variable outside the loop. It's still inside a try/finally block that the foreach emits so it isn't visible outside the real foreach construct but what matters is that the variable is technically shared between all the iterations. When forming a closure of the number, its references are replaced with the lambda.number field. Below is a combination of these two mechanisms.

// The number variable would be declared here but is now replaced
// with the lambda.
Lambda lambda = new Lambda();

while (enumerator.MoveNext())
{
    // Again, number replaced with the lambda.
    lambda.number = enumerator.Current;

    actions.Add(new Func<int>(lambda.Method));
}

So I guess it is correct behaviour - definitely not the one I expected, but it isn't completely random either.

The lesson here is that syntactic sugar is great until the abstraction it provides leaks and causes weird bugs in the software. While syntactic sugar is meant to abstract away some nasty code structures, it's worth it to know how those structures would be implemented without the syntax. This issue isn't limited to high level languages with lots of abstraction, it also comes up with lower level languages as well, consider array indexing in C/C++ for an example.


Bug tracking goes live

2009-05-27 01:25:55

For some reason programmers dislike bugs and some think that the only place that should have bugs is a bug tracker. These people do have some points, but I still don't completely agree with them. I believe there are some bugs that don't necessarily need to be in a bug tracker. Unfortunately I haven't really found that many people who agree with me so I've now bended to the peer pressure and implemented a bug tracker on this site to which I've gathered some of my bugs. The one in the title stays there though!

You better be satisfied now, Lel!


All we can agree on are the View and the Model

2009-05-22 22:55:22

Patterns for everyone

Some 40 years ago Trygve M. H. Reenskaug and some people at Xerox came up with this new thing we call Model-View-Controller. These days architectural design patterns would make for some rather cruel quizzes and since I like cruel let's have one! I just made up one of the following acronyms. Which one?

  • MVA
  • MVC
  • MVP
  • MVVM
  • POMV
  • SMVM
  • TMVE

Of course that'd be the Plain Old Model-View (POMV) which I just made up to represent the traditional way of not having anything sitting between the Model and the View. Coming up with yet another MV-Pattern was not the point of this article though. I'm more interested in the existing ones and what problems they are trying to solve. Also it is probably worth pointing out that this is not meant as an exhaustive study of the patterns so if you are looking for that, go ask the Google!

The underlying problem

Let's approach the problem of software design without any patterns first. It is pretty common in software development that the managment comes up with a need to view and process some data. This data might be located in their own database or it could be provided by a third party through a web service or something. What matters is that it is somehow predefined in most cases and it needs to be accessed - the first solution would of course be to teach the management some SQL or HTTP but there is an issue here. The people in management are evolved from apes and might have difficulties cross joining dozen tables or parsing HTML in their head. Even if they manage to learn some SQL, they'll soon start requesting some sort of easier user interface. They'll even be extra helpful and provide some simple interface sketches!

This is all the managers care about. They have some data and they want an interface to that. Programmers should figure out how to do that - and why not? It's easy! Let's take an example of an application which is used to input new people to a database because those INSERT INTO statements are just evil. Below is a part of an application in C# that could be used for this purpose.

Listing 1: Person creator using POMV-pattern
public partial class MyForm : Form {

    public MyForm() {
        // Initialize the graphical layout designed with the
        // Forms designer and wire the event handlers.
        InitializeComponent();

        // Populate UI controls from the model.
        DBAO model = DBAO.GetInstance();
        CompanyDropDown.ItemSource = model.Companies;
    }

    public HasCompanyCheckBox_CheckedChanged(object sender, EventArgs e) {
        // Modify the UI based on check box value.
        CompanyDropDown.Visible = HasCompanyCheckBox.Checked;
    }

    public SaveButton_Clicked(object sender, EventArgs e) {

        // Create a new person when the user clicks the save button.
        string name = NameTextBox.Text;
        Person person = new Person(name);
        
        if (HasCompanyCheckBox.Checked)
            person.Company = CompanyDropDown.SelectedItem;

        DBAO model = DBAO.GetInstance();
        model.Save(person);
    }
}

And I guess using a separate data access object instead of doing string concatenation for unparamerized SQL in the event handlers is pretty advanced in this case but I want to concentrate on the View here.

That should do the trick and the management will be happy for another week; That's when they come up with these three new features they want to have. And in a year the functionality of the one window will be built out of some thousands of code lines - in one file.

At some point the developers get frustrated and decide to move parts of the logic into another file at which point they face the question: Which lines should they move? This is the question the different architectural patterns try to answer - in different ways.

At this point the MVC is the simplest out of these. The very basic idea is to move all the non-UI things out of the view. Reading things from the Model (lines 9-10) can stay since they act upon the UI but writing to database (lines 27-28) should go as they don't really have anything to do with the UI other than taking some values as user input.

Listing 2: Person creator using MVC-pattern
public partial class MyForm : Form {

    public MyForm() {
        InitializeComponent();

        // Populate UI controls from the model.
        DBAO model = DBAO.GetInstance();
        CompanyDropdown.ItemSource = model.Companies;
    }

    public HasCompanyCheckBox_CheckedChanged(object sender, EventArgs e);
    
    public string PersonName { get { return NameTextBox.Text; } }
    public bool HasCompany { get { return HasCompanyCheckBox.Checked; } }
    public Company ParentCompany { get { return CompanyDropDown.SelectedValue; } }
    public event EventHandler SavePerson;
}

public class MyController {
    
    public MyController() {
        myView = new MyForm();
        myView.SavePerson += new EventHandler(View_SavePerson);
    }

    public View_SavePerson(object sender, EventArgs e) {

        // Create a new person when the user clicks the save button.
        string name = myView.PersonName;
        Person person = new Person(name);
        
        if (myView.HasCompany)
            person.Company = myView.ParentCompany;

        DBAO model = DBAO.GetInstance();
        model.Save(person);
    }
}

This is a rather easy solution to the original problem. The development team has now one piece of code that deals with the UI logic and anything that isn't directly related to modifying the UI will be moved to another file. Everything goes fine until someone decides that the Database needs some refactoring. This means that everything that uses the Model is suspectible to changes. The UI logic is sitll pulling information from the Model and needs to be maintained when the Model changes. The new Controller layer has large amount of functionality related to the Model and also needs to be maintained. So since the Development team is doing some refactoring they decide to solve this new problem in such a way that in future they don't need to deal with both the View and the Controller when the Model changes.

And here they need to choose between the rest of the patterns: MVP variant Passive View, MVA or MVVM. The basic idea behind these all is the same: Remove logic from the View so it's simple; Move logic to the thing between the Model and the View. The main difference is the way this is implemented which I'm not going to analyze as I'm not completely sure about all the different details myself. I'll just provide a Passive View/MVA variant of the example program.

Listing 3: Person creator using MVP/MVA -pattern
public partial class MyForm : Form {

    public MyForm() {
        InitializeComponent();
    }

    public HasCompanyCheckBox_CheckedChanged(object sender, EventArgs e) {
        // Modify the UI based on check box value.
        CompanyDropDown.Visible = HasCompanyCheckBox.Checked;
    }
    
    public string PersonName { get { return NameTextBox.Text; } }
    public bool HasCompany { get { return HasCompanyCheckBox.Checked; } }
    public Company ParentCompany { get { return CompanyDropDown.SelectedValue; } }
    public event EventHandler SavePerson;
    
    public CompanyCollection Companies {
        get { return CompanyDropDown.ItemSource; }
        set { CompanyDropDown.ItemSource = value; }
    }
}

public class MyAdapter {

    MyForm myView;
    
    public MyAdapter(MyForm view) {
        myView = new MyForm();
        
        DBAO model = DBAO.GetInstance();
        myView.Companies = model.Companies;
        
        myView.SavePerson += new EventHandler(View_SavePerson);
    }

    public View_SavePerson(object sender, EventArgs e);
}

In this version the View doesn't have any logic which is tied to the Model. The Adapter is doing all the lifting and just tells the View what to do. The only programmed logic in the View is at lines 7-10 and is dealing with the UI.

Conclusions

These samples are rather minimalistic and I'm not even mentioning the effects on testability or other things here. But I believe these samples are a sufficient for describing the differences between the patterns. I would say that the Passive View/MVA variant has the cleanest separation and the POMV variant we began with has the worst. The real question is which one would you use if you were to write this application? I'm pretty certain I'd be going with the POMV one in the start. In the current form, what are the benefits of the MVC or Passive View versions?

I'm not sure cleaner separation of responsibilities is enough to offset the fact that the unabbreviated versions of the two latter variants contain 50% more code and twice the amount of code files than the first one. The point is that complex design patterns add complexity to the code and their benefits are usually noticeable only on larger programs. I have experienced this the hard way with the previous versions of this site (Picture 1). The first iterations failed because my coding style in PHP didn't provide enough control over complexity and the next iterations failed because the architecture of JavaEE resulted in too much overhead which turned the simple site into a complex problem.

Picture 1: Program complexity in terms of architectural pattern and original complexity.

So in the end the quest for the best pattern continues. We are pretty certain we want to have the database oriented stuff at a layer different than the one where we have the UI logic. But no one has yet come up with the universal solution on what we should use to glue these two layers together.

I know I didn't explain the MVVM pattern. I skipped it for now because I'm pretty certain I will be writing something about it soon enough and in more depth as I currently consider it one of the best patterns. But this is my strong opinion.


OpenID: authentication and why we want it

2009-05-21 03:37:30

Large portion of the Internet requires some sort of authentication from the users these days. This introduces two problems from user perspective. The obvious one is that users will have a heap of different authentication credentials they need to remember. The second problem is the fact that the web site must store the credentials in some way - and this way, whatever it is, is designed and implemented by humans. And since humans are.. well.. humans.. there is always a chance that the storage system contains a vulnerability which allows a third party to steal the passwords.

Fortunately in 2005 some smart people at Six Apart came up with an alternative way to authenticate users on different sites. OpenID is a distributed authentication system which allows sharing one set of credentials between several sites. OpenID does not require a specific provider so anyone is free to use whatever provider they trust such as Google or myOpenID and since the sole purpose of OpenID providers is to provide a secure way of authenticating the user I'm pretty sure that they are more likely to get that right than an average developer.

But why even have a login here? I mean.. it's not like there will be more than two users? :p

There are three different reasons really.

  1. Administration authentication
  2. Experimenting with new technologies
  3. Asserting identity for comments

The first point should be pretty obvious. I don't want all the people who find my secret admin URL to be able to create new posts on the site so administration operations require authentication.

The second point is explained at the top of the sidebar. One of the largest purposes for this whole environment is to allow me to experiment with new technologies. OpenID is one of these.

So that leaves the third option, which is something I consider essential for any serious platform and feel strongly about so let me explain.. I understand that the possibility for anonymity is kind of a core value for the Internet and this is not something I'm trying to dispute. My problem with anonymity is the way many people abuse it.

The issue with lying is that if you get caught, no one is going to trust you any longer. But who won't they trust if people can't tell one anonymous poster from another? They won't trust anyone and this causes problems with serious discussions. Companies such as Amazon know this first hand with their user review systems and Amazon is trying to solve this through their Real Name attribution program.

My goal in providing OpenID authentication on the site is similar to that of Amazon's with their Real Name system. OpenID allows users to provide a (hopefully) trusted third party who can validate their identity. Of course some url alone does little to assert credibility of the person behind a statement. Fortunately there is one neat thing more in OpenID which solves this problem!

OpenID allows delegating the authentication to a provider. So you can use any url you are controlling as your OpenID user name. For example jubjub.homeip.net contains the OpenID links required for delegation. This means I can authenticate to an OpenID enabled site by supplying the address of my own site. This way the other site can immediately validate my identity and connect it to the original site which can then be used as the basis for my credibility.

I know there are those people who feel you should never post any real information to the Internet due to the threat of identity theft. The only thing where I agree with these people is that you should not post private information such as social security numbers or bank account details in public places. Private information does not equal identity information though. Identity information is something that tells other people who you are such as OpenID or real name while private information is something you can use to prove that the identity information is correct (OpenID password, social security number). The problem with not asserting your identity is that anyone can claim to be you. So claiming you must stay anonymous just doesn't make sense from an identity security point of view.

And apologies for the rant. I have few people criticizing me for using my real name in the Internet so I had to express my reasons. :p


And this works!

2009-05-19 01:04:29

I have a horrible track record of getting all giddy about new stuff and starting all these super interesting projects only to get bored in half a week. I can actually count some five of such projects since January only. So I'm entitled to be happy for the fact that I actually managed to stick to a project long enough (Mighty two days!) to produce something that I can use... I mean.. I've made publishing platforms in the past. Those were mainly for photographs but this is the first time I'm writing the content through some form instead of typing a hundred word message into an SQL insert statement.

And the nice thing is that now all that remains are mostly the fun stuff such as JavaScript. One of the functions of this site is to provide me with a place where I can play with some JavaScript/AJAX. Sure there are some missing CSS and other minor stuff, but.. that can wait! I mean.. who wants to look at pretty alignments or perfect margins when they can admire the hundreth auto-suggest implementation?


Safari knows best

2009-05-19 00:51:55

Usually I have a heap of problems with CSS but this time it went pretty painlessly (Not having IE6 to test with probably has something to do with that). But was it completely painless? Hah! As if..

Safari decided it had a better idea than I about what colors I wanted to use in my images. It's not that I have something against color spaces and Safari rendering images with the correct color profile - I'm all for that. But it should render the CSS colors with the same profile in that case. If web is to default to sRGB profile, then use that for CSS and everything and not just pngs which are supposed to be same color as the css files.

I really like the rounded corners. Too bad CSS doesn't have a corner-rounding attribute. This means I had to do it myself. There are two ways to do it that I know, either make the rounded part transparent or then mask the otherwise rectangular image with opaque mask. While making the rounded part transparent sounds like the "Correct" way to do this, there are some problems with this. Especially when it comes to resizing. This is why I used masking when rounding my corners.

The benefit of this is the fact that if I ever change the header banner to a picture that actually has something else than solid color to the left, the masked corner will clip correctly. If I hadn't put min-width of some 880px on the content, you'd actually see the effect already. The problem here is that Safari wants to apply sRGB color space on the mask which makes its color differ from the background.