Slides from my Productivity Boosters talk at CONDG

Posted on July 22nd, 2010 in Uncategorized by Jon Kruger

Here are the slides from my Productivity Boosters talk. Some other links you might be interested in:

Create a plan of how you are going to be a productive and effective developer!


Kick It on DotNetKicks.com

I’m doing the “grok talk” at CONDG on Thursday

Posted on July 20th, 2010 in Uncategorized by Jon Kruger

I’m doing a quick little “grok talk” at the CONDG meeting this Thursday, July 22. I’ll be talking about some simple productivity tips that have helped me to get things done faster and become more productive and effective. While this does not sound very exciting and sexy as hearing Tim Wingfield talk about IronRuby, finding ways to become faster and more productive is something that we all could use.

And if I end up boring you to death (which I don’t plan on doing), you can stay and listen to Tim talk about IronRuby.


Kick It on DotNetKicks.com

Why your company should buy you a new dev machine today

Posted on May 11th, 2010 in Uncategorized by Jon Kruger

When you go to work and write code, you have one main tool that you use - your dev machine. The power of your machine will partially determine how fast you can get things done.

How often does your company buy you a new machine? Every 2 years? Every 3 years?

I don’t know many companies where developers get new machines every 2 years or less. I’m here to show you why waiting longer than this makes no sense.

It makes no sense because hardware is cheap, but developers are expensive. I’m currently on a project where I’m working on dev machines that were purchased in early 2008. I’ve worked on other projects with machines that were 6 months old that were considerably faster.

On my project, it takes about 45 seconds to compile the solution. But what if I could reduce that to 40 seconds per compile by buying a brand new top-of-the-line machine?

Let’s say that I compile every 5 minutes. So in an 8 hour day, I compile 96 times. Each day, I will save 480 seconds, or 8 minutes. If I work 1900 hours in a year (which equates to about 11 months of work days since most people have about one month of work days in PTO), I will save 1900 minutes, or 31.6 hours.

Let’s say that the average developer on your team makes $75,000 a year. If that were the case and you worked 1900 hours, you are making $39.47/hr. This means that if you save 31.6 hours of this developer’s time, you are essentially saving $1250 over the course of the year.

For $1250, I can buy a pretty good dev machine, especially if I don’t buy monitors to go with it and use existing monitors. I think I used pretty conservative numbers here too:

  • I think I could probably cut compile time by more than 5 seconds by replacing a 2-year-old machine with a new one.
  • I probably compile more than every 5 minutes (especially when I’m making failing tests pass or making little changes in the app and running the app to see if it worked).
  • I only looked at compile time — I didn’t look at how long it takes for a machine to run tests, how long it takes to run long-running database queries, or how long it takes for your app to start up.
  • I didn’t account for the productivity hit developers take because they switch their focus on to something else for 45 seconds while they wait for the solution to compile.
  • Some developers make more than $75,000, and if you’re dealing with consultants, you have higher hourly rates.
  • Many developers work more than 1900 hours a year.
  • I didn’t take into account the feeling your developers get when you reward them with shiny new hardware, which will make them feel like you really care about them.

Even with my conservative estimates, I would say it is definitely worth it to buy new machines at least every 2 years. You might even be able to argue that you should buy machines every year. You would have to do the math and see if it’s worth it.

Convincing IT managers to go for this is difficult for some reason, even when you show them the numbers. So many IT managers will tell you that spending is frozen, or that they don’t have money in the budget for hardware, or that it’s not fair to buy the dev team new machines but not buy <insert team that doesn’t really need it> new machines. Are you serious? You would rather have your developers, who are expensive relative to the cost of hardware, have to sit and wait longer for the solution to compile? This is short-sighted thinking. You’re pretty much guaranteed some level of return on that investment within a year.

If you’re going to hold your developers to a high standard, empower them to meet these expectations and make sure that you’re giving them the best tools available.


Kick It on DotNetKicks.com

I’m ready for a new kind of conference

Posted on May 7th, 2010 in Uncategorized by Jon Kruger

During the last week I was able to go to two software development conferences, the Ann Arbor Day of .NET and Stir Trek. I love these events because I get to see a lot of people that I don’t get to see on a regular basis.

