What do CFO’s Want?

CFO’s and business owners want feedback from their programmers, which is tough when often times the better programmers have spent their lives incubating skills that borrow from their ability to return phone calls.  And costs for a web site are all over the place; from several hundred dollars for a simple revision to a hundreds of thousands of dollars for a site with vast databases, and volumes of functionality. So – when a project depends on a high level of accountability and communication, and all of them do, clients just want to know what is really happening behind the veil of code.

All consultants’ fees are based on a daily billing rate, which reflects the value they place on one day’s labor plus expected overhead expenses. These rates appear in fixed fees, monthly retainers, hourly billing or even by measuring a company’s performance.  Either way, those fees must be justified with the quality of their work combined with effective communication and reporting.

The savior of the coding hero is to maintain good internal systems and to enjoy the ability to recognize weakness and to compensate for it by surrounding one’s self with colleagues of varying skills and personalities.  This wisdom steers a client away from hiring one-man shops where “man-down” doesn’t mean the death of a project.  Consistency comes when redundancies are as present as the front-line programmer.

At Whiteboard, we make a habit of communicating internally through continual education, participation in the open source community and a diligent internal peer review process.  In doing so we encourage our staff to pay attention to the details.  It also keeps us talking, keeping all parties informed.  Upon request, our clients receive online access to reports that monitor the progress of each project, including time sheets.

We have cleaned up many messes created by one-man shops or companies who care little for the details.  And while we are grateful for the opportunity to do so, we feel your pain and look forward to providing relief.

 


Register Repository Implementations Automatically with a Castle Facility

Isn’t it annoying to have to register all your repository implementations by hand? When you get to a certain number of them, it becomes quite a task. If you want to register them for multiple interfaces, it gets even worse.

When using Windsor as your inversion of control container, separating your repository registrations into a facility is a good start.  In general though, all our repositories follow a simple pattern and should be easily registrable automatically following an algorithm.

Domain driven design tells us that the repository interfaces are a part of the domain but the implementations are not.  Therefore, we usually have two assemblies that are important.

This is a typical project layout:

Our facility needs to allow us to configure what assemblies it searches for types and the base type of the repository.

Specification

Here is a simple test describing the desired behavior:


[TestFixture]
public class RepositoryRegistrationFacilityTestFixture
{
[Test]
public void ShouldRegisterCustomerRepository()
{
var kernel = new Castle.MicroKernel.DefaultKernel();

var facility = new RepositoryRegistrationFacility(typeof (IRepository<>), typeof (Customer).Assembly);

facility.Init(kernel,
new Castle.Core.Configuration.MutableConfiguration(“facility-config”));

kernel.Resolve().ShouldBeInstanceOfType(typeof (CustomerRepository));
kernel.Resolve<IRepository>().ShouldBeInstanceOfType(typeof (CustomerRepository));

}

protected interface IRepository
{
}
protected interface ICustomerRepository : IRepository
{
}
protected class CustomerRepository : ICustomerRepository
{
}
protected class Customer
{
}
}

Implementation


public class RepositoryRegistrationFacility : AbstractFacility
{
private readonly Assembly[] assemblies;
private readonly Type genericRepositoryType;

public RepositoryRegistrationFacility(Type genericRepositoryType, params Assembly[] assemblies)
{
this.assemblies = assemblies;
this.genericRepositoryType = genericRepositoryType;
}

protected override void Init()
{
Predicate isGenericRepositoryInterface =
type =>
type.GetInterfaces().Contains(
x => x.IsGenericType && x.GetGenericTypeDefinition().IsAssignableFrom(genericRepositoryType));

IEnumerabletypes =
assemblies.Aggregate(Enumerable.Empty(), (accumulator, assembly) => accumulator.Concat(assembly.GetTypes()));

IEnumerablerepositoryInterfaces = types.Where(
type => type.IsInterface && !type.IsGenericTypeDefinition && isGenericRepositoryInterface(type));

repositoryInterfaces
.ForEach(interfaceType =>
{
Type implementor =
types.FirstOrDefault(type => interfaceType.IsAssignableFrom(type) && !type.IsAbstract);
if (implementor == null) return;

IEnumerablegenericRepositoryInterfaceTypes = implementor.GetInterfaces().Where(
x =>
x.IsGenericType &&
x.GetGenericTypeDefinition().IsAssignableFrom(genericRepositoryType));

Kernel.Register(
Component.For(interfaceType).ImplementedBy(implementor).Forward(
genericRepositoryInterfaceTypes));
});
}
}

Now in fluent configuration you can just do this:

container.AddFacility("persistent-repository-facility", new RepositoryRegistrationFacility(typeof(IRepository<>), typeof(IRepository<>).Assembly, typeof(SomethingRepository).Assembly));

