Monday, February 16, 2015

How TFS and git can play together

Playing around with Git for some days now, I see the following benefits over centralized systems (ordered by importance):
  • quick context switches between branches and quick setup of new branches
  • faster, due to fewer network traffic
  • using state-of-the-art technology, e.g. consistent style of working with open source community
  • no need to be online
  • inherent decentralized backup of repositories
  • 2-way commit (i.e. staging area) gives more fine-grained control about what to check in
TFS and git are playing together out-of-the-box since Version 2013 of Visual Studio / Team Foundation Server (let's call this TFS-git), but the problem in projects that are using TFS as a central repository (Team Foundation Version Control ("TFVC")) is that making a hard switch to TFS-git at a certain point of time will most probably be too risky in enterprise scenarios. It makes more sense to start small and first gain some experienc with DVCS to see if it fits your needs - how can this be achieved?
The solution is a hybrid way: installing git-tfs (a two way bridge between git and tfs, the platform neutral alternative is Microsofts git-tf) makes it possible to work with git locally while the remote repository stays TFVC, i.e. every developer on the project is free to decide to choose between working with the bridge or using TFS "traditionally".

To be complete, let me mention a 3rd option: there may be situations where the only need for TFS functionality is the usage of TFS build processes (i.e. no work item management and other TFS functionality). For these scenarios, it is possible to use Visual Studio and git without TFVC, hosting the "central" repository e.g. at github.

The following table contains the support of the features work item management, build process usage and gated checkin in relation to the mentioned possibilities how TFS and git can play together:

work item mgmt. build process usage gated checkin
TFS-git yes yes no
git-tfs (locally git, remote TFVC) yes yes no
git with any non-TFVC (e.g. github) no yes no

Monday, December 15, 2014

Rhino Mocks AAA syntax recommondations


The multiple models that are supported by Rhino Mocks (Standard, Record/Replay, Fluent, Act/Arrange/Assert) together with some weaknesses in the documentation make the software a bit unintuitive to use for the beginner - that was my own experience as well as the experience of several people I spoke to.
I personally prefer AAA syntax over the others, mainly due to the fact that this is the style which is used in many other testing frameworks both for server and client side testing.
2 things helped me a lot:

First, check out  the Rhino Mocks AAA Syntax Quick Reference assembled by Sven - thanks a lot!

Second, following Ayende's recommendations on how to use AAA make life easier:
  • In general, prefer stubs over mocks. Mocks are only necessary for complex interactions
  • Use the static MockRepository.Generate... methods instead of newing up MockRepository (see box "Create Mocks/Stubs" in the quick reference)
  • Do not use CreateMock and StriktMock
  • Use inline constraints instead of .IgnoreArguments()

Tuesday, November 25, 2014

DDD Dos and Don'ts in a real life project

We recently reviewed our two year old DDD / Hexagonal architecture based online shop ASP.NET MVC application and tried to identify the DDD related issues which should be refactored (or at least avoid in new applications). Here is a short abstract about the list of the main findings:

Domain Anaemia

Some of the domain objects are quite anaemic. That is mainly the case in places where we are the application is integrating web services which are already covering most (or all) of the domain stuff.
An example for this is a pricing web service which takes care about customer price calculations, rebates, currency conversions and so on (in other words: a lot of business rules). Our conclusion is that it in fact makes sense to apply DDD to this pricing service – but it does not make sense to apply DDD in the parts of the consuming applications that are dealing with this topic because all you do is get the data from the pricing service, pass it through the separate layers and display it. No business rules and stuff, so no need for a domain layer.
We probably would nowadays even go a step further: we would actually prefer a pure non-DDD presentation application which is only taking care about presentation concerns and is integrating web services that are containing all the business rules and are DDD based. Like this it can be avoided to have kind of a hybrid architecture in one application (parts of the application are worth applying DDD, other parts are just passing results from the infrastructure layer to the UI). Moreover in the past it turned out that most of the “DDD worthy” stuff will sooner or later be used by other clients than our application (e.g. the prices are needed by the companies CRM system) and then it anyway makes sense to separate this parts from the application.
Other examples than the pricing service which I already mentioned would be a product service, a cart management service, an order tracking service or an availability service.

Separation of application services

We initially thought that it would make sense to separate our different application services (the “use case controllers”) from each other, e.g. we have an independent “CartApplicationService”, “CatalogApplicationService”, “PricingApplicationService” and so on.
Now we had the following situation more than once: one of these services actually had to use data that was already processed by one of the other services. Because we had defined that as being not possible (we used Visual Studio’s Architecture Diagram functionality to forbid it) the developers usually found workarounds containing duplicated code (sometimes only few lines, sometimes more) which is clearly violating the DRY principle.
This strict separation does not make sense. The reason for this is that there are basically 3 classifications of services (chapter 6 of the book "SOA in Practise" covers the details):
- basic services wrap or hide implementation details of a specific single backend and can be either data-driven or logic-driven
- composed services are using ("orchestrate") multiple basic services or other composed services
- process services handle long running workflows or business processes and are - in contrast to the other classifications - usually stateful.

Only the first of these - the basic service - does have the constraint that it must not communicate with other services. Though the author mainly talks about the classification of web services the same can be applied to application services. The important thing is to be aware of which type an application service is and deal with its dependencies accordingly. This approach is much better than finding workarounds including acceptance of DRY-violations.

Application service return types

Application services are sometimes called “use case controllers”. Might be due to this we made the mistake that we created specialized return data types (DTOs) for more or less every application service method. That certainly resulted in an explosion of the number of DTO classes and classes that are mapping domain objects to these DTOs. On the other hand, view models in our presentation layer were more or less useless. They were nearly always a 1:1 representation of the DTOs.
The preferred way is to let the application services return much fewer different data types (usually the DTO representations of the domain objects) and use view models as they are thought to be used, i.e. mapping to formats that are needed by the UI.

DAOs versus repositories
At the point of time we started modelling the application we were not aware of the differences between repositories and DAOs at all. We for instance created two assemblies within the infrastructure layer – one for database access and one for service proxies. When we started using real repositories (instead of DAOs that were named repositories) we soon needed repository implementations that contained both database access components and service proxies. Now we had the choice between creating a new third assembly containing these repositories and referencing the two others or to arbitrarily choose one of the existing assemblies for putting the repository implementations there and referencing the other assembly.
All of these solutions seem to be suboptimal – the solution is to just create one infrastructure assembly containing everything (which does not mean that every type of component should have access to all other types – which in turn can be avoided introducing Visual Studio Architecture Diagrams or using a tool like NDepend).

Monday, April 14, 2014

The famous "broken closures in loop" bug

I bet I am not the first who introduced this closure related type of bug in my javascript code:
Say you wanted to add "onclick"-functionaly to a number of similar UI Elements where the behavior for each item should only differ in one parameter - in the following simplified example the element should alert it's index within the list of elements that have the css class "someCssClass" applied:

  var elems = document.getElementsByClassName("someCssClass");  
  for (var i = 0; i < elems.length; i++) {  
     elems[i].addEventListener("click", function() {  
         alert(i);  
     });  
  }  

Expected behavior is that clicking the first UI element alerts "0", the second "1" and so on.

If you tried this out you would see that this does not work as expected. Instead, every element alerts the index of the last element.

Can you spot the bug?


The reason why the index of the last element is being displayed is that the anonymous function is being called after the loop has executed. At this point in time the value of i is already elems.length - 1 for all elements.

To fix this we need to introduce a different "lexical environment". There are multiple ways to do this, here is one which adheres to JSLint's recommodation not to make functions within a loop:


  var elems = document.getElementsByClassName("myClass");  
  for (var i = 0; i < elems.length; i++) {  
   elems[i].addEventListener("click", alertIndex(i));  
  }  
  function alertIndex(i) {  
   return function() {  
    alert(i);  
   };  
  }  

But why is this working?

The reasons are:

1. With the introduction of function "alertIndex" we introduced a new lexical environment. The interpreter works in a way that it is traversing up the lexical environments until it finds the appropriate variable (and "encloses" it as it would be it's own variable - therefore the denomiation "closure"). In that case it does not find it in the anonymous function which is triggering the alert but one level up inside "alertIndex".

2. Variables in outer lexical environments might change, but inner lexical environments do always see the last value.

More about lexical environments and closures can be found at http://javascript.info/tutorial/closures



Monday, November 18, 2013

Repositories vs. DAOs

Dealing with DDD for some time now, I asked myself the following question:

What is the difference between a Repository and a DAO (Data Access Object) ?

The reason for the question was that in many repositories (real world projects and tutorials on the web) I could not see much difference to good old DAOs.

Let's say you we have a functionality which is grabbing customers out of your database - seems to be modern to call stuff like this "CustomerRepository" - I personally doubt that this is what DDD is aiming at.
I started searching on the web but it was not so easy to find a precise answers but finally I stumbled over a very good blog post with illustrative examples. You definitely should check this out. I just would like to abstract it by opposing different aspects of repositories and DAOs:



Repository DAO
"business interface" speaking ubiquitous domain language "technical interface" contracting between data source and OO application
Close to domain Close to data source
typically one per aggregate root typically one per database table (or web service operation)
containing one or multiple DAOs used by a repository
interfaces in domain layer interfaces in infrastructure layer
parameters of interface methods are domain types parameters of interface methods are reflecting the data source
implementations in infrastructure layer (lots of technical plumbing) implementations in infrastructure layer (purely technical)

Friday, October 11, 2013

The seven falsy values in JavaScript

JavaScript is different from other languages regarding the evaluation if a value is true or false.
The easiest way is to remember the 7 values that are evaluated to "false".
Here they are (some of them are obvious, some are a bit surprising):
  • undefined
  • null
  • false
  • +0
  • -0
  • NaN
  • "" (empty string)
Everything else (e.g. objects, arrays, numbers, strings, regular Expressions ...) evaluates to "true".

This behavior can be used in different ways, e.g. shortening the check if a jQuery selector returns elements or not:

if ($('#foo').length > 0) {
    ...
}

can also be checked as follows (because jQuery returns an array of length 0 which is evaluated to "false"):

if ($('#foo').length) {
    ...
}

Note that you can produce subtle bugs if you are not aware of the evaluation rules.
Example:

function printLineItem(article, price) {
    if (article && price) {
        console.log("Article: " + article + "Price: " + price);
    }
}

printLineItem("Amiga 500", 999);
printLineItem("5 bitcoins voucher for next purchase", 0);

Bad luck for the customer, he won't get the voucher :-(

Friday, July 19, 2013

JavaScript type checks

JavaScript type checks have slight complexity. This and the reason that your code should be consistent through your project(s) make it necessary that type checks are part of your javascript programming guidelines.
I am using the recommodations from the jQuery project.

They say:

String
 typeof object === "string"  
Number
 typeof object === "number"  
Boolean
 typeof object === "boolean"  
Object
 typeof object === "object"  
Plain Object
 jQuery.isPlainObject(object)  
Function
 jQuery.isFunction(object)  
Array
 jQuery.isArray(object)  
Element
 object.nodeType  
null
 object === null
null or undefined
 object == null
undefined
     Global Variables
 typeof variable === "undefined"
     Local Variables
 variable === undefined
     Properties
 object.prop === undefined