Naming Things

This is the second post in the series ‘Introduction to Professional Programming Concepts’. The first post was What is Dependency Injection?

In programming, appropriate naming of everything is extremely important to being able to read and understand code. This applies whether you’re reading code that someone else wrote years ago, and even to code you wrote last month! With a cursory understanding of code structure and flow control, anyone should be able to read and understand your code – a person on your team, a QA engineer, even a non-technical manager. With proper naming, understanding code is not a problem.

Consider the following function:

When you’re stuck trying to figure out what a function like this is supposed to do, it can be a tedious and painful process. The function’s name is fairly cryptic, and parameter names have no meaning whatsoever. If you see code written like this, it means that the developer either didn’t care enough to take the time to make their code self-documenting, or they were simply unaware of its importance in professional software development. What if the function looked more like this?

Now, the meaning of the arguments and the purpose of the function become clear. It even highlights a possible bug – probably the customer is eligible if their number of months is equal to the minimum required! Test-driven development is great, but we just discovered a bug just by naming things properly!

This concept applies all the way through the software stack – from parameters and variable names, all the way up to class names and module or library names. I’m not going to take the hard line here that some people do – that all comments are signs of bad code – but it is true that the vast majority of comments can be replaced and improved by using proper naming to make the code self-documenting. Here are some guidelines I like to follow when it comes to naming things in code:

  • Never use one-letter parameter names, except as an iterator (i) or as a lambda input parameter
  • Never be afraid to give something a longer name if it helps with understanding its purpose
  • Class names should be nouns, method names should be verbs
  • If you are working on poorly-named code, rename each piece as you understand its purpose

I hear that Pluralsight has a new Clean Code course, and it has a naming module! I will be watching that at my earliest opportunity, and adding to this post based on what I learn. As with all my posts, this is only my opinion. I can (and will!) change it when my experience shows me where I’m incorrect.

Have other code naming tips or guidelines? Share them in the comments!

Leave the first comment

What is Dependency Injection?

This is the first in a series posts which will explain, in plain language, some important architectural concepts in professional software development. The goal of the series is to help educate both programmers who haven’t used these patterns before, and non-programmers, such as managers or those on the client end of a software development contract. I chose dependency injection for the topic of the first post because it is central to creating software that is well-factored and testable, and because it ties in closely with many other software architecture concepts.

Dependency injection is simple. Like anything, it can get a bit complex if you try to make it very generic and automate it, but at the core the concept is only this: instead of “newing up” the thing you need inside a function, let that thing be given to you. An example will help to clarify this.

Let’s say that we want to send an email every day to employees whose anniversary is the following day. Such a function might look like this:

  1. function Keep_Out_Of_Trouble_With_Spouse
  2.      // Get the list of employees we want to contact
  3.      employeeDatabase = new EmployeeDatabaseConnection()
  4.      employees = employeeDatabase.getEmployees
  6.      // Send them each an email to remind them about their anniversary
  7.      emailService = new EmailService();
  9.      for each employee in employees
  10.             if employee.Anniversary == Tomorrow
  11.                     emailService.sendAnniversaryReminderTo(employee)
  12.      end
  13. end

This function is fairly well-factored – the finding of employees by anniversary date is taken care of by the EmployeeDatabaseConnection class, and the construction and sending of the anniversary reminder email is delegated to the EmailService. So far, so good – we can change the logic of either of those components without having to change our function. But what happens when we want to test this function? As it stands, we will end up sending a lot of (possibly incorrect – we’re just testing after all!) emails to employees during testing.

The way to eliminate that side effect during testing is dependency injection. If we inject the email service, we get:

  1. function Keep_Out_Of_Trouble_With_Spouse(IEmailService emailService)
  2.      // Get the list of employees we want to contact
  3.      employeeDatabase = new EmployeeDatabaseConnection()
  4.      employees = employeeDatabase.getEmployees
  6.      // Send them each an email to remind them about their anniversary
  7.      for each employee in employees
  8.           if employee.Anniversary == Tomorrow
  9.                emailService.sendAnniversaryReminderTo(employee)
  10.      end
  11. end

