Friday, December 31, 2010

2010 wrap-up

2010 has been a decent year. It started a bit slow, but it has been pretty productive for the last couple of months. Looking back at the goals I sat for myself in January, it seems I completed most of them:

  • Released 3 open source projects: Nollie, ViewStateToDB and AutoMock.
  • Learned the basics of jQuery, ASP.NET MVC, Silverlight and Windows Phone programming.
  • Started working with the new version of Entity Framework, "Code-First", but did not have time to look into nHibernate.
  • Wrote 33 blog posts.
  • Read a few books on design patterns and Domain-Driven Design.
  • Improved my architectural skills and testing skills.
  • Though I did not manage to become a MCPD.

All in all I'm satisfied with 2010, but hopefully 2011 will be even better.

AutoMock is out on CodePlex

The first version of AutoMock is now out on CodePlex. AutoMock is a small library that simplifies the process of doing unit testing with a mocking framework. Without AutoMock, the process of unit testing a class that uses dependency injection, involves creating mocks for each dependency and injecting these into the class under test. This is both repetitive and boring, especially on classes with many dependencies. AutoMock simplifies this process by creating the mocks for you, together with an instance of the class under test. This saves us some lines of code for every test we write, it also makes the test smaller in size, thus easier to read and understand. Check out for more information. Below is some sample code.

The class to test:
The class below uses constructor based dependency injection. It updates the data source with the customer name, writes a new event to the log and sends a notification e-mail.

public class CustomerUpdater
 private ICustomerDataProvider _customerData;
 private IMailSender _mailSender;
 private ILogWriter _logWriter;

 public CustomerUpdater(
  ICustomerDataProvider customerData,
  IMailSender mailSender,
  ILogWriter logWriter)
  _customerData = customerData;
  _mailSender = mailSender;
  _logWriter = logWriter;

 public void UpdateCustomerName(int customerId, string name, string email)
  var customer = _customerData.GetCustomer(1);

  customer.Name = name;


  _logWriter.Write(string.Format("Customer {0} has been updated", name));

  _mailSender.SendMail(email, string.Format("Customer {0} has been updated", name));

Unit test without using AutoMock:

public void UpdateCustomerName_email_should_be_sent()
 var customerData = MockRepository.GenerateStub<ICustomerDataProvider>();
 customerData.Expect(x => x.GetCustomer(0)).IgnoreArguments().Return(new CustomerItem());
 var mailSender = MockRepository.GenerateStub<IMailSender>();
 var logWriter = MockRepository.GenerateStub<ILogWriter>();

 var customerUpdater = new CustomerUpdater(customerData, mailSender, logWriter);

 customerUpdater.UpdateCustomerName(1, "Frank", "");

 mailSender.AssertWasCalled(x => x.SendMail(null, null), x => x.IgnoreArguments());

Unit test using AutoMock:

public void UpdateCustomerName_email_should_be_sent()
 var autoMocker = new RhinoAutoMocker<CustomerUpdater>();
 autoMocker.Get<ICustomerDataProvider>().Expect(x => x.GetCustomer(0)).IgnoreArguments().Return(new CustomerItem());

 autoMocker.ClassUnderTest.UpdateCustomerName(1, "Frank", "");

 autoMocker.Get<IMailSender>().AssertWasCalled(x => x.SendMail(null, null), x => x.IgnoreArguments());

Tuesday, December 28, 2010

C#: Checked and unchecked keywords

Today I came across two C# keywords that I haven't noticed before, checked and unchecked.

After some research it turns out that checked and unchecked are used to control the overflow checking of integral-type arithmetic operations and conversions. This means that by using checked, if a value is out of range for the destination type, depending on the complexity of the expression either a compile-time error will be given or a runtime exception of type System.OverflowException will be thrown. While if unchecked is used, the number will be truncated. Both of these keywords can either be used as block statements or as operators.

Unchecked example:

int i = unchecked(Int32.MaxValue);
// i is now 2147483647

int i = unchecked(Int32.MaxValue + 1);
// i is now -2147483648

Checked example:

int i = checked(Int32.MaxValue);
// i is now 2147483647

int i = checked(Int32.MaxValue + 1);
// Gives a compile-time error, "Error: The operation overflows at compile time in checked mode"

 int i = Int32.MaxValue;
