Saturday, May 26, 2012

Dropping The "I"

I could have sworn that I'd written something a while back about dropping the "I" in front of interfaces, but I can't seem to find it.  Maybe I had merely intended to write it.  Oh well.  In any event, what I may or may not have said before is still working very well for me.

The idea, at least when I heard it, came from good old Uncle Bob.  It's simple, really.  While I'm not entirely familiar with the idiomatic conventions in most other languages, in C# (or .NET in general, I suppose) the convention has always been to prefix interfaces with an "I".  Something like this:

public interface IModelRepository { }
public class ModelRepository : IModelRepository { }

But... why?  The IDE knows it's an interface and not a class.  So you're not doing the IDE a favor.  The developers know it's an interface because, well, it's an interface.  And the code itself shouldn't care.  It's an "encoding" in the type that harkens back to things like Hungarian Notation.  And it's unnecessary.

A while back I adopted another convention for my code.  Something more like this:

public interface ModelRepository { }
public class ModelRepositoryImplementation : ModelRepository { }

Doesn't that just feel... cleaner?  There's no unnecessary encoding, each name states exactly what it does.  The interface is a repository for some model, the class is an implementation of that repository.  Two concerns, separated.

It looks cleaner throughout the rest of the codebase as well, because the rest of the codebase doesn't care about the implementation.  It cares only about the interface.  The specific module which wires up the implementation to the interface (the service locator, if you will) is all that cares about it.  And within that code it's also much cleaner.  After all, semantically what is that code doing?  Is it supplying a repository for an I-repository?  Or is it supplying an implementation for a repository?  It just makes more sense to name the constructs by what they are and what they do.

Now, sadly, this isn't common practice.  As a consultant I often have to go with what the community collectively prescribes because the code I write will be handed off to some developer with whom I will never work.  Most likely some "resource" who was hired specifically for a support role.  (I hate calling people "resources" by the way.)

So more often than not I have to go with the I-prefix simply because it's a more commonly known pattern and is expected and understood by more people.

But, for my code (and for code where I'm the team lead on a proper ongoing team dynamic, not a drive-by consultant implementation) I love this.  Clean.

No comments:

Post a Comment