Archive for December, 2015

What Makes Good Code? – Should Every Class Have An Interface? Pt 1

What Makes Good Code? - Should Every Class Have An Interface?

What’s An Interface?

I mentioned in the first post of this series that I’ll likely be referring to C# in most of these posts. I think the concept of an interface in C# extends to other languages–sometimes by a different name–so the discussion here may still be applicable. Some examples in C++, Javaand Python to get you going for comparisons.

From MSDN:

An interface contains definitions for a group of related functionalities that a class or a struct can implement.
By using interfaces, you can, for example, include behavior from multiple sources in a class. That capability is important in C# because the language doesn’t support multiple inheritance of classes. In addition, you must use an interface if you want to simulate inheritance for structs, because they can’t actually inherit from another struct or class.

It’s also important to note that an interface decouples the definition of something from its implementation. Decoupled code is, in general, something that programmers are always after. If we refer back to the points I defined for what makes good code (again, in my opinion), we can see how interfaces should help with that.

  • Extensibility: Referring to interfaces in code instead of concrete classes allows a developer to swap out the implementation easier (i.e. extend support for different data providers in your data layer). They provide a specification to be met should a developer want to extend the code base with new concrete implementations.
  • Maintainability: Interfaces make refactoring an easier job (when the interface signature doesn’t have to change). A developer can get the flexibility of modifying the implementation that already exists or creating a new one provided that it meets the interface.
  • Testability: Referring to interfaces in code instead of concrete classes allows mocking frameworks to leverage mocked objects so that true unit tests are easier to write.
  • Readability: I’m neutral on this. I don’t think interfaces are overly helpful for making code more readable, but I don’t think they inherently make code harder to read.

I’m only trying to focus on some of the pro’s here, and we’ll use this sub-series to explore if these hold true across the board. So… should every class have a backing interface?

An Example

Let’s walk through a little example. In this example, we’ll look at an object that “does stuff”, but it requires something that can do a string lookup to “do stuff” with. We’ll look at how using an interface can make this type of code extensible!

First, here is our interface that we’ll use for looking up strings:

public interface IStringLookup
    string GetString(string name);

And here is our first implementation of something that can lookup strings for us. It’ll just lookup an XML node and pull a value from it. (How it actually does this stuff isn’t really important for the example, which is why I’m glossing over it):

public sealed class XmlStringLookup : IStringLookup
    private readonly XmlDocument _xmlDocument;

    public XmlStringLookup(XmlDocument xmlDocument)
        _xmlDocument = xmlDocument;

    public string GetString(string name)
        return _xmlDocument

This will be used to plug into the rest of the code:

private static int Main(string[] args)
    var obj = CreateObj();
    var stringLookup = CreateStringLookup();
    return 0;
private static IMyObject CreateObj()
    return new MyObject();
private static IStringLookup CreateStringLookup()
    return new XmlStringLookup(new XmlDocument());
public interface IMyObject
    void DoStuff(IStringLookup stringLookup);
public class MyObject : IMyObject
    public void DoStuff(IStringLookup stringLookup)
        var theFancyString = stringLookup.GetString("FancyString");
        // TODO: do stuff with this string

In the code snippet above, you’ll see our Main() method creating an instance of “MyObject” which is the thing that’s going to “DoStuff” with our XML string lookup. The important thing to note is that the DoStuff method takes in the interface IStringLookup that our XML class implements.

Now, XML string lookups are great, but let’s show why interfaces make this code extensible. Let’s swap out an XML lookup for an overly simplified CSV string lookup! Here’s the implementation:

public sealed class CsvStringLookup : IStringLookup
    private readonly StreamReader _reader;
    public CsvStringLookup(StreamReader reader)
        _reader = reader;
    public string GetString(string name)
        string line;
        while ((line = _reader.ReadLine()) != null)
            var split = line.Split(',');
            if (split[0] != name)
            return split[1];
        throw new InvalidOperationException("Not found.");

Now to leverage this class, we only need to modify ONE line of code from the original posting! Just modify CreateStringLookup() to be:

private static IStringLookup CreateStringLookup()
    return new CsvStringLookup(new StreamReader(File.OpenRead(@"pathtosomefile.txt")));

And voila! We’ve been able to extend our code to use a COMPLETELY different implementation of a string lookup with relatively no code change. You could make the argument that if you needed to modify the implementation for a buggy class that as long as you were adhering to the interface, you wouldn’t need to modify much surrounding code (just like this example). This would be a point towards improved maintainability in code.

“But wait!” you shout, “I could have done the EXACT same thing with an abstract class instead of the IStringLookup interface you big dummy! Interfaces are garbage!”

And you wouldn’t be wrong about the abstract class part! It’s totally true that IStringLookup could instead have been an abstract class like StringLookupBase (or something…) and the benefits would still apply! That’s a really interesting point, so let’s keep that in mind as we continue on through out this whole series. The little lesson here? It’s not the interface that gives us this bonus, it’s the API boundary and level of abstraction we introduced (something that does string lookups). Both an interface and abstract class happen to help us a lot here.

