Jeremy Miller has been commissioned by Addison Wesley to write a book on Presentation Patterns. He has chosen to do this the Martin Fowler way by using a wiki engine and making it available to the public as he writes it. This book is targeted directly at the “How”s of writing  desktop applications and rich clients using WPF and Silverlight. Here is a brief description from the site:

Inside of an enterprise application, the user interface layer can be very complex in its own right and is a huge source of potential bugs because of the element of human interaction. This book will present the design patterns that can be used to manage the complexity of user interface code. The book will discuss patterns for organizing the responsibilities of a single screen, coordinating the activities of multiple screens within an application, and architecting a structure that allows a desktop application to be efficiently extended over a longer lifecycle.


 
Categories: Development | Fundamentals

I was just reading Ayende’s post on coding pitfalls and it’s associated comments. This struck me as less about pitfalls and more about pet peeves. A personal pet peeve of mine is when I discover a block of code that makes multiple calls out to fetch a single value while processing.

For example:

if(Call.ToSomethingByName("Name") != "foo") {
  if(Call.ToSomethingByName("Name") !="bar")
    var something = Call.ToSomethingByName("Name");
    processNonFoos(something);
  else
    var someotherthing = Call.ToSomethingByName("Name");
    processFoos(something);
}

Just seeing this kind of construct tells me the person who wrote it was not thinking about anything other than “make it work”. They were so focused on getting the task at hand done and moving on they didn’t stop to think about the all the possible gotchas and potential failure cases.

This code was most likely tested by hitting F5, plugging some text into a form and clicking submit. As long as no errors were thrown the developer moves on to the next task.

Just looking at this code, how many possible failure points do you see? What happens if Call.ToSomethingByName(“Name”) return null? What happens if Call.ToSomethingByName(“Name”) makes calls to the database? What happens if Call.ToSomethingByName(“Name”) returns something different on each call?


 
Categories: Development | Fundamentals

ASP.NET MVC is all the rage right now in the .NET space. But did you know that MVC is a pattern that has been around for decades? And there are other communities of developers that have been using it to produce websites for years. Here are a set of videos from the Ruby on Rails community about the common pitfalls in MVC development.


 
Categories: Fundamentals | Random

YAGNI, "you aren't gonna need it" (should maybe have a sub-principal of "will prolly come back around to bite you in the ass later"), is a principal that gets tossed around a lot to keep gold plating developers like me in check. I just love traveling down bunny trails adding "wouldn't it be cool if..." features to the code I am working on. I recognize this this fault in myself and routinely stop to ask myself, "why am I doing this?" or "how does this relate to the task at hand?" maybe even a "what effects could this have in other areas of the system?" on occasions where I am feeling extra saucy.

I wish someone had asked those questions of the person who wrote this code that I discovered deep in the bowls of "the code base that must not be named".

public void CleanData(DataRow row, int upperLimit)
{
if ((row == null))
{
return;
}

//Look at each field in this row
for (int i = 0; i <= upperLimit; i++)
{
//If this field is null, change the value of the field to some type of empty value
if ((row.ItemArray.GetValue(i)) == DBNull.Value)
{
// Handle all possible types of data in a datatable
switch (row.Table.Columns[i].DataType.Name)
{
case "Boolean":
row[i] = false;
break;

case "Byte":
row[i] = (byte) 0;
break;

case "Byte[]":
row[i] = 0;
break;

case "DateTime":
row[i] = DateTime.MinValue;
break;

case "Decimal":
row[i] = (decimal) 0;
break;

case "Double":
row[i] = (double) 0;
break;

case "Int16":
case "Int32":
case "Int64":
row[i] = Conversions.ToInteger(0);
break;

case "Long":
row[i] = Conversions.ToLong(0);
break;

case "Short":
row[i] = (short) 0;
break;

case "Single":
row[i] = (float) 0;
break;

case "String":
row[i] = "";
break;

//If a type shows up that is not handled, throw a meaningful exception
default:
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
Resources.InvalidConversionDataType,
row.Table.Columns[i].DataType.Name));
}
}
 

Now at first glance, this doesn't seem that bad. A very nice example of gold plating. I can hear the developer now saying to him or herself, "wouldn't it be cool if we never had to check for DBNull? Seriously that would be jalapeno hot!"

I wonder if the developer was thinking about this possible unintended consequence that I am currently working to resolve.

yagnidoh

So, now I have nonsense dates being rendered out to my page. Trying to address this issue at the source, I commented out the line that sets dates to a min value in the clean data method to see what happens.

yagniuberdoh

Well that is interesting. To make it perfectly obvious _StaffMember is a hashtable. And the value of it's Staff_Lockout_Datetime key is and empty string. And this error is being caused by me switching a low level data clean up method to not change a null value to a invalid date.

So how is this hashtable created? Once again, deep in the bowls of the code base is a method called ToHashtable that takes a datarow and returns a hashtable. The interesting block of code is below.

 

For i As Integer = 0 To tableRow.Table.Columns.Count - 1

If tableRow.IsNull(i) Then

'Convert nulls to 0 or "" before putting in hashtable
Select Case tableRow.Table.Columns(i).DataType.Name

Case "Int64", "Int32", "Int16", "Decimal", "Double", "Single"

'Numeric data types
If convertDBNullIntToZero Then
ht.Add(tableRow.Table.Columns(i).ColumnName, 0)
Else
ht.Add(tableRow.Table.Columns(i).ColumnName, "")
End If

Case Else

'String, DateTime data types
ht.Add(tableRow.Table.Columns(i).ColumnName, "")