On the other hand, I don’t feel like I get much out of the sessions anymore. It’s not that the sessions are bad, but I feel like I’ve heard a 100/200 level talk on pretty much everything I want to hear about. At each of these conferences there have been some talks that I have really enjoyed, but a lot that I don’t have a real interest in hearing again.

Granted, I’ve been to more of these events than a lot of people. I remember the first time I went to events like this and they were awesome. I was learning a ton of stuff and it was new and exciting.

I miss that feeling. I certainly don’t know it all. I know there is a lot that I could learn. But I guess I’m ready for a new kind of conference. Some ideas floating around in my head:

  • A conference featuring mostly 300-400 level talks
  • A BarCamp style event where anyone can sign up and show code
  • An all open space conference

I know there are conferences like this. I know I’m not the only person who thinks this because I’ve talked to other people feeling the same way. I’ve heard of some of these conferences, but they’ve been other places other than Central Ohio. For example, look at the session list for the most recent ALT.NET Seattle event and notice the difference between this event and the various Day of .NET events. Granted, the target audience is different. But I’m a part of that target audience. I don’t always have the time and money to travel to these events.

I think part of the problem is the wide breadth of technologies in the .NET space. In the last year Microsoft has released Silverlight 4, Windows Mobile 7, .NET 4, ASP.NET MVC 2, OData, and probably other stuff that I can’t remember off the top of my head. So it’s really easy to come up with an “Intro to <insert new MS tech here>” because there are so many choices. Often times these are compelling topics, don’t get me wrong. But every day I go to work and I’m working on plain old web apps or Winforms apps or WPF apps like the rest of you. I want someone to come talk about how I can do better at what I’m doing every day. Show me how to better implement design patterns, or how to test my code better, or how you structure your MVC app to take advantage of jQuery validation, or how to use some ORM, etc. Those things will help me do a better job on the projects that I’m working on today. Sure, I’m curious about Windows Mobile 7 and Silverlight and OData, but my first priority is to get better at the stuff I’m using at work right now.

I feel like I’m getting a lot of talks that might pique my curiosity about new technology, but not a whole lot about how I can improve at the stuff I already know. I’m talking about talks like Nate Kohari’s talk at MIX about how he built Agile Zen with ASP.NET MVC and jQuery. When I watched this talk, I got some ideas on how to do some things, but I also realized that Nate is doing some crazy stuff with jQuery and JavaScript that I would’ve never thought of. It showed me some things that I need to go learn that could really help me on my current ASP.NET MVC project.

Please don’t think I’m criticizing conferences like Stir Trek or the Ann Arbor Day of .NET, because they’re good events put on by volunteers who spend their own time to put it on without any compensation, and I’m really thankful that people spend their time so that we can have community events like this.

I guess I’m just looking how I can take my daily work to the next level.


Kick It on DotNetKicks.com

TDD Boot Camp — discounted rates!

Posted on May 6th, 2010 in Uncategorized by Jon Kruger

Sign up for TDD Boot Camp at the discounted rate of $750! Also, if you sign up with a group of 3 or more, you get the even more discounted rate of $600.

The bottom line is that I want to help you learn TDD and get all the benefits out of it that I get on a daily basis.


Kick It on DotNetKicks.com

Improving your validation code — a refactoring exercise

Posted on March 11th, 2010 in Uncategorized by Jon Kruger

Today we’re going to talk about validation. Most people have some concept where they validate an entity object before it is saved to the database. There are many ways to implement this, and I’ve finally found my favorite way of writing validation code. But what I think is really interesting is the thought process of the many years of validation refactoring that have got me how I do validation today. A lot of this has to do with good coding practices that I’ve picked up over time and little tricks that allow me to write better code. This is a really good example of how I’ve learned to write better code, so I thought I’d walk you through it (and maybe you’ll like how I do validation too).

In the past, I would’ve created one method called something like Validate() and put all of the validation rules for that entity inside that method. It ended up looking something like this.


public class Order
{
  public Customer Customer { get; set; }
  public IList<Product> Products { get; set; }
  public string State { get; set; }
  public decimal Tax { get; set; }
  public decimal ShippingCharges { get; set; }
  public decimal Total { get; set; }
  
