I will be attending the ALT.NET Seattle 2009 Conference this weekend February 27th - March 1st at the DigiPen Campus in Redmond, WA. If any ALT.NET people want to get together for lunch or dinner while I am there feel free to contact me via the plethora of options to the right. I will be in full on geek out mode and happy to talk with you.

Looking forward to seeing everybody.

UPDATE: I just realized I posted this with the wrong date... No wonder no body was looking for me. 8(


 
Categories: Development | Events | Local

I was asked by a few people for access to my slide deck and code samples, so here they are.

The walk though of Dependency Injection by hand and how to use Ninject was directly adapted from the documentation for Ninject written by the amazing Nate Kohari.

To learn more about the SOLID principals check out Robert "Uncle Bob" Martin's original white papers on the subject or pick up the book Agile Principals, Patterns and Practices in C#.

If you are interested in playing with an IoC container, here is the list I discussed last night:

I had a ton of fun last night, thanks for listening to me ramble.


 
Categories: Development | Events | Local

I'll be presenting on the topic of Dependency Injection at the South Sound .NET Users Group on February 12th, 2009. In an effort to beef up my presentation to close to two hours, I decided to give a brief introduction to the S.O.L.I.D. Principals as described by Uncle Bob Martin as supporting material/introduction to Inversion of Control and Dependency Injection.

You can find the the first post in this series here:

S.O.L.I.D. By Example: Single Responsibility Principal

The Single Responsibility Principal demonstrated how to keep classes simple, focused and uncluttered. The Open Closed Principal is about protecting behavior that we know works. OCP states:

You should be able to extend a classes behavior, without modifying it.

Let's jump right into the example to demonstrate the difference. Imagine that we are given a specification for an order service that saves orders to a database. Our initial implementation might look something like this:

 

public class OrderService
{
private readonly OrderRepository _orderRepository;

public OrderService(OrderRepository orderRepository)
{
_orderRepository = orderRepository;
}

public bool SaveOrder(Order order)
{
if (order.IsValid)
{
_orderRepository.Save(order);
}
return true;
}
}

 

We have a simple order service that verifies an order is valid and then saves it to an order repository. Pretty clean and it appears to conform with SRP. Good times!

Two months later we get an addendum to the specification that states the company would like the order service to also send a confirmation email out when the order is accepted and saved to the database.

No problem! We start hacking away and come up with version 2 of our class:

public class OrderService
{
private readonly EmailService _emailService;
private readonly OrderRepository _orderRepository;

public OrderService(EmailService emailService, OrderRepository orderRepository)
{
_emailService = emailService;
_orderRepository = orderRepository;
}

public bool SaveOrder(Order order)
{
if (order.IsValid)
{
_orderRepository.Save(order);
}
if (Configuration.SendEmailConfirmation)
{
_emailService.SendConfirmation(order);
}
return true;
}
}

In our edits we have modified our order service and added a dependency on a new class called email service. We have also modified the save order method to use the new email service. We also added to the complexity of the class by adding additional branching logic in the body of the save order method.

So in essence we took a class that had been written, presumably tested and functioning fine for a couple months and modified its behavior potentially breaking not only the new specification but the original at the same time.

Instead, we could approach the problem a different way to preserve the working functionality of the order service class but add additional behavior to it by extending the class.

All we would need to do is modify the original class like this:

public class OrderService
{
private readonly OrderRepository _orderRepository;

public OrderService(OrderRepository orderRepository)
{
_orderRepository = orderRepository;
}

public virtual bool SaveOrder(Order order)
{
if (order.IsValid)
{
_orderRepository.Save(order);
}
return true;
}

Note that the save order method has been marked as virtual. This allows us to provide an alternative implementation. You can look at this as opening the class up to extension of its behavior.

So to add the new specified behavior we simply inherit from order service and override the save order method like this:

public class EmailingOrderService : OrderService
{
private readonly EmailService _emailService;

public EmailingOrderService(EmailService emailService,
OrderRepository orderRepository)
: base(orderRepository)
{
_emailService = emailService;
}

public override bool SaveOrder(Order order)
{
if (base.SaveOrder(order))
{
_emailService.SendConfirmation(order);
}
return true;
}

 

We create a new emailing order service that inherits from order service. The constructor has a dependency on the original order repository which it passes along to its base class. It also adds a new dependency on email service.

The new implementation of save order delegates the saving of the order to its base class and then uses the email service to send the email confirmation.

So we have effectively added the new behavior in such a way that we are not potentially breaking the original object. We have also prevented the addition of branching complexity and overall lines of code within the save order methods.


 
Categories: Development | Fundamentals

Please join us Thursday, February 12th, to eat pizza and enjoy a informative presentation by Bobby Johnson on Dependency Injection: A Beginners Guild to Why Ninjas Are Awesome


Special thanks to Alliance Enterprises for providing pizza.


Presentation Summary
This presentation will describe the core concepts of  Dependency Injection (DI), first described by Martin Fowler in his article Inversion of Control (IoC) Containers and the Dependency Injection Pattern.


The presentation will highlight the benefits of Dependency Injection including:

  • Creating classes that are easier to unit test in isolation
  • Promotes loose coupling between classes and subsystems
  • Adds potential flexibility to a codebase for future changes
  • Can enable better code reuse


Bobby will also be sharing simple and fun examples on how to use DI along with a real world example of its use in a web-based application.


Speaker Bio
Bobby Johnson is a Senior Software Developer at Alliance Enterprises, a performance management software company based in Lacey, Washington.  As an avid enthusiast of Agile methods and a self proclaimed code monkey, Bobby is currently focused on overseeing the  implementation of Agile techniques like DDD, TDD, CI into Alliance's software and quality engineering processes.  Prior to joining Alliance, Bobby worked at the Washington State Department of Labor & Industries as a  Development Specialist.


To find out more about Bobby and his technical misadventures visit his blog at www.iamnotmyself.com
Meeting Specifics
February 12th, 7 - 9 pm
Olympia Center (222 Columbia NW)


All attendees are eligible for the prize drawings. Past prizes have included technical books, passes to Devscovery, copies of Visual Studio, Vista, Office 2007 and more.


Don't forget to let your friends and co-workers know about this meeting.  Feel free to forward this email and/or direct them to www.ssdotnet.org for more information.

That's right b@#$%es, I'm packing a posse and they are bringing the pizza.


 
Categories: Development | Events | Local

I'll be presenting on the topic of Dependency Injection at the South Sound .NET Users Group on February 12th, 2009. In an effort to beef up my presentation to close to two hours, I decided to give a brief introduction to the S.O.L.I.D. Principals as described by Uncle Bob Martin as supporting material/introduction to Inversion of Control and Dependency Injection.

 

I sat down last night and started writing sample code that demonstrated each of the principals. The first being, the Single Responsibility Principal.

"A class should have one, and only one reason to change."

For example, let's take a look at the following User class:

 

namespace Sample.BigBallOfMud
{
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }

public string GenerateUpdate()
{
return String.Format(
"UPDATE Users SET FirstName='{0}', LastName='{1}' WHERE Id={2}",
FirstName, LastName, Id);
}

public string GenerateDelete()
{
return String.Format(
"DELETE FROM Users WHERE Id={0}", Id);
}

public string GenrateInsert()
{
if (Id != 0)
throw new InvalidOperationException(
String.Format(
"This user already exists with an ID of {0}",
Id));

return String.Format(
"INSERT INTO Users VALUES ({0},{1})",
FirstName, LastName);
}

public bool IsValid()
{
return !String.IsNullOrEmpty(FirstName) &&
!String.IsNullOrEmpty(LastName);
}
}
}

 

This class represents a user and various functions that related to the concept of user. In the context of SRP this class has three distinct responsibilities:

  1. Uniquely identify and represent a user in the system.
  2. Map the user to various SQL statements for interaction with the database.
  3. Validate that the user is valid based on some business specification.

SRP tells us that each of these responsibilities should be in a separate class. Uncle Bob explains this principal best:

"Because each responsibility is an axis of change. When the requirements change, that
change will be manifest through a change in responsibility amongst the classes. If a class
assumes more than one responsibility, then there will be more than one reason for it to
change.


If a class has more then one responsibility, then the responsibilities become coupled.
Changes to one responsibility may impair or inhibit the class’ ability to meet the others.
This kind of coupling leads to fragile designs that break in unexpected ways when
changed."

Given this principal let's consider the following refactoring of the user class:

namespace Sample.SOLID
{
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}

public class UserSQLMapper
{
private readonly User _user;

public UserSQLMapper(User user)
{
_user = user;
}

public string GenerateUpdate()
{
return String.Format(
"UPDATE Users SET FirstName='{0}', LastName='{1}' WHERE Id={2}",
_user.FirstName, _user.LastName, _user.Id);
}

public string GenerateDelete()
{
return String.Format(
"DELETE FROM Users WHERE Id={0}",
_user.Id);
}

public string GenrateInsert()
{
if (_user.Id != 0)
throw new InvalidOperationException(
String.Format("This user already exists with an ID of {0}",
_user.Id));

return String.Format(
"INSERT INTO Users VALUES ({0},{1})",
_user.FirstName, _user.LastName);
}
}

public class ValidUserSpecification
{
public bool IsSatisifedBy(User user)
{
return !String.IsNullOrEmpty(user.FirstName) &&
!String.IsNullOrEmpty(user.LastName);
}
}
}

 