End Select

Else
'blah blah blah
End If
Next

 

So once again we have some gold plating here attempting to prevent other developers from having to check for null values. The interesting thing is why are we checking for nulls on a row that has already been though the clean process when the dataset was retrieved from the database? It seems to me this block of code has never been hit before today. Maybe our gold plate-ers are not comparing notes on all the filigree they are adorning our objects with.

The icing to this cake is the line of code where it all blows up. Look at it. What are they really trying to do?

If CDate(_StaffMember("Staff_Lockout_Datetime")) <> CDate(Nothing) Then

All they really want to know is if the hash table value is null. Exactly what our gold plate-ers have so desperately been trying to hide from us.

So I am left with two choices:

  1. Attempt to locate all the areas in the entire application where this gold plating has caused assumptions and correct them to let null dates make their way out the UI and hope like hell I don't introduce more bizarre side effects.
  2. Come up with some goofy databinding or prerender hack to work around the invalid dates.

Both options leave a bad taste in my mouth and a strong desire to drown my sorrows with a nice Irish whiskey.


 
Categories: Development | Fundamentals

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

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

Karl Seguin of CodeBetter.com released a 79 page ebook called Foundations of Programming yesterday. Browsing the table of contents, I found a ton of good information is covered here. Some highlights include: YAGNI & DRY principals, Explicitness, Cohesion & Coupling, Domain Driven Design... The list just goes on and on and on.

If you want to read about the stuff that a giant Wrox tomb will never mention, grab this ebook as a great launching point.


 
Categories: Development | Events | Fundamentals

Stephen Bohlen of Microdesk recently posted to the ALT.NET mailing list that he plans to release his internal training material on NHibernate to the world at large. The first two, of a planned  5, are online and ready for consumption.


I have been doing some noodling with NHibernate recently, so I downloaded the screen casts and watched them this morning. The quality is excellent, the material is comprehensive and Stephen's teaching style is top notch.

If you are interested in learning what NHibernate is all about and what you can do with it, I cannot recommend these enough. Grab them here:


 
Categories: Development | Fundamentals | Tools

I have been reading a ton of the ALT.NET bloggers and mailing list lately. They are constantly talking about the methodology of software development and the tools they use. On the concept front Domain Driven Design, Inversion of Control, Separation of Concerns and Test Driven Development are all popular topics that have been stewing in my mind. I also wanted to give some of the tools like Nhibernate, Rhino.Mocks and Ninject a try. I was also itching to get into the new Microsoft ASP.NET MVC code.

For the last couple months, I have been festering in the swamp of legacy VB.NET spaghetti code and haven't had the time or motivation to write something fresh just for the sheer joy of creation. Friday, I kind of snapped, fired up Visual Studio 2008, downloaded the tool stack and started hacking away.

Things seemed to just click on all of the topics I had been reading about. I started out with NHibernate and getting a simple User entity to persist to a SQL Sever 2005 database. I then moved on to implementing the Repository Pattern for my User entity abstracting away the actual persistence to a DataProvider class wrapping NHibernate. By this time I had Factory Patterns all over the place, so I added a reference to Ninject.Core and got rid of those too. I then whipped out a MVC site to consume my new repository.

After an evening of furious experimentation, I had a complete database to web page end to end implementation of my User entity. I was stoked, still am. I am currently working on getting unit tests in place using Rhino.Mocks, integration tests on my data access layer and fully implementing CRUD in the MVC site. It is a hell of a lot of fun.

If anyone is interested in seeing what I am working on or want a simple example of using all these things together in an easily understandable way, I posted my work to CodePlex. If you are new to this stuff like I am, download it and check it out. If you are an old hat and want to give me some pointers or tips, please download it and fill me in.

If you work with me and happen to read my blog and are interested, I would love to talk to you about the project and what I learned and discovered. Hit me up.


 
Categories: Development | Fundamentals | Tools | Unit Testing

The Liskov Substitution Principal (LSP) is a concept in Object Oriented Programming that states:

Functions that use pointers or references to base classes must be able to use objects of derived classes with out knowing it.

At it's heart LSP is about interfaces and contracts as well as how to decided when to extend a class vs. use another strategy such as composition to achieve your goal.

The most effective way I have seen to illustrate this point was in Head First OOA&D. They present a scenario where you are a developer on a project to build a framework for strategy games.

They present a class that represents a board that looks like this:

Board

All of the methods take X and Y coordinates as parameters to locate the tile position in the two dimensional array of Tiles. This will allow a game developer to manage units in the board during the course of the game.

The book goes on to change the requirements to say that the game frame work must also support 3d game boards to accommodate games that have flight. So a ThreeDBoard class is introduced that extends Board.

At first glace this seems like a good decision. Board provides both the Height and Width properties and ThreeDBoard provides the Z axis.

Where it breaks down is when you look at all the other members inherited from Board. The methods for AddUnit, GetTile, GetUnits and so on, all take both X and Y parameters in the Board class but the ThreeDBoard needs a Z parameter as well.

So you must implement those methods again with a Z parameter. The Z parameter has no context to the Board class and the inherited methods from the Board class lose their meaning. A unit of code attempting to use the ThreeDBoard class as it's base class Board would be very out of luck.

Maybe we should find another approach. Instead of extending Board, ThreeDBoard should be composed of Board objects. One Board object per unit of the Z axis.

This allows us to use good object oriented principals like encapsulation and reuse and doesn't violate LSP.

LSP is a good method for discovering if you are using inheritance poorly. Try it next time you go to extend a class.


 
Categories: Development | Fundamentals