  public ValidationErrorsCollection Validate()
  {
    var errors = new ValidationErrorsCollection();
    if (Customer == null)
      errors.Add("Customer is required.");
    if (Products.Count == 0)
      errors.Add("You must have at least one product.");
    if (State == "OH")
    {
      if (Tax == 0)
        errors.Add("You must charge tax in Ohio.");
    }
    else
    {  
      if (ShippingCharges > 0)
        errors.Add("You cannot have free shipping outside of Ohio.");
    }
    
    return errors;
  }
}

The problem with this approach is that it’s a pain to read the Validate() method. If you have a large object, this method starts getting really cluttered really fast and you have all kinds of crazy if statements floating around that make things hard to figure out. This method may be called Validate(), but it’s not telling much about how the object is going to be validated.

So how can we make our validation classes more readable and descriptive? First, I like to do simple validation using attributes. I’m talking about whether a field is required, checking for null, checking for min/max values, etc. I know that there is a certain percentage of the population that despises attributes on entity objects. They feel like it clutters up their class. In my opinion, I like using attributes because it’s really easy, it reduces duplication, it’s less work, and I like having attributes that describe a property and give me more information about it than just its type. On my project, I’m using NHibernate.Validator to give me these attributes, and I’ve also defined several new validation attributes of my own (just open NHibernate.Validator.dll in Reflector and see how the out-of-the-box ones are written and you’ll be able to create your own attributes with no problems). Now my class looks more like this:


public class Order
{
  [Required("Customer")]
  public Customer Customer { get; set; }
  [AtLeastOneItemInList("You must have at least one product.")]
  public IList<Product> Products { get; set; }
  public string State { get; set; }
  public decimal Tax { get; set; }
  public decimal ShippingCharges { get; set; }
  public decimal Total { get; set; }
  
  public ValidationErrorsCollection Validate()
  {
    var errors = new ValidationErrorsCollection();
    if (State == "OH")
    {
      if (Tax == 0)
        errors.Add("You must charge tax in Ohio.");
    }
    else
    {  
      if (ShippingCharges > 0)
        errors.Add("You cannot have free shipping outside of Ohio.");
    }
    return errors;
  }
}

When I put these attributes on properties, I don’t write unit tests for that validation. If I was really concerned about whether or not I put an attribute on a property, I could spend 2 seconds going and actually checking to see if that attribute was on the property instead of spending 2 minutes writing a test. It’s just so easy to use an attribute that it’s hard to screw it up. I haven’t been burned by this yet. So already I’ve eliminated some validation code that was cluttering up my validation methods and I eliminated some tests that I would’ve otherwise written.

But my Validate() method still looks messy, and it’s doing a bunch of different validations. The method name sure isn’t telling me anything about the type of custom validation that is being done.

Let’s write some tests and see where our tests might lead us.


[TestFixture]
public class When_validating_whether_tax_is_charged
{
  [Test]
  public void Should_return_error_if_tax_is_0_and_state_is_Ohio()
  {
    var order = new Order {Tax = 0, State = "OH"};
    order.Validate().ShouldContain(Order.TaxValidationMessage);
  }
 
  [Test]
  public void Should_not_return_error_if_tax_is_greater_than_0_and_state_is_Ohio()
  {
    var order = new Order { Tax = 3, State = "OH" };
    order.Validate().ShouldNotContain(Order.TaxValidationMessage);
  }
 
  [Test]
  public void Should_not_return_error_if_tax_is_0_and_state_is_not_Ohio()
  {
    var order = new Order { Tax = 0, State = "MI" };
    order.Validate().ShouldNotContain(Order.TaxValidationMessage);
  }
 
  [Test]
  public void Should_not_return_error_if_tax_is_greater_than_0_and_state_is_not_Ohio()
  {
    var order = new Order { Tax = 3, State = "MI" };
    order.Validate().ShouldNotContain(Order.TaxValidationMessage);
  }
}
 
[TestFixture]
public class When_validating_whether_shipping_is_charged
{
  [Test]
  public void Should_return_error_if_shipping_is_0_and_state_is_not_Ohio()
  {
    var order = new Order {ShippingCharges = 0, State = "MI"};
    order.Validate().ShouldContain(Order.ShippingValidationMessage);
  }
 
