December
30

Following my post on the Special Case pattern, I just wanted to give a few more examples in which the pattern proves to be really helpful. In the previous post, we talked about using the Special Case pattern when returning collections, but you can use it in other places as well.

Subclassing

Suppose we have a cached collection of User objects, and we want to fetch a specific User and save it to the database.

User user = cache.Get(”John”);
if (user != null)
{
     user.Save();
}

If we subclass User with a class called MissingUser, and have our cache object return it when it can’t find a user, we can reduce our calling code to:

User user = cache.Get(”John”);
user.Save(); 

MissingUser.Save() overrides User.Save() and does nothing.

Side note: we could definitely go with checking cache.Contains(”John”), and acting on the result, but I think this is too much detail for this level of abstraction, and may be violating Tell, Don’t Ask.

Instantiation

Suppose we want to display a User’s profile. Our User class has a string called Name and a bitmap called Picture.

User user = profiles.Get(”Mark”);
if (user != null)
{
     this.Name = user.Name; // Binding is for the weak.
     this.Picture = user.Picture;
}

When a User is not found in the profiles repository, we could make it return an instance of the regular User class, where User.Name = “Not Found”, and Picture is something like

Missing User

This way, we can just write:

User user = profiles.Get(”Mark”);
this.Name = user.Name;
this.Picture = user.Picture;

and a profile will always be displayed.

Conditioning on Instantiation

What if we wanted to check if a User exists in a managers repository, and only if it is not found, fetch it from a clerks repository? One might be tempted to write something like:

User user = managers.Get(”Ahmed”);
if (user != null)
{
     // Ahmed is a manager.
     Display(user);
}

else
{
     // Ahmed must be a clerk.
     user = clerks.Get(”Ahmed”);
     Display(user);
}

In the previous examples, we avoided the conditional (null check) by using Special Case. If you look at the requirement for this example, you’ll see that the conditional is built into it, and there is no way to get around it.

But if we use the same technique we used in the second example, we could create an instance of User, that has a boolean property called Exists, which will be populated according to the result. This way, we could express our condition much better:

User user = managers.Get(”Ahmed”);
if (user.Exists)

{
     // Ahmed is a manager.
     Display(user);
}

else
{
     // Ahmed must be a clerk.
     user = clerks.Get(”Ahmed”);
     Display(user);
}

No code saved here, but our intention is much clearer this way.

What the hell is a “if (user != null)”? English, people.

kick it on DotNetKicks.com

6
December
27

Guys, will you knock it off with returning nulls from methods? You should return Special Cases, not nulls! nulls tend to bypass any polymorphic structure, and cause code to be cluttered with null checks. For example:

public IEnumerable<Picture> GetAllPictures()
{
  if ( .. there are pictures .. )
  {
    return pictures;
  }
  else
  {
    return null;
  }
}

Oh boy, users of this method would have to check for nulls every time before they operate on it: (if they don’t they might get a NullReferenceException, which s-uhhh-cks)

var pictures = GetAllPictures();
if (pictures != null)
{
  foreach (var picture in pictures)
  {
    …
  }
}

Isn’t that null check a big distraction from the actual logic? If you use a Special Case for that enumerable and return Enumerable<Picture>.Empty(), the calling code could be reduced to:

var pictures = GetAllPictures();
foreach (var picture in pictures)
{
  …
}

Much better, no?

kick it on DotNetKicks.com

2
August
13

A hallway talk at the Alt.NET Israel Unconference got me thinking about coding standards in general, and naming conventions in particular.

I’ve seen dozens of holy wars regarding the subject of naming conventions - when a project starts, when a new team member comes along, when the team leader is replaced etc.

I used to think that a project should have a single naming convention, and everyone should follow it. Now, I’m not so sure any more. I mean, what is really so important about naming conventions? What makes a project with a unified naming convention better than a project without one?

Unity

The first argument for naming conventions is always unity. You want all your data members to look the same.

But, think of it, what is really that important about unity? What business value do you get from it? Does it cut down development time? Does it improve performance?