Note how instead of creating the email service within our function, we’re receiving it as a parameter to our function. Also note that the type of the parameter is IEmailService. This means that instead of saying “we have to have an EmailService!” we’re saying “We just need something that can handle the functions we’re going to call”. The way to define that is an Interface. For testing, we could have a class called ConsolEmailService which looks like this:

  1. public class ConsoleEmailService extends IEmailService
  2.      function sendAnniversaryReminderTo(employee)
  3.           Console.WriteLine("Sending anniversary reminder to: " + employee.Name
  4.      end
  5. end

Ahh, that’s better! Now we can test to our heart’s content without worrying about flooding our beloved employees’ inboxes. But we still have a problem – any time we test, we don’t know how many employees in the database might have an anniversary coming up. It could be a hundred, or it could be none. Not a very good situation to be in when you want to test for a consistent result. Like the EmailService, the EmployeeDatbaseConnection can be injected as well. Let’s see what that would look like:

  1. function Keep_Out_Of_Trouble_With_Spouse(IEmailService emailService, IEmployeeRepository employeeRepository)
  2.      // Get the list of employees we want to contact
  3.      employees = employeeRepository.getEmployees
  5.      // Send them each an email to remind them about their anniversary
  6.      for each employee in employeesWithAnUpcomingAnniversary
  7.           if employee.Anniversary == Tomorrow
  8.                 emailService.sendAnniversaryReminderTo(employee)
  9.      end
  10. end

I’ve used the name “IEmployeeRepository” here to touch on the fact that using the repository pattern is generally a good way to access your data – the repository can take care of retrieving raw data and filtering or transforming it for use by other parts of the application. But other than that, it’s the same story – now we don’t need a database connection per se, but just something that can handle a call to getEmployeesWithAnniversaryOn(). That might look something like this:

  1. public class MockEmployeeRepository extends IEmployeeRepository
  2.      function getEmployees
  3.           bob = new Employee { Name = "Bob", Anniversary = Today – 1 }
  4.           jim = new Employee { Name = "Jim", Anniversary = Today }
  5.           pat = new Employee { Name = "Pat", Anniversary = Today + 1 }
  6.           sue = new Employee { Name = "Sue", Anniversary = Today + 2 }
  8.           return new Employee[] { bob, jim, pat, sue }
  9.      end
  10. end

Now we know that whenever we use the MockEmployeeRepository, we can expect to get back one employee whose anniversary is tomorrow, and three that aren’t. Much better for testing!

Leave the first comment

My new favorite Linux VPN Provider

So, for the past six months or so, I’ve been using a Linux VPN service called Digital Ocean. These guys are awesome, and because of that they’re growing super fast. They just opened up their second data center in New York, and they have one in San Francisco as well. I’ve spun up instances of Debian and Ubuntu in both locations and they both perform flawlessly.

On one occasion I needed to get a linux box up quickly to help with some Python demos that were being put on at a conference. I instantiated one of their lowest-level configurations (512MB RAM, 1 CPU, 20GB of SSD storage) and we were off! Unfortunately, apparently having 10 people actively doing a bunch of stuff in IPython notebooks can be extremely taxing on a server. I think what happened is that we maxxed out the RAN and caused the server to start to swap everything out. As anyone who is familiar with the relative speeds of storage mechanisms knows, even an SSD is orders of magnitude slower than RAM.

In any case, the server started to bog down hard. No problem, I just flipped over to the admin console, upgraded the server instance to have 16GB of RAM and 8 CPU cores. Note that this can also be done via their REST API, which is awesome. Once the server booted back up, we were in business. The demo went great, and I got to save the day. Thanks, Digital Ocean!

I really haven’t found anything bad to say about this service, except that I can’t seem to get Mono to run an MVC3 app on Linux. Oh wait – that’s not their fault! But if I could get that piece of my current puzzle solved I would be super super happy.

*Note: the links I posted above are affiliate links. If this is a service you do need, but you happen to hate helping people out who tell you about awesome things, please feel free to google them or whatever.


Leave the first comment

ASP.NET MVC Helper for creating Twitter Bootstrap Form Fields

Being a good (read: lazy) programmer, when I find myself doing something over and over, I automate it. Ostensibly, this is done to save time in the long run and to prevent mistakes in repetitive work. Really though, it’s because I think doing the same thing is boring, and creating something new is fun.

One thing I got sick of recently was creating form fields for Twitter Bootstrap forms. It’s not a large or complex task, and neither is the solution. It will help reduce the number of lines in your Razor files though. If you have improvements, let me know!

  1. namespace MySweetApp
  2. {
  3.   using System;
  4.   using System.Linq.Expressions;
  5.   using System.Text;
  6.   using System.Web;
  7.   using System.Web.Mvc;
  8.   using System.Web.Mvc.Html;
  10.   public static class FormHelpers
  11.   {
  12.     public static HtmlString FormField(this HtmlHelper helper, Expression<Func> func)
  13.     {
  14.       var result = new StringBuilder();
  15.       result.Append(@"<div>");
  16.       result.Append(helper.LabelFor(func, new { @class = "control-label" }));
  17.       result.Append(@"<div>");
  18.       result.Append(helper.EditorFor(func));
  19.       result.Append(@"</div></div>");
  20.       return new HtmlString(result.ToString());
  21.     }
  22.   }
  23. }

Also, is there a good site out there for sharing code snippets? I haven’t found one. I don’t want to publish small things like this on GitHub or NuGet, but I would like to get them somewhere that’s more searchable than my blog, where they might have a chance of helping more people.

Leave the first comment