// Throws a runtime exception, "System.OverflowException: Arithmetic operation resulted in an overflow".

Saturday, December 25, 2010

Convention over configuration / Coding by convention

Convention over configuration, also known as coding by convention, is a software development principle with the goal to reduce the number of decisions that developers need to make. The way to do this is to use a set of conventions in the component, where the developer only needs to specify any unconventional aspects. For example, in an object relational mapping framework (ORM) this could imply that when a class is named Contact in the code, the ORM framework would assume the corresponding table in the database would also be named Contact. If this is not the case, then it must be configured.

The great benefits of this principle are ease of use and smaller configuration files as the developers don't have to configure or know all the details of the component.

Thursday, December 23, 2010

Creating instances dynamically within a layer that uses dependency injection and an IOC container

In a project where I use dependency injection in the business layer together with an IOC container, I had a need to create instances of a type dynamically from a string value, within the business layer itself. One way to do this would be to use reflection, however since the type to create an instance of is decided one layer up (here: service layer), this is not possible. The way I ended up doing it was to inject an instance of a type that implements an interface with a Resolve method, where the type of this instance is defined in the service layer.

Class diagram:

Class diagram


1) Created an interface in the business layer:

public interface IInstanceManager
 T Resolve(string type);

2) Created a new class in the service layer that implements the IInstanceManager interface:

public class InstanceManager : IInstanceManager
 public T Resolve(string type)
  var typeInstance = Type.GetType(type);

  if (typeInstance == null)
   throw new Exception(string.Format("Type {0} was not found", type));

  return (T) _container.Resolve(typeInstance);

3) Registered the InstanceManager with the IOC container (here: Castle Windsor):


4) Modified the class that needed to create instances dynamically to accept and use an instance of a type implementing IInstanceManager:

public class ClassA : IClassA
 private IInstanceManager _instanceManager;

 public ClassA(IInstanceManager instanceManager)
  _instanceManager = instanceManager;

 public void DoSomethingOnA()
  var instance = _instanceManager.Resolve("ISomeTypeThatImplementsIClassB");

T-SQL: Remove or reduce decimal places, with or without rounding

In T-SQL, this is how you can remove or reduce the number of decimal places in a number:

With rounding:

select ROUND(55.4567, 2, 0)
-- Returns 55.4600

select CAST(55.4567 as decimal(38, 2))
-- Returns 55.46

Without rounding:

select ROUND(55.4567, 2, 1)
-- Returns 55.4500

select CAST(ROUND(55.4567, 2, 1) as decimal(38, 2))
-- Returns 55.45

T-SQL: How to get the difference in days between two dates

This is how you can get the difference in days between two dates in T-SQL:

declare @Today datetime
declare @NewYear datetime

set @Today = '2010/12/23';
set @NewYear = '2010/12/31';

select DATEDIFF(day, @today, @NewYear) as DifferenceInDays; 
-- Returns 8.

Monday, December 20, 2010

The 80-20 rule

The 80-20 rule, also known as the Pareto principle, states that roughly 80% of the effects come from 20% of the cases. If we apply this to software development it can be rephrased into a few different rules or principles:

  • 80% of the functionality will take 20% of the implementation time.
  • 80% of the functionality can be implemented for 20% of the cost.
  • 80% of the users only uses 20% of the functionality.
  • 80% of the errors and crashes will be eliminated if 20% of the top reported bugs are fixed.

Based on my own experience I agree with all of these principles. What about you?

Pet projects are required to be a good developer

The most skilled developers I know are those who work on pet projects in their spare time. A pet project can be anything from learning new technology or concepts by writing code, to creating or contributing to some real applications. Why should we do this? Well, for most of us with an 8 to 4 job there isn't enough time during the working hours to both finish our work duties and stay up to date on important principles, tools and frameworks. So if we can spend some hours off our spare time to write code it will improve our skills considerably.

Sunday, December 19, 2010

Always use strong typing

When working on a project with many developers it's highly recommended to have everything strongly typed. If things are loosely typed, a small change can break the entire application. If it's strongly typed a compile time error will be given unless it's a bug due to incorrect logic.

Some people would say that this is why we have tests. Well, few have 100% code coverage on both their unit tests and integration tests. So unless you are one of those, the key to fewer bugs is to use strong typing.