I have not tested the binsor registration, but you should be able to do something like this to register it using binsor:

facility RepositoryRegistrationFacility:
genericRepositoryType: IRepository
assemblies: array(System.Reflection.Assembly, IRepository.Assembly, SomethingRepository.Assembly)

I hope this is useful.

kick it on DotNetKicks.com


State Pattern

State Pattern

The state pattern is a behavioral pattern that allows an object to partially change its type at runtime. This is useful in situations where we can not change the type of a base object, but wish to represent the state of it in encapsulated classes.

Let us consider a payroll system where employees are compensated and promoted based upon their current position.

We could use a property to store the employee’s current position.


public class Employee
{
public string Name { get; set; }

public EmployeePosition Position { get; set; }

public void Promote()
{
switch (Position)
{
case EmployeePosition.JuniorDeveloper:
Position = EmployeePosition.SeniorDeveloper;
break;
case EmployeePosition.SeniorDeveloper:
Position = EmployeePosition.TechnicalLead;
break;
case EmployeePosition.TechnicalLead:
// This is as high as it goes.
break;
}
}

public void Compensate(Accounting accounting)
{
int salary = 0;

switch (Position)
{
case EmployeePosition.JuniorDeveloper:
salary = 40000;
break;
case EmployeePosition.SeniorDeveloper:
salary = 75000;
break;
case EmployeePosition.TechnicalLead:
salary = 100000;
break;
}

accounting.Pay(this, salary);
}
}

public enum EmployeePosition
{
JuniorDeveloper,
SeniorDeveloper,
TechnicalLead
}

public class Accounting
{
public void Pay(Employee employee, int dollars)
{
// Pay the employee
}
}
This code is brittle. Changing the EmployeePosition enum requires changing multiple methods in the Employee domain object. The logic is spread thin and the encapsulation is non-existent.

A Better Way

A better way to do this is to use the state pattern. With the state pattern, the EmployeePosition enum is replaced by an abstract class representing the employees current position.

public abstract class AbstractEmploymentState
{
private readonly Employee employee;

public AbstractEmploymentState(Employee employee)
{
this.employee = employee;
}

protected virtual Employee Employee { get { return employee; } }

public abstract void Promote();

public abstract void Compensate(Accounting accounting);
}

public class Employee
{
private AbstractEmploymentState employmentState;
public string Name { get; set; }

public AbstractEmploymentState EmploymentState
{
get { return employmentState; }
set { employmentState = value; }
}

public void Promote()
{
EmploymentState.Promote();
}

public void Compensnate(Accounting accounting)
{
EmploymentState.Compensate(accounting);
}
}

public class JuniorDeveloperState: AbstractEmploymentState
{
public JuniorDeveloperState(Employee employee) : base(employee)
{
}

public override void Promote()
{
Employee.EmploymentState = new SeniorDeveloperState(Employee);
}

public override void Compensate(Accounting accounting)
{
accounting.Pay(Employee, 40000);
}
}

public class SeniorDeveloperState: AbstractEmploymentState
{
public SeniorDeveloperState(Employee employee) : base(employee)
{
}

public override void Promote()
{
Employee.EmploymentState = new TechinicalLeadState(Employee);
}

public override void Compensate(Accounting accounting)
{
accounting.Pay(Employee, 75000);
}
}

public class TechinicalLeadState: AbstractEmploymentState
{
public TechinicalLeadState(Employee employee) : base(employee)
{
}

public override void Promote()
{
// Do Nothing, this is as high as it goes for now.
}

public override void Compensate(Accounting accounting)
{
accounting.Pay(Employee, 100000);
}
}

public class Accounting
{
public void Pay(Employee employee, int dollars)
{
// Pay the employee
}
}
In this example, employees are compensated and promoted based upon their positions. The domain object, Employee, delegates these actions to the AbstractEmploymentState object.

Note how simplified the Promote and Compensate methods of Employee are:

public void Promote()
{
EmploymentState.Promote();
}

public void Compensate(Accounting accounting)
{
EmploymentState.Compensate(accounting);
}

Adding a new state, or increasing the complexity of the logic involved in compensation and promotion of the Employees is encapsulated, leaving the design flexible.

Polymorphic Employee

Ok, so polymorphism is good. Every OO programmer knows that, right? So why don’t we just make the Employee class polymorphic with subclasses for each position i.e. JuniorDeveloper, SeniorDeveloper, and TechnicalLead are all classes that inherit from Employee and implement the appropriate Compensate and Promote logic.

In this case, implementing the promote logic in the subclasses would be quite challenging as we can not change the type of a class at runtime. It could be done by changing the Promote method signature to return an Employee. The subclasses could then each implement Promote that returned an appropriate subclass of employee. However, this solution feels contrived. It is also more difficult to understand for a future maintenance programmer and could lead to hard to find bugs.