We now have three very specific class that are descriptive of what their responsibilities are. The User class has been decoupled from database concerns and validation concerns. It clearly represents a single concept and only needs to change when we redefine what a User is.

Database mapping concerns have been encapsulated in the UserSQLMapper class. It's sole responsibility is to map a user to various sql statements. The only reason for this class to chance is a Schema change in the database. At first glance you might say it has an additional change vector of the User class. But if we add additional properties to User, the UserSQLMapper only needs to care if we are mapping that property to the database. If we are mapping to the database, the schema has changed. So one responsibility there.

Validation of the User class has been broken out into a Specification class called ValidUserSpecification. It's responsibility is pretty clear. It answers the question, "Is this a valid user?". Specifications in this style are a nice way to do validation rules, but I'll save that for another post.

BONUS: One aspect of SRP that is not very clear from this example, is how it can lead to better design through refactoring.

One of the most common complaints about SRP is object explosion. If I am constantly breaking classes down into single responsibilities, won't I trade the complexity of large objects for the complexity of thousands of little objects?

This is a valid concern. But consider our example above. Imagine we now have 10 classes that have been broken down in this same Entity, Mapper, Specification way giving us 30. Would it not be possible to look at the set of 10 mapping classes and reduce them down to some smaller subset of classes that perform the responsibility in a generic fashion?

When things are broken down by concern like this it is far easier to consider the concern in isolation and come up with a better design for that single concern.


 
Categories: Development | Fundamentals