Continue to Part 2

Staying Productive

Staying Productive


I wrote a post a long while back about how I started to use Google Keep to get myself organized. Google Keep has been a go-to app for me on my phone for a long time now. I love using it to make lists of things, and I find it much more convenient than a paper notebook.

Don’t get me wrong–I think a paper notebook still has plenty of uses! I love my notebook for long running meetings with open-ended discussions or brain storming sessions. It’s great to be able to take a pen/pencil and doodle down any idea that comes to mind. When I’m having a free-form conversation, I need a free-form way to take notes.

However, my phone is something I almost always have with me–and my paper notebook isn’t. My phone allows me to take my Google Keep notes and email them to myself. It allows me to have a reminder right on my homescreen every time I unlock my phone. It’s just more convenient.

But something happened since the last time I wrote about using Google Keep. I use it more and more, and at some point I felt like I was getting less and less done. This is less about in the office and more about how productive I feel at home. So how can I be getting less done (or at least feeling that way) if I’m taking my own advice and using Google Keep to hack my TODO list?

I have tons of lists and no actions.

I think that’s the big take away. I list all the things I’m thinking about, and I keep making more lists. There’s no time frame around actioning things with the lists I’m making! So, in the spirit of continuous improvement, I set out to make some changes.


I know I wanted to make some changes with this part of my life because it was starting to weigh down on me; I didn’t feel productive. But I knew this wasn’t going to be something I’d answer over night. I kept my eyes and ears open for ideas for a little while before I thought up some tweaks.

The first thing I came across while living my alter ego was an Instagram post by Big J. Big J is this guy that’s incredibly big and incredibly strong. He’s lived the bodybuilding life and has a lot to show for it… And because being successful in the bodybuilding and strength world means being extremely motivated and hardworking, it’s no surprise I picked up this little bit from Big J:

Simple idea, right? Put some time into planning your schedule for the upcoming days. It almost seems to obvious to not be doing. I mean, don’t I do this already? I have meeting invites and stuff in my calendar for work… But, that’s right! I don’t have anything in my calendar for my own personal things that I like to do outside of work. Hmmm…

The next little tip to push me along was after a conversation with a teammate of mine at work. Our conversation was mostly about work-life balance, but my colleague was telling me about something he was trying out around forming habits. Essentially, over a period of time he’s been recording his success at keeping on top of good habits and identifying reasons why he’s sometimes missing them. Definitely right up the continuous improvement alley! Another great point he brought up was that good habits need to be introduced one at a time and only once you’ve been consistent with your other habits. By adding too much at once, you can derail the whole good habit process.

The “Staying Productive” Hack

This is the hack I’ve been implementing for a bit over a week now, and it’s helped tremendously with feeling productive!

Every night when I’m laying in bed, I spend about 5-15 minutes with my phone and I schedule personal activities in my calendar for the following day.

There it is. It’s not rocket science or something Earth shattering, but it’s definitely helping. Taking a page out of Big J’s book and a tip from my colleague, I’ve modified my schedule to introduce a very brief planning period every day. And it’s just one change that I think is helping introduce a good habit into my life.

This has helped me:

  • Stay on top of prepping food (which is a big part of the lifestyle I try to live)
  • Schedule time to relax (yes, I even schedule time for things like video games!)
  • Schedule time to blog (I run three blogs, and sometimes finding time to write feels like a chore)
  • Work on personal projects
  • … Feel like I’m being productive.

And no, I didn’t drop Google Keep–It actually helps feed into my scheduling! It’s great to look over my lists of things and try to create actions for them.

Next Steps

This simple hack is not only nothing particularly fancy, it’s also not bullet proof! But that’s okay when you’re always trying to continuously improve. Some snags I’ve run into or things I’ve thought about are:

  • How do I adjust my planned schedule when unexpected things come up? If someone drops in for a visit out of nowhere, or my car breaks down, or my dog decides to tear up the furniture, how do I make sure I can continue on with my planned schedule? Right now some things drop off the schedule or I push other things off to compensate. This hasn’t been too big of a problem so far, but sometimes this has a bit of a landslide effect and it makes the rest of the day feel unproductive. A little bit of dirt in the cogs seems to throw the whole thing off for me! This is something I’ll be thinking about as I encounter it and I’ll try to thing of some easy solutions.
  • How can I be more like Big J?! Aside from being bigger and stronger, how can I plan for more days? Big J plans every Sunday but I plan every night for the next day. Is there a happy medium? Planning every Sunday would potentially amplify the landslide effect I previously mentioned, but it would be a convenient single planning session for the whole week. Perhaps I’ll continue with the advice of my colleague and modify one part of my new habit at a time and look at planning for an extra day at a time and see how that goes!

If you’ve been making checklists and find that you’re unable to action items, try this approach! It takes only a few minutes every day, and so far I’ve been having great success in feeling productive. It’s not difficult, so it’s worth a try!