Another reason we may not wish to have a polymorphic Employee class is because there may be multiple state objects in a single domain object. What if we need not only to compensate and promote employees based upon their position, but also to assign vacation days based upon the project to which the employee is currently assigned?  A situation where we needed a class for TechnicalLeadWhoIsWorkingOnProjectX arises.

Another reason to use the state pattern instead of full blown polymorphism of the domain object is when using an ORM such as NHibernate.  NHibernate with Single Table Inheritance does not make it easy to change the type of a persistent object. You can do with with SQL, but it’s a clumsy solution.

Conclusions

The state pattern is a useful tool in a programmer’s Swiss Army Knife of design patterns.  It can help you avoid ugly switch statements and encapsulate domain logic in a flexible manner.

kick it on DotNetKicks.com

Data Transfer Objects

Data Transfer Objects Pattern

Data Transfer Objects (DTOs) are a necessary time-sink when working with SOA.  Proper SOA dictates that you must not pass domain objects across service boundaries.  In many cases, such as when using an ORM, it is extremely difficult to pass your domain objects across the service boundaries even if you choose to disregard the SOA guidance. Also, there may be good reasons why you do not want to make your domain objects serializable.

DTOs Defined

So what exactly are DTOs?  They are objects that have no behavior outside of accessors and mutators of their properties. Often times DTOs line up one-to-one with domain objects as in the following example.

///

/// Domain Object
///

 

public class Company{
private string name;
private string taxId;
public Company(string name, string taxId) {
this.name = name;
this.taxId = taxId;
}

public string Name { get { return name; } }
public string TaxId { get { return taxId; } }}

///

/// Data Transfer Object
///

 

public class CompanyDTO{
public string Name { get; set; }
public string TaxId { get; set; }}

Other times DTOs may need to carry data for a request that has no direct representation as a single object in the domain. Consider a service that needs to expose data about a company and its owner. Obviously the clients shouldn’t have to request data about the company and then data about the owner in a separate request. Doing so would incur the costs of two round trips, and the owner data is a part of a single logical unit as exposed by the service.


///

/// A company
///

 

public class Company{
private string name;
private string taxId;

public Company(string name, string taxId)
{
this.name = name;
this.taxId = taxId;
}

public string Name { get { return name; } }
public string TaxId { get { return taxId; } }

public Owner Owner { get; set; }}

///

/// Owner of a company
///

 

public class Owner{
public Company Company { get; set; }

public string FirstName { get; set; }
public string LastName { get; set; }}

///

/// Data Transfer Object
///

 

public class CompanyDTO{
public string Name { get; set; }
public string TaxId { get; set; }

public string OwnerName { get; set; }
}

From Domain Object to DTO and Back Again

The assembler pattern, a subset of the mapping pattern, is used to translate DTOs to and from domain objects.

It is possible to create a reusable conventions based assembler. I will talk more about this in the future. For small projects, the cost of creating assemblers for the DTOs is trivial. For larger ones, it is still worth the effort for the sake of encapsulation.

///

/// Assembler for Company and CompanyDTO.
///

 

public interface ICompanyAssembler{
CompanyDTO Convert(Company company);
Company Convert(CompanyDTO DTO);}

What is so useful about an object that has no behavior?

DTOs may seem like weak objects because of their lack of behavior; but this is what makes them the one object that is safe to pass across a service boundary. A client that interacts with your service may, and often will, have a different domain from the service itself. In fact, many different clients with many different domains may interact with your service. It is difficult and undesirable to share the same domain model between a service and all its potential clients.

Consider again the Company example. Let us assume that the service we are writing is a better business bureau catalog of companies. The domain object, Company, may include such methods as “FileComplaint” or “RevokeLicense.”

This service may be consumed by an auction site that wants to use the companies names and ratings but has no need to file complaints and does not have the ability to revoke a license.  The company domain object for the auction site will include methods such as “AddAuction” or “AssociateWithReview.”

Sharing the domain objects between the auction site and the better business bureau service would pollute both domains; not to mention the fact that they may, and in this example certainly would, have different owners who do not wish to share code bases.

Sharing DTOs, because of their lack of behavior, works fine though. The DTOs serve as a simple, abstracted definition for the data that the service and its clients must exchange.

DTOs also insulate your service clients from changes to the domain of the service and vice versa. You are free to change your domain objects as much as you want and leave the DTOs alone. The assembler can simply be updated as the domain objects are updated.

If the domain objects were shared by the clients, every change to a domain object would directly impact clients, greatly increasing the costs of maintaining the service.

kick it on DotNetKicks.com