  [Test]
  public void Should_not_return_error_if_shipping_is_0_and_state_is_Ohio()
  {
    var order = new Order { ShippingCharges = 0, State = "OH" };
    order.Validate().ShouldNotContain(Order.ShippingValidationMessage);
  }
 
  [Test]
  public void Should_not_return_error_if_shipping_is_greater_than_0_and_state_is_Ohio()
  {
    var order = new Order { ShippingCharges = 5, State = "OH" };
    order.Validate().ShouldNotContain(Order.ShippingValidationMessage);
  }
 
  [Test]
  public void Should_not_return_error_if_shipping_is_greater_than_0_and_state_is_not_Ohio()
  {
    var order = new Order { ShippingCharges = 5, State = "MI" };
    order.Validate().ShouldNotContain(Order.ShippingValidationMessage);
  }
}

These tests are testing all of the positive and negative possibilities of each validation rule. Notice that I’m not checking just that the object was valid, I’m testing for the presence of a specific error message. If you just try to test whether the object is valid or not, how do you really know if your code is working? If you test that the object should not be valid in a certain scenario and it comes back with some validation error, how would you know that it returned an error for the specific rule that you were testing unless you check for that validation message?

I could just leave the validation code in my implementation class as is. But I’m still not happy with the Validate() method because it has a bunch of different rules all thrown in one place, with the potential for even more to get added. If I just refactor the code in the method into smaller methods, it’ll read better. So now I have this:


public class Order
{
  public const string ShippingValidationMessage = "You cannot have free shipping outside of Ohio.";
  public const string TaxValidationMessage = "You must charge tax in Ohio.";
 
  public Customer Customer { get; set; }
  public IList<Product> Products { get; set; }
  public string State { get; set; }
  public decimal Tax { get; set; }
  public decimal ShippingCharges { get; set; }
  public decimal Total { get; set; }
 
  public ValidationErrorsCollection Validate()
  {
    var errors = new ValidationErrorsCollection();
    ValidateThatTaxIsChargedInOhio(errors);
    ValidateThatShippingIsChargedOnOrdersSentOutsideOfOhio(errors);
    return errors;
  }
 
  private void ValidateThatShippingIsChargedOnOrdersSentOutsideOfOhio(
            ValidationErrorsCollection errors)
  {
    if (State != "OH" && ShippingCharges == 0)
      errors.Add(ShippingValidationMessage);
  }
 
  private void ValidateThatTaxIsChargedInOhio(ValidationErrorsCollection errors)
  {
    if (State == "OH" && Tax == 0)
      errors.Add(TaxValidationMessage);
  }
}

That’s better. Now when you read my Validate() method, you have more details about what validation rules we are testing for. This is a more natural way of writing the code when you write your tests first because it just makes sense to create one method for each test class.

Then your boss comes to you with a new rule — an Ohio customer only gets free shipping on their first order. This is a little bit trickier to test because now I’m dealing with data outside of the object that is being validated. In order to test this, I am going to have to call out to the database in order to see if this customer has an order with free shipping. How this is done I don’t really care about in this example, I just know that I’m going to have some class that determines whether a customer has an existing order with free shipping.

One of the cardinal rules of writing unit tests is that I need to stub out external dependencies (like a database), and in order to do that, I need to use dependency injection and take in those dependencies as interface parameters in my constructor. But another rule of DI is that I can’t take dependencies into entity objects. This means that I’m going to have to split the validation code out from my entity object. I’ll move them out into a class called OrderValidator, and it’ll look like this:


public class OrderValidator : IValidator<Order>
{
  private readonly IGetOrdersForCustomerService _getOrdersForCustomerService;
  public const string ShippingValidationMessage = "You cannot have free shipping outside of Ohio.";
  public const string TaxValidationMessage = "You must charge tax in Ohio.";
  public const string CustomersDoNotHaveMoreThanOneOrderWithFreeShippingValidationMessage =
    "A customer cannot have more than one order with free shipping.";
 
  public OrderValidator(IGetOrdersForCustomerService getOrdersForCustomerService)
  {
    _getOrdersForCustomerService = getOrdersForCustomerService;
  }
 