What Makes Good Code? – Patterns and Practices Series

What Makes Good Code?

It’s been a while since I’ve had a programming oriented post, and I figured this would be a great topic to write about. It’s been a topic I’ve been thinking about more and more over the last year and I’ve been experimenting with certain patterns and practices to see if certain things actually make code “better”. A lot of the information presented in this series will be completely based on my opinion, but I’ll try to back up my opinion with as many concrete examples as I can. If you have a differing opinion, I’d love to hear it in the comments.

I’d also like to call out that much of what I’ll be discussing is in the context of object oriented programming. To be specific, there may be mostly C# examples used. If this isn’t something you’re actively doing, then don’t worry! It would be great to hear if you see parallels in the work you’re doing.

What Is “Good”?

So let’s start by defining what “good” or “better” means (and I’ll leave this high level and we can dive in afterwards)…

  • Extensible: Re-writing of code is minimized when adding more functionality. It feels straight forward to extend the code. Developers won’t do “the wrong thing” when trying to extend the code.
  • Maintainable: Many of the same qualities that go with extensible. Fixing bugs or making tweaks involves touching few places in the code base.
  • Testable: It’s straight forward to write coded tests that can exercise functionality of the code under test.
  • Readable**:  Developers should be able to read code and understand what it’s doing. The flow of execution within and between different modules of code shouldn’t cause anyone a headache,

All of these describe qualities of the code. I could argue that you could write very maintainable, extensible, and testable code and it would be awful if it didn’t actually solve the customers’ needs. I’d like to try and leave this aspect out of the discussion, and focus on the actual patterns/practices that we can implement in code. I’d love to write something separate about writing code that actually solves a problem versus code that may potentially solve some possible problem at some potential point in the future (and yes, all of the uncertainty in that sentence was on purpose).

Why Should We Care?

It’s kind of a funny question, I guess, but I think it’s a fair one to ask. Why should we care what good code is? If we agree on the definition of good code, so what? Maybe those criteria for good code are obvious to some people. Maybe they weren’t so obvious to some people, but they still don’t really care. So why the fuss about what good code is?

If you’ve read other posts on DevLeader or you know me personally, you may know that I started work at a digital forensics startup a few years back in Waterloo Ontario. What you may not know is that that startup has grown significantly, and based on the accolades we’ve received as an entire organization, we’re actually one of the fastest growing software companies in North America in terms of revenue. I’m not trying to do the horn tooting without a reason though… I think one of the reasons we’ve been able to have such great success on the development side of things is because we’re always trying to improve.

We didn’t always write “good” code, and we certainly don’t always write “good” code right now. However, we’re always trying to figure out how we can get better. So why might WE care as developers at our office? I think it comes down to trade-offs.

In the real world of software development, you’re often faced with trade-offs. You can get a product out faster if you don’t test it. Or you can get a product out and test it, but maybe you had to take a lot of shortcuts in the code. Or maybe you can get all the features in the product and tested, but you can’t hit the deadline. There’s countless more combinations of trade-offs that we make in real software development every day. I think that by understanding what “good” code means allows a team to recognize just what kinds of corners they’re cutting sometimes. When teams talk about introducing “tech debt”, there’s a better grasp around what type of debt you’re introducing. If you need to get some extra features and bug fixes in but they’re getting added with some tech debt, what could that end up meaning?

Even if you don’t agree with what my criteria are for good code, I think it’s important that you establish this within your team. If everyone can agree on what good code is, it makes constructive conversations about different implementations much easier. Just because some new code is different doesn’t instantaneously make it scary and/or wrong… Maybe it’s a new way that emphasizes one of the criteria for good code a bit more than another implementation might emphasize. Perhaps it doesn’t… You can at least refer back to a reference point for what “good” is.

It’s also important to recognize that the criteria for “good” may change over time. Revisiting the definition periodically might allow you to recognize when your team is redefining what “good” means to them.

Enough Rambling! Where’s This Going?

Right. Okay. I want to write some follow up posts that will focus on a few of the following items:

  • Does every class need an interface?
  • Does every class need a factory that can create it?
  • Unit tests versus functional tests
  • Is there a benefit to only passing interfaces to objects around?
  • Is there a way to enforce that interfaces HAVE to be passed around?
  • Is the single responsibility principle even helpful?
  • Mutability and immutability
  • Is it always good to follow patterns and practices in all scenarios?

And after I feel that I’ve covered enough on these topics, I’d like to circle back and revisit what “good” code is. It’ll be cool to see if the definition changes at all!

**Readability was an after thought and I’m not sure how… I started writing the first example post for this series and QUICKLY realized I had omitted this.

  • Nick Cosentino

    Nick Cosentino

    I work as a team lead of software engineering at Magnet Forensics ( I'm into powerlifting, bodybuilding, and blogging about leadership/development topics over at

    Verified Services

    View Full Profile →

  • Copyright © 1996-2010 Dev Leader. All rights reserved.
    Jarrah theme by Templates Next | Powered by WordPress