IMO, if one developer wants his field to be called “_identifier”, another wants “m_identifier” and the other wants “nIdentifier”, just let them! No one ever died from Hungarian notation or a “m_” prefix, I believe.

Readability

For those who still believe in Hungarian notation (or any of its siblings), readability seems to be a great argument for naming conventions.

However, Hungarian notation might have been a good argument a decade ago. Today, all IDE’s provide great intellisense, and one could determine the type of a member in a second by hovering on it.

Scope

Determining the scope of a variable (method or class) is important, but can also be easily discovered by intellisense.

Focus on What’s Important

I’m not trying to say you shouldn’t have a naming convention in your project. I’m just trying to say, don’t let it bother you so much.

Set up a naming convention at the beginning of the project, have your team members agree on it, but don’t hunt down any exception and have it fixed.

Write a unit test or get a cup of coffee instead.

Do you think naming conventions are important? Where would you draw the line?

kick it on DotNetKicks.com

5
December
26

I just saw the reddit.com comments regarding my screencast on Speed Coding with Regionerate & GhostDoc.

I just had to point out that the purpose of the screencast wasn’t to show how fast programming can be done using these tools. What I wanted to show was how to reduce typing using these tools. My only way to "impress" the audience was to do it quickly.

Programming fast reminds me of constructing the book cabinet we just bought from IKEA. The manual states that in order to construct the cabinet, all you need is a screwdriver. I used one to build half of the cabinet. However, using an electric screwdriver I was able to reduce time it took me to build the other half down to a friction of the time. It doesn’t mean that I didn’t have to understand exactly what to put where and carefully consider each step. It’s just that when I needed to do a brainless activity like screwing the damn screw, I got a lot of help from my power tool. If I wouldn’t have paused to think between each step, I would have probably attached the whole thang to the ceiling.

The same goes for programming. Personally, I think 10 times before adding a member to a class. I think carefully about the overall plan and about every step of the way. But when I do decide that I want to create a property, it is easily & quickly available by a power tool. Using these tools elevates the communication level between my thoughts and the literal representation of them (a.k.a. code). I no longer need to think about the syntax of a property and that I need to replace every reference to the exposed member inside my class, I need to think about "Encapsulate Field". Sort of like macros for the ol’ kicker.

Regarding the automatic documentation generated by GhostDoc, if anyone uses it as a complete documentation generator without manually tweaking its results, he might as well throw it to the recycle bin. GhostDoc is great when you -

  1. Have a complex method and need a tool to generate the structure for you. After generating it you should definitely tweak it to explain what your method does.
  2. Have a simple method or property which looks like
   1:          public XmlNode ParentNode
   2:          {
   3:              get;
   4:              set;
   5:          }

In such a case, running GhostDoc on it will result in -

   1:          /// <summary>
   2:          /// Gets or sets the parent node.
   3:          /// </summary>
   4:          /// <value>The parent node.</value>
   5:          public XmlNode ParentNode
   6:          {
   7:              get;
   8:              set;
   9:          }

which doesn’t really add a lot of information, but keeps things consistent with the rest of your application. This is very important when you generate big documentation files using NDoc (or any other tool) as it prevents missing / inconsistent documentation areas.

About comparing Visual Studio.Net’s refactoring tools to ReSharper, well, did I not make myself clear with free alternative?

0
August
14

I have been invited for a couple of weeks to do some coding standards work in a rather large IT department.

Basically the job is to evaluate their coding standards document and make sure it is enforced. Since coding standards documents are usually dropped on your table by your manager in your first day of work and they usually remain untouched, we have to come up with a solution that will actually force people to comply to these standards.

So I did some reading on FxCop and found this great video by Guy Smith-Ferrier that really brought me up to speed on writing custom FxCop rules in an hour. Writing these rules is a real pain and I’ll have to do my best to use existing rules and avoid creating new ones.

The only problem with using FxCop in order to apply these standards is that it will analyze entire assemblies and will produce a lot of warnings, as this IT department has dozens of large existing & legacy projects.

My challenge will be to make FxCop run without shouting too much on legacy code. I will continue to update as things progress.

2