  public ValidationErrorsCollection Validate(Order order)
  {
    var errors = new ValidationErrorsCollection();
    ValidateThatTaxIsChargedInOhio(order, errors);
    ValidateThatShippingIsChargedOnOrdersSentOutsideOfOhio(order, errors);
    ValidateThatCustomersDoNotHaveMoreThanOneOrderWithFreeShipping(order, errors);
    return errors;
  }
 
  private void ValidateThatCustomersDoNotHaveMoreThanOneOrderWithFreeShipping(Order order, ValidationErrorsCollection errors)
  {
    var ordersForCustomer = _getOrdersForCustomerService.GetOrdersForCustomer(order.Customer);
    if (order.IsNew)
      ordersForCustomer.Add(order);
    else
    {
      ordersForCustomer = ordersForCustomer.Where(o => o.Id != order.Id).ToList();
      ordersForCustomer.Add(order);
    }
    if (ordersForCustomer.Count(o => o.ShippingCharges == 0) > 1)
      errors.Add(CustomersDoNotHaveMoreThanOneOrderWithFreeShippingValidationMessage);
  }
 
  private void ValidateThatShippingIsChargedOnOrdersSentOutsideOfOhio(Order order, ValidationErrorsCollection errors)
  {
    if (order.State != "OH" && order.ShippingCharges == 0)
      errors.Add(ShippingValidationMessage);
  }
 
  private void ValidateThatTaxIsChargedInOhio(Order order, ValidationErrorsCollection errors)
  {
    if (order.State == "OH" && order.Tax == 0)
      errors.Add(TaxValidationMessage);
  }
}

Notice that the OrderValidator class implements IValidator. This interface is pretty simple and looks like this:


public interface IValidator<T>
{
    ValidationErrorsCollection Validate(T obj);
}

Now that the validation class has been moved outside of the entity object, I need to know which IValidator<T> classes I need to run when I want to validate an object of a certain type. No worries, I can just create a class that will register validator objects by type. When the application starts up, I’ll tell my registration class to go search the assemblies for classes that implement IValidator<T>. Then when it’s time to validate, I can ask this registration class for all IValidator<T> types that it found for the type of entity that I need to validate and have it do the validation.

I think we could take this one step further. Currently our OrderValidator class is doing three different validations. You could argue that this violates the Single Responsibility Principle because this class is doing three things. But you might also be able to argue that it doesn’t violate the Single Reposibility Principle because OrderValidator is only doing one type of thing. Does it really matter?

What if you got a new validation rule that says that the State property on the Order can only contain one of the lower 48 U.S. states (any state other than Alaska or Hawaii). We also want to add this rule to a bunch of other entity objects that only should use the lower 48 states for their State property. Ideally, I would like to write this validation rule once and use it for all of those objects.

In order to do this, I’m going to create an interface first:


public interface IHasLower48State
{
  public string State { get; }
}

I’ll put this interface on the Order class and all of the other classes that have this rule. Now I’ll write my validation code (after I write my tests, of course!). The only problem is that it doesn’t really fit inside OrderValidator anymore because I’m not necessarily validating an Order, I’m validating a IHasLower48State, which could be an Order, but it also could be something else.

What I really need now is a class for this one validation rule. I’m going to give it an uber-descriptive name.


public class Validate_that_state_is_one_of_the_lower_48_states : IValidator<IHasLower48State>
{
  public const string Message = "State must be one of the lower 48 states.";
  
  public ValidationErrorsCollection Validate(IHasLower48State obj)
  {
    if (obj.State == "AK" || obj.State == "HI")
      errors.Add(Message);
  }
}

Some of you are freaking out because I put underscores in the class name. I put underscores in test class names, and it just seemed natural to use a very descriptive English class name that describes exactly what validation is being performed here. If you don’t like the underscores, then call it something descriptive without using underscores.

Now I change my registration class so that when you ask for all of the validation classes for an entity, it also checks for validation classes for interfaces that the entity implements.

What’s great about is that if an entity object implements IHasLower48State, it will now pick up this validation rule for free. My registration class has auto-wired it for me, so I don’t have to configure anything. I get functionality for free with no extra work! I’m creating cross-cutting validation rules where I’m validating types of entities.

Conclusion

If you made it to this point, you’re a dedicated reader after making it through all of that (or you just skipped to the end). I wrote all of this not only to show how I do validation, but also to show you the thought process I go through and the hows and whys behind how I refactor things and find better ways to write code.


Kick It on DotNetKicks.com

Software Engineering 101 - Sat., Feb. 27 - Nashville and online!

Posted on February 24th, 2010 in Uncategorized by Jon Kruger

Leon Gersing, Jim Holmes, and I are putting on our Software Engineering 101 event this Saturday, Februrary 27 in Nashville. If you’re not in Nashville (and you probably aren’t), you can watch the entire event online on LiveMeeting!

We’ll cover topics like object-oriented programming, the SOLID principles, and code metrics and we’ll spend the afternoon doing some hands-on test-driven development. This event was a lot of fun the first time we did it and I’m really looking forward to it.

You can register for this FREE event here (you need to register if you want to watch online to get the LiveMeeting info).


Kick It on DotNetKicks.com

Going independent

Posted on January 22nd, 2010 in Uncategorized by Jon Kruger

Three years ago, my three year plan was to go off on my own as an independent consultant. Well, it’s year 3 and the time has come to make it happen.

For the past four years, I have worked at Quick Solutions and I have loved it. I came into Quick Solutions never having done ASP.NET and ended up getting all kinds of experience in all kinds of different technologies. I never could’ve learned as much as I did and I certainly would not be in this spot today if it weren’t for all of the really smart people that I got to work with.

So what am I going to be doing now? I’m still going to be leading a .NET project for Quick Solutions. There will be plenty of blogging and I have some side business ideas to work on. You will most likely see plenty of me at various community events, lunches, code and coffee, and whatever else is going on.

I don’t know what the future will hold, but I always remember the line in Good Will Hunting where Robin Williams says that he’s going to put his money on the table and see what cards he’ll get. I’m really looking forward to it.


Kick It on DotNetKicks.com

Convincing others how to do TDD, OOP/SOLID talks @ CodeMash

Posted on January 9th, 2010 in Uncategorized by Jon Kruger

If you’re going to CodeMash next week, I’ll be speaking at a couple of sessions. On Wednesday morning, I’ll be doing a PreCompiler session on object-oriented programming and the SOLID principles. I’m not big on 101 level talks, so this will be very little beginner material and mostly advanced OOP ninja stuff. I know this doesn’t sound very sexy, but learning advanced OOP and SOLID has drastically improved the code that I write, which is why I’m talking about it. We’ll do some hands-on coding too, so bring your laptop and get ready to learn from each other.

I’ll also be doing a short 30-minute session on how to convince others to do test-driven development. This is a touchy, difficult task that requires lots of tact, patience, and passion for TDD, but it can be done! I’m not sure what time I’ll be doing this, but check the schedule when you get there and you should find it (it will be in the vendor session timeslot).


Kick It on DotNetKicks.com

Why you need to go to CodeMash

Posted on November 20th, 2009 in Uncategorized by Jon Kruger

This is your annual reminder that you need to go to CodeMash this coming January. I’ve gone the last two years and I look forward to it every year. In three days time you can get exposed to pretty much anything relating to software development, and as far as conferences go, it’s really cheap. So if you want to see why people are making such a big deal about Ruby, or you want to learn how to write iPhone apps, or if you want to learn how to do TDD, or just learn more about what you do at your day job, then CodeMash is for you!

Not only are there great sessions, there are open spaces going on throughout the whole conference. Open spaces are self-organizing discussions where you propose a topic that you want to talk about and put it on the board in a time slot. So not only will you have the great eyes-forward conference sessions, there are several open spaces in each time slot where you can go and talk with other people on whatever topics you can think up. Last year I spent almost the entire conference in the open spaces and I had a great time.

Every year people come from all over the country to come to CodeMash, and last year it sold out. It’s well on its way to selling out again, so go bug your boss as soon as you can and tell him or her that you need to go to CodeMash.

Oh, and I’ll be speaking at the PreCompiler (the first day of the event) on OOP, the SOLID principles, and other “clean code” tips! It’ll be an interactive session when we’ll do some coding and learn from each other, so it should be fun. I know I’m looking forward to it.

Hope to see you at CodeMash!


Kick It on DotNetKicks.com
Next Page »