Tips

Autofac Modules and Code Organization

Organizing Code With Autofac Modules

What are Autofac Modules?

I’ve been writing a little bit about Autofac and why it’s rad, but today I want to talk about Autofac modules. In my previous post on this, I talk about one of drawbacks to the constructor dependency pattern is that at some point in your application, generally in the entry point, you get allllll of this spaghetti code that is the setup for your code base.

Essentially, we’ve balanced having nice clean testable classes with having a really messy spot in the code. But it’s only ONE spot and the rest of your code is nice. So it’s a decent trade off. But we can do better than that, can’t we?

Autofac modules!

We can use Autofac modules to organize some of the code that we have in our entry point into logical groupings. So an Autofac module is an implementation of a class that registers types to our dependency container to be resolved at a later time. You could do this all in one big module, but like many things in programming, having some giant monolothic thing that does ALLLL the work usually isn’t the best.

An Example of Converting to Autofac Modules

Let’s create a simple application as an example. I’ll describe it in words, and then I’ll toss up some code to show a simple representation if it. We’ll assume we’re using dependencies passed as interfaces via constructors as one of our best practices, which makes this conversion much easier!

So our app will have a main window with a main content area and a header area. These will be represented by three objects. Our application will also have a logger instance that we pass around so classes that need logging abilities can take an ILogger in their constructor. But our logger will have some simple configuration that we need to do before we use it.

Let’s assume to start our Program.cs file looks like this:

internal sealed class Program
{
    private static void Main(string[] args)
    {
        var logger = new FileLogger();
        logger.LogLevel = LogLevel.Debug;
        logger.FilePath = "log.txt";

        var header = new FancyHeader(logger);
        var content = BoringMainContent();
        var window = new MainWindow(header, content);
        window.Show();
    }
}

Before getting comfortable with Autofac, my initial first step would be to logically group things in the main method. In this particular case, we have something simple and surprise… it’s all grouped. But my next step would usually be to pull these things out into their own methods. I do this because it helps me identify if my groupings make sense and where my dependencies are. Let’s try it!

internal sealed class Program
{
    private static void Main(string[] args)
    {
        var logger = InitializeLogging();
        var window = InitializeGui(logger);
        window.Show();
    }

    // no params passed in, so no dependencies
    // return value is an ILogger, so we have a
    // logical grouping that will provide us a logger
    private static ILogger InitializeLogging()
    {
        var logger = new FileLogger();
        logger.LogLevel = LogLevel.Debug;
        logger.FilePath = "log.txt";
        return logger;
    }

    // only parameter is a logger, so that's our dependency
    // return value is a window, so this grouping provides
    // a window for us
    private IWindow InitializeGui(ILogger logger)
    {
        var header = new FancyHeader(logger);
        var content = BoringMainContent();
        var window = new MainWindow(header, content);
        return window;
    }
}

Alright cool. So yes, this is a bit of extra code compared to the initial example, but I promise you grouping these things out into separate methods as a starting point when you have a LOT of initialization logic will help a ton. Once they are in methods, you can pull them out into their own classes. Refactoring 101 for single responsibility principle going on here 😉 BUT, we’re interested in Autofac. So what’s the next step?

We have two logical groupings going on here in our example. One is logging and the other is for the GUI. So we can actually go ahead and make two Autofac modules that do this work for us.

public sealed class LoggingModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder
            .RegisterType<FileLogger>()
            .AsImplementedInterfaces() // FileLogger will be resolved as an ILogger
            .SingleInstance() // we only ever need to use one logger instance for our app
            .OnActivated(x =>
            {
                // this handles our extra setup we had for this object
                x.Instance.LogLevel = LogLevel.Debug;
                x.Instance.FilePath = "log.txt";
            });
    }
}

public sealed class GuiModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder
            .RegisterType<FancyHeader>() // this has a dependency on ILogger, but autofac will figure it out for us
            .AsImplementedInterfaces() // FancyHeader will be resolved as IHeader
            .SingleInstance(); // we only ever need to use one instance for our app
        builder
            .RegisterType<BoringMainContent>()
            .AsImplementedInterfaces() // BoringMainContent will be resolved as IContent
            .SingleInstance(); // we only ever need to use one instance for our app
        builder
            .RegisterType<MainWindow>() // Autofac will resolve our IHeader and IContent dependencies for us
            .AsImplementedInterfaces() // MainWindow will be resolved as IWindow
            .SingleInstance(); // we only ever need to use one instance for our app
    }
}

And those are our two logical groupings for modules! So, how do we use this and what does our Main() method look like now? I’ll demonstrate with one way that works for a couple modules, but I want to follow up with another post that talks about dynamically loading modules. If you can imagine this scenario blown out across MANY modules, you’ll understand why it might be helpful.

The idea for our Main() method is that we just want to resolve the one main dependency manually and let Autofac do the rest. So in this case, it’s our MainWindow.

private static void Main(string[] args)
{
    // create an autofac container builder
    var containerBuilder = new ContainerBuilder();

    // manually register our two new modules we made
    containerBuilder.RegisterModule<LoggingModule>();
    containerBuilder.RegisterModule<GuiModule >();

    // create the dependency container
    var container = containerBuilder.Build();

    // resolve and use our main dependency by it's interface
    // (because we shouldn't care what the implementation is...
    // that was up to the configuration via modules!)
    var window = container.Resolve<IWindow>();
    window.Show();
}

In Summary…

This example showed us how to group your main initialization logic out into groups that would play nice as Autofac modules. In a really simple example, having modules might look like bloated extra code, but it already illustrated that your entry point is very simple and follows a pattern to extend (just register another module for more dependencies… and I’ll add more on this later). There’s also an obvious way to group more new logic into your application for dependencies! So discussed logging and GUI initialization, but you could extend this to:

  • User Settings
  • Analytics/Telemetry
  • Error Reporting
  • Database Configuration
  • Etc… Just add more modules!

Sometimes the pain of having a really hectic entry point isn’t realized until you’ve had to work on teams where people are modifying the same beast of an entry point all the time:

  • Simple merge conflicts in your “using” statements… Because there’s hundreds of lines of using statements at the top of the file
  • Visual studio actually CANNOT use intellisense properly when the file gets too unwieldly
  • The debugger cannot resolve variables properly when the main entry point gets too big
  • Merging and auto-conflict resolution sometimes results in code just getting blown away in the entry point… And good luck finding what went wrong in your thousands of lines of initilization

So what’s next? Well, if you keep building out your app you might notice you have tons of modules now. Your single GUI module might have to get broken out into modules for certain parts of the GUI, for example, just to keep them more manageable. Maybe you want plugins to extend the application dynamically, which is really powerful! Our method for registering modules just isn’t really extensible at that point, but it’s very explicit. I’ll be sharing some information about automatic Autofac module discovery and registration next!


ProjectXyz: Why I Started A Team For My Hobby Project

ProjectXyz - Why I Started a Team

Who Needs A Team?!

I’ve been building RPG backends for as long as I’ve been able to code. I think my first one that I made for my grade 11 class is the only RPG that I “finished”… It was text-based and all you could do was fight AI via clicking attack, buy better weapons, level up, and repeat. It was also 10000 lines of VB6 code and so brutal that I couldn’t add anything to it without copying hundreds of lines of code.

Since then, I’ve had the itch. I keep rewriting this thing. I keep taking “Text RPG” (super cool and catchy, I know) and rewriting it. I had my first visual representation of this game called Macerus (here’s another rewrite for unity), which is actually how I landed my first co-op job. But every time I’d get so far, I’d decide I needed to rewrite it because I had messed up the architecture in some way and refactoring would be too much work.

My latest attempt is called ProjecyXyz, because I can’t come up with names. And funny enough, I just Googled it while writing this article and there’s actually a company with the same name… So maybe I’ll have to get more creative. ProjectXyz is supposed to be a very generic RPG game framework that allows new systems, mechanics, and game content to be dropped in, in addition to being independent of a front end for rendering.

It’s also something I’ve been making on my own. Because I’ve been making RPG backends on my own for years now. So who needs to have a team, right?

Too Much Pride For A Team

I think initially I wanted to do this all on my own because of pride. I also don’t think it was something I was conscious about except for the fact I looked at this project as my baby and something I could control the development of. I wasn’t consciously telling myself “I have to do this on my own so that I’m better than other people” or anything silly like that.

But why would I go ask others for help? They don’t code like me. They don’t have the same investment into this idea as me. They aren’t as passionate. They might have their own ideas for how to do things too! How could I have someone like that working on MY project?

Those are all pretty naive reasons for considering to work alone though. Sure, this is my pet project and I’m going to likely feel more attached to it than anyone else. That’s probably expected. It doesn’t mean that I can’t find people that are super interested in working on something like this. They could be totally passionate about learning different aspects of creating an RPG backend.

As for having their own ideas… That’s probably one of the BIGGEST reasons in FAVOUR of having a team! It’s easy to get scared about having other people put their ideas into something you feel like is “yours”. It might have taken a few years of working in the industry (currently just passed 6 years of working at Magnet Forensics), but it’s actually very common for other people to be contributing ideas into code bases you’re working on. It happens every day. Sometimes you have design meetings or code reviews or general architectural discussions and your idea ISN’T the one that’s picked. That’s cool! As long as everyone is striving for extensible and testable code, we can make changes if we need to going forward. You don’t need to make every decision and sometimes it’s much better that way. Other people are smart too 😉

Passion is Key for a Team

While the “team” I started isn’t an official team, it’s the first time I’ve been very open to having people directly contribute to my pet project. I think one of the most obvious reasons I became comfortable with this is because I found someone that was very passionate about exploring this space.

My colleague and I were talking about some of the concepts in ProjectXyz and where I wanted to go with it. Immediately he expressed interest in map generation and how that’s always been something he wanted to explore. How can maps be procedurally generated? Can we take this concept and generate maps on the fly? What are memory and runtime constraints? How do we represent this information in code? What about persistent storage?

I could immediately tell he was very curious about how a system like this might work. After several conversations with him about how he was starting to hack up some ideas and doing research on different algorithms, I knew he was passionate about it. We discussed working on some of these things together and contributing to the project code that I have, and we’ve been going back and forth for a few weeks now sharing ideas and his progress that he’s making for map generation. I’ve been hands off only really acting as a sounding board for him.

I think having someone passionate like this is critical for a small team. There’s going to be many barriers when working on a challenging project, and it’s easy to get bogged down and lose motivation when you’re stuck. Having additional people that are passionate about seeing progress in your project means you have some support for pushing through those hard times when you might lose motivation. If my colleague comes to me and says “I’ve been stuck on this issue and maps wont generate how I want…”, then I’m more than happy to sit down with him and talk through his algorithm and maybe where there’s an issue. I’m invested in seeing his piece come to fruition. Similarly, if I’m working on something like dynamic item generation for the game and I get stuck, I know he’s there to do the exact same thing. We both want to see this thing working how we intend.

So passion is important for a team. But is it sufficient? Is it the only requirement for adding a team member?

A Team is Built on Trust

Trust! Trust is a huge part of establishing a team because you need to be able to rely on each other. As mentioned, my colleague is passionate about working on this and has an interest in map generation. But what if I had never seen any of his code before? What if I didn’t know if he’s had practice with writing extensible code, testable code, following good design practices, etc… What if?

To be honest, I probably would be pretty nervous about him contributing code. It might be a huge barrier for me. I’d want to review his code and make sure it wasn’t “polluting” my pet project. I’ve re-written this code enough times that I really don’t want to have to think about rewriting it again! If I was nervous about someone contributing code I was going to need to re-write from scratch just to have an extensible design, it might not even be worth it having them contribute in the first place. It might actually create MORE work in the long run. It sounds selfish, but if the goal of adding someone to the team is to provide a net positive effect, then having to re-write code that isn’t up to par might be a deal breaker.

But that’s not the case here. I have multiple years of experience working with this colleague closely on various projects. We align to coding practices but still have our own twist on things. We value the same things in “good” code (extensible and testable). We use many of the same design patterns in similar situations. I’ve seen enough of his code to know that most of the time my comments about it are “oh, have you considered” and not “… you need to rewrite this”.

I can trust that what he wants to contribute will be aligned to my vision. I also can trust that new ideas he introduces are probably awesome new perspective that I hadn’t thought of. I also trust that if we disagree on something, we’re open to discussing it and coming to a resolution. So trust in this case certainly removes the barrier to entry to adding additional people to my hobby project.

Should You Form a Team?

While this was a pretty general article, I just wanted to get you thinking about opening up your hobby project(s) to other people to contribute. This is something I wish I would have considered more seriously early on. Maybe I wouldn’t be re-writing my project for the millionth time!

Some general points:

  • You’re not a “worse” programmer for getting other people contributing. Good programmers need to be able to work with others!
  • Other people can have good ideas too! Sometimes, they’re even better than your own ideas 😉
  • Other people may have more knowledge or interest in areas that need to get work done that you just don’t want to do! Perfect!
  • You’ll want to try and find people passionate about working in the area your project focuses
  • You’ll want to find people that you feel like you can trust so that you’re comfortable with them working on “your baby”
  • Getting help doesn’t mean your code must be “open source”. You can still share private repositories together (i.e. consider BitBucket!)

So what do you think? Is your hobby project kind of stale because you’ve hit enough roadblocks and it’s time to get some more firepower to tackle it?

Share your thoughts below about your experiences with forming teams for your hobby projects!


Stitching – Combining Unity3D And Autofac

Stitching - Combining Unity3D And Autofac

Before We Talk About Stitching…

In Unity3D, the scripts we write and attach to GameObjects inherit from a base class called MonoBehaviour (and yes, that says Behaviour with a U in it, not the American spelling like Behavior… Just a heads up). MonoBehaviour instances can be attached to GameObjects in code by calling the AddComponent method, which takes a type parameter or type argument, and returns the new instance of the attached MonoBehaviour that it creates.

This API usage means that:

  • We cannot attach existing instances of a MonoBehaviour to a GameObject
  • Unity3D takes care of instantiating MonoBehaviours for us (thanks Unity!)
  • … We can’t pass parameters into the constructor of a MonoBehaviour because Unity3D only handles parameterless constructors (boo Unity!)

So what’s the problem with that? It kind of goes against some design patterns I’m a big fan of, where you pass your object’s dependencies in via the constructor. You can read my little primer about constructor parameter passing, dependency injection, and Autofac to learn more.

The challenge I’m trying to address is that my non-MonoBehaviour classes are all going to be setup to use constructor parameter passing as much as possible but the MonoBehaviour classes cannot. So I’d like to reduce the amount of disjoint coding styles as much as I can and make the MonoBehaviour classes feel like the rest of my stuff!

What Is “Stitching”?

Here’s where this little pattern I created called “Stitching” comes into play. Stitching involves using a class referred to as a Stitcher that’s single purpose is to take parameters in via a constructor, and wire them up to either public properties or public fields (but I REALLY suggest using properties) on the MonoBehaviour that we instantiate through the GameObject.AddComponent() API.

The code ends up looking something like this:

public sealed class MyComponentStitcher
{
  private readonly IDependency _dependency;

  public MyComponentStitcher(IDependency dependency)
  {
    // take in our dependencies and save them as fields
    _dependency = dependency;
  }

  public MyComponent Stitch(GameObject gameObject)
  {
    // create the MonoBehaviour instance using the Unity3D API
    var componentInstance = gameObject.AddComponent<MyComponent>();

    // wire up our dependencies (assign our field to a property on the component)
    componentInstance.Dependency = _dependency;

    return componentInstance;
  }
}

Where you can see that:

  • We inject dependencies into the Stitcher’s constructor
  • We call AddComponent() with the component type we want on the object we want to “stitch” to
  • We mutate the component
  • We return the newly made component

How Do We Use Stitching In Practice?

Now that we see the pattern for a how a Stitcher works, how do we actually use Stitching in practice? Let’s start by using another example:

public sealed class SomeClass
{
  private readonly IMyComponentStitcher _stitcher;

  public SomeClass(IMyComponentStitcher stitcher)
  {
    _stitcher = stitcher;
  }

  public void MyMethod()
  {
    // create a new Unity3D game object
    var gameObject = new GameObject("My Game Object");

    // "stitch" our 
    var myComponent = _stitcher.Stitch(gameObject);

    // we can use some information that would have been injected into the constructor
    // this should print the injected value
    Debug.Log(myComponent.InjectedInfo);
  }
}

From this, you can see that:

  • We have a class called MyClass following our constructor parameter passing paradigm
  • The method MyMethod()
    • Creates a new game object
    • Adds a MyComponent instance to our game object by calling the Stitch() method
    • Using our imagination and the example above, pretend our Stitcher implementation takes a parameter in its constructor to assign to the InjectedInfo property of of MonoBehaviour
  • Logs out the value of the InjectedInfo property found on our newly created instance

So What Makes Stitching Better?

You might feel like this is extra code right now, but this is where the power of Autofac comes into play. You can read my article about using Autofac with Unity3D for more information.

By creating a Stitcher, we can register it to our Autofac container. The Autofac container will then resolve any dependencies that our Stitcher requires for us. The net effect of this is that when we Stitch MonoBehaviours to GameObjects, we get what feels like Autofac resolving dependencies for our MonoBeaviours. We don’t need to mutate MonoBehaviour fields/properties all over our code to assign the dependencies the script needs to use. Instead, we treat the Stitcher class like a factory for our MonoBehaviour.

So in summary:

  • Stitching allows us to leverage Autofac for instantiating MonoBehaviours
  • Stitcher classes essentially become a factory class for our MonoBehaviours (with the side effect that they *must* mutate the GameObject that we need to attach the MonoBehaviour to)
  • Allows assignment of MonoBehaviour fields/properties for initialization to exist in one spot so we can put the bad object mutating code in one spot that feels hidden

Using Autofac With Unity3D

Autofac With Unity

Why Consider Using Autofac With Unity3D?

I think using a dependency injection framework is really valuable when you’re building a complex application, and in my opinion, a game built in Unity is a great example of this. Using Autofac with Unity3D doesn’t need to be a special case. I wrote a primer for using Autofac, and in it I discuss reasons why it’s valuable and some of the reasons you’d consider switching to using a dependency container framework. Now it doesn’t need to be Autofac, but I love the API and the usability, so that’s my weapon of choice.

Building a game can result in many complex systems working together. Not only that, if you intend to build many games it’s a great opportunity to refactor code into different libraries for re-usability. If we’re practicing writing good code using constructor dependency passing with interfaces, then things really start to line up in favour of using a dependency injection framework.

Getting Set Up

At the end of my autofac primer article, I provided a link to the Nuget package for Autofac. You’ll notice that there’s a version dependency for .NET 4.5, so if you’re not sure how to get Unity3D working with .NET 4.5, you’ll want to check this other article of mine. It’s very simple, so don’t worry!

Unity3D, at the time of writing this and using version 2018.1.1f1, there’s no native Nuget package support. I haven’t spent too much time investigating alternatives, but not to worry. I’ll explain a quick work around. The TL;DR is that we need the binaries from the Nuget package to be loaded up by Unity3D and we’ll miss out on the Nuget-y-ness for now. Not a huge deal since we’ll still have Autofac support!

  • Start a new Visual Studio C# project
    • Ensure that the .NET framework is at least 4.5 and more specifically, the version of .NET that you’d like to use in your Unity3D project
  • Open up the Nuget package manager in Visual Studio
  • Search for Autofac online in the package manager (it should be the same one I referred to above!)
  • Add this package to your visual studio project
  • Compile this visual studio project
  • Assuming you built in debug, go to the output folder (which is in bindebug if you didn’t change anything from default)
  • In the output folder, you’ll find “Autofac.dll”
  • You’ll want to add this into your Unity3D project’s “Assets” folder
    • I like nice folder hierarchies, so I’d suggest making a subfolder inside of “Assets” called “Third Party” or “Dependencies”… Something that’s obvious for what it means
    • Drop in the Autofac.dll file into there
  • Unity3D will add a corresponding *.meta file to go along with this

Great! We’re almost there. If you want to test it out, open up a script from Unity3D. This will launch a new Visual Studio instance if you haven’t opened up one for your Unity project yet. At the very top of your file you should be able to type:

using Autofac;

And the namespace should resolve! If not, sometimes this takes Unity3D a refresh operation to regenerate the project file on disc, so if you switch to Unity3D again and it starts doing some processing, switching back to Visual Studio might resolve this.

Using Autofac With Unity3D

Up until this point, we’ve proven we can reference Autofac. I’m not going to explain all the ins and outs for how you’ll want to organize your Autofac initialization in this post, but we can walk through a quick example!

  • Pick a game object on your scene
  • Add a new C# script to it
    • Call it whatever you’d like, but make sure you know how to open it
  • … now go open it in Visual Studio 🙂
  • We should have a method in there called Start()
    • If not, feel free to add it:
    • private void Start()
      {
        // TODO: we'll add stuff here
      }
  • Let’s use this code to make a new class that you can put inside the same script file for now:
    • public sealed class MyAutofacObject
      {
      
        public MyAutofacObject()
        {
          Debug.Log("Constructor for our object!");
        }
      
        public void DoThing()
        {
          Debug.Log("Test!");
        }
      }
  • Inside this start method, let’s try doing something VERY simple to prove Autofac works!
    • var containerBuilder = new Autofac.ContainerBuilder();
      containerBuilder.RegisterType<MyAutofacObject>().SingleInstance();
      
      var container = containerBuilder.Build()
      var instance = container.Resolve<MyAutofacObject>();
      
      instance.DoThing();

Now if we run our game, here’s what should happen:

  • The script attached to the game object should run
  • The Start() method on the script should be the first thing that goes
  • The code we added should:
    • Make a new ContainerBuilder
    • Register our MyAutofacObject type as a single instance
    • Build the container
    • Resolve an instance of our type
    • Log out a message saying it’s in the constructor
    • Log out a message that says Test!

And voila! It’s simple, but it should demonstrate that Autofac is working!

Next Steps

This is a very contrived example of using Autofac with Unity3D. It proves that the code can be run, but it doesn’t do too much that’s useful. There are going to be many considerations you’ll need to make for how you want to organize your dependencies, register your classes/interfaces, and so on.

I’ll continue to add into this Unity3D series of posts, but let me know what else you’d like to know about using Autofac with Unity3D! I’d be happy to try and answer, or even create an article to help explain.

Thanks!


Dependency Injection with Autofac – A Primer

Autofac Logo

Before Autofac…

I’ve written before about IoC and dependency injection, but these are older posts and my perspective and experience with these topics has fortunately been growing. I think they’re incredibly important when you’re building complex systems, but the concepts can offer some benefits in all of your programming! When you get in the habit of practicing this kind of thing, you can get some pretty flexible code… for free.

So a quick recap on what I mean by dependency injection here… I’m mostly focused on passing interfaces into constructors (and yes, I’m going to be using C# terminology as I do in most of my programming examples, but these concepts are generally the same in other languages). The benefits here:

  • You can write implementations that don’t depend on other implementations… Just an API.
  • Not depending on an interface means you can write mockable code for your unit tests. (I’ll follow up with a post on this to help provide examples)
  • You can swap out functionality by providing a different implementation of an interface and NOT re-writing core code
    • This can be a very powerful refactoring tool
    • This can allow creation of new functionality in a system simply by adding one small class instead of re-writing code

So that’s all good and well… So what do we use Autofac for?

When you might want to take the leap to Autofac

So you’ve been writing code now using interfaces in your constructor parameters. You’ve got nice modular code using composition. You have unit tests. Things are great.

There comes a point where you decide you need to break open a class in the depths of your system and provide it a new interface as part of the constructor. This is in line with the constructor parameter passing paradigm (nice alliteration, woo!) you’ve been using, so it feels good. You modify your constructor to take the new interface parameter. You change up your method to call this new interface’s API. You update your tests. It works!

Now you need to make the rest of your application work though, and it turns out because this class is created so deep down in your system, you need to find a way to pass this new interface implementation allllllllll the way down. And suddenly, you find you need to break open 10 other classes to pass this interface into the constructor. It’s a simple change in that it’s the same change in 10 spots… But it’s 10 spots. And it’s tedious. And you got lucky because you own this code and you don’t need to worry about breaking the constructor API for other people.

But it might be time to look into something like Autofac at this point because it can make this problem disappear for you.

Enter Autofac!

Autofac is awesome. The end.

But seriously, Autofac is one example of a dependency container framework. The idea with a framework like this is that programmers can register things to the container and then at a later point these things can be resolved. So you could:

  • Decide to take a particular implementation and register it so that it can be resolved by its interface
  • Decide if you want a registration to act like a singleton (and remember, a singleton does NOT have to have global access… it just means literally a single instance)
  • Run callbacks when an instance is created
  • … and so much more

In my opinion, the two major benefits of Autofac as they relate to this example are:

  • You can better organize the top level of your application to wire up specific implementations to use in your code
  • … Autofac can magically resolve the dependencies for you so it solves that nasty problem of passing down dependencies via constructors to deep areas of your code

You’ll need to be careful that you don’t abuse the container though! It’s considered an anti-pattern to use the container to manually resolve dependencies across various areas of your application (generally this is referred to as the Service Locator (anti)Pattern, but people go back and forth on why it’s good or bad). The “proper” use case is to resolve your single entry point class in one spot, call the methods you need on your entry point class, and let Autofac do its magic to resolve all of your registered dependencies.

Where Can I Get Autofac?

This is the easy part! You can use your Nuget package manager in Visual Studio to find the right package for your .NET framework dependency. Check it out at the Nuget Gallery!

What’s Next?

I have some examples I’d like to write about next for using Autofac including:

  • Using Modules for Organizing Code Dependencies
  • Patterns for Dynamically Resolving Modules Across Assemblies
  • How to use Autofac with Unity3D

But I’d love to hear what you want to know more about! Comment and let me know, and I’ll see what I can do.


Unity3D and .NET 4.x Framework

Unity

Unity3D Default .NET Framework

I recently wrote that I wanted to start writing more Unity3D articles because I’m starting to pick up more Unity3D hobby work. It felt like a good opportunity to share some of my learnings so that anyone searching across the web might stumble upon this and get answers to the same problems I had.

Unity3D as of 2018.1.1f1 (which is the version I’m currently using), still defaults to using .NET 3.5 as the framework version. Nothing wrong with that either. I’m sure there are reasons that they have for staying at that version, probably because of Mono and cross platform reasons if I were to guess, so I’m not complaining. For reference, this setting in Unity3D is referred to as “Scripting Runtime Version”. So if you’re googling more about this later, that’s what Unity calls it. For the libraries I was building to use as a game framework, I was using .NET 4.6 and discovered I was going to have a challenge getting them working in Unity3D.

If you want to see what your setting is currently set at, you need to check out the “Player” settings. This was kind of buried in the UI for me so I didn’t know it was a thing that could be adjusted. In Unity3D 2018.1.1f1, click Edit->Project Settings->Player. Here’s what it looks like:

Unity3D - Player Settings

In Unity, click Edit->Project Settings->Player

From there, you’re going to get “PlayerSettings” in your Inspector tab. You’ll need to expand the “Other Settings” to see your scripting runtime version:

Unity3D - Other Settings

“Other Settings” accordion control in PlayerSettings Inspector tab

Once you expand that, here’s the setting you’re interested in:

Unity3D - Scripting Runtime Version

Scripting Runtime Version – The selected .NET version Unity will use

Switching Unity3D to .NET 4.x

Now that you know where the setting is… it’s pretty easy 🙂

Unity3D - Scripting Runtime Version

Use the dropdown to pick which .NET framework version you’d like to use.

You can read more about this setting over at the official Unity3D documentation pages:

https://docs.unity3d.com/Manual/ScriptingRuntimeUpgrade.html

This outlines what things are affected in different platforms and scenarios so YOU SHOULD READ IT to understand what will change.

Hope that makes things a bit easier for you to get up and running with .NET 4.x assemblies in Unity3D!


Experimenting with Paid for Ads for Web Traffic

Experimenting with Paid for Ads for Web Traffic

Why Did I Consider Paid for Ads?

I wrote a post about focusing on some of my strengths in order to minimize risk in new areas, and part of that meant focusing on increasing brand awareness for DevLeader as a proving ground. The idea of driving more web traffic to my blog via ads came up because I was interested in experimenting with Instagram ads for my show car branding, but not knowing anything about paid for ads made taking that first step feel pretty risky.

What should I expect for paying for ads? What will $1 get me? What will $10 get me? I have no idea where to start with this kind of thing, so I felt it was important to use my more solid brand, DevLeader, as the basis for this experiment. If I can watch what happens with traffic to this blog by playing with ads, then I can apply that learning to my vehicle brand.

Free Credit For Ads!

One thing that I found when playing with some of my SEO tools is that many paid-for ad services will actually give you a coupon or some sort of matching credit for using their ad service. What does that mean? Well, like almost everything in life… if it sounds too good to be true, it probably is. The coupons or credits don’t mean that you get to pay nothing for your ads, but it’s still a cool opportunity. Generally, these services will say “If you spend X dollars with our ad service, we’ll give you a credit to worth Y dollars that you can use for your NEXT set of ads”.

Make sense? They want to cover your NEXT purchase you make with them to get you on board with them. So it’s not a free experiment to try this out, but it means that if you’re going to drop $100 into it, that $100 might technically stretch out to be valued at $200 if you were to get a $100 coupon from one of these services.

Just something to think about! If you’re serious about looking into advertising and you’re willing to make the initial investment, it seems like a great opportunity.

Google AdWords

The obvious choice for me to start with was Google AdWords because all of my accounts are linked up in someway through Google at various points, and I use a lot of their tooling. The setup was very simple, but you’ll need to remember to have your credit card on hand. Like I said, nothing is free. You can stop your ads at any time though, so you don’t need to be paranoid about accidentally spending $500 on an ad. I mean, I think it would be difficult to have that happen and I’m a total newbie.

Google AdWords guides you through setting up your first ads pretty well, especially for someone that’s never done this before. When it comes time to pick keywords and bidding strategies… I sort of just guessed. It’s an experiment, right? They offer tools to measure your metrics, so you can try changing keywords to see how the effectiveness changes. I started by creating a search campaign that would maximize clicks. I set my spending limit to $3/day. Picked some popular keywords for my blog, like programming, C#, and Unity. And… now I wait to see what happens! I hope to follow up on all of this experimentation to share my learnings in this area so that anyone else on the fence can learn from my experiences.

For free credits, Google AdWords claims to match up to $150 of your first months spending, so I think I’m going to try shooting for that. I’ll start off at spending $3/day and see if I can experiment with a few different options for ads. By the end of the first month, I hope to use all $150 of my initial investment so that I’ll have $150 from Google to play with in the upcoming months!

Bing Ads

Bing Ads was a cool option to explore after setting up Google AdWords, so I suggest if you’re going to try both of these that you do Google AdWords first. Once I created my account for Bing, I was actually able to import my Google AdWords campaign I created extremely easily. I didn’t even have to think about it. I plan to measure the return on investment of both of these with the same campaign setup to see which one is more effective.

The great thing about Bing Ads? Once you spend $25 (USD), they’ll give you $100 (USD) for your next purchases. Just a $25 experiment that if it works well, I can get 3x the investment back to play with! Very cool!


Resolutions: Why Have Them and How to be Successful

Resolutions

What’s Up With Resolutions?

It’s that time of year! You know, where everyone is thinking back on all of the things they wish they had actually accomplished this year and they’re convincing themselves they’ll get it done next year. It’s time to set some New Year’s resolutions!

But what’s up with that? Why does it take people a whole year to reflect on what’s going right or wrong in their life and try to change their direction? Why does it take you a year to realize your diet and exercise regime is something you couldn’t stick to and you’re no better off than you were last year? Why were you still unmotivated in your career doing the same old thing? Why didn’t you get your head in the game for school? Why did you continue to pursue toxic relationships?

Continuous Improvement

Resolutions are all about trying to get better; we’re trying to continuously improve. Often when I talk to people about “agile” software development, all that I really try to drive at is that “continuous improvement”, in my own personal opinion, is really the important part.

So to continuously try to improve, you need to analyze what’s going well and what’s going not so well, set some goals, try things out, and re-evaluate. It’s a nice iterative cycle. It’s kind of like setting mini resolutions for yourself (or in the case of software development, maybe for your team or teams).

The big difference is the amount of time between measuring whether or not your change is having an effect! Waiting an entire year to try and measure your success would be absolute insanity in a fast moving software environment… why haven’t we gotten better at realizing this for our own personal continuous improvement?

Mark Manson

I’ve been reading a ton of Mark Manson material lately because of events going on in my life and the fact that the way he writes really aligns with how I often talk to my close friends. There’s analysis, there’s some humour, but it’s often a bit blunt and to the point. It’s actually a really nice change from many leadership, self help, or similar content where everything almost feels impossibly positive. This just feels like a real person talking to you.

Mark talks about setting goals in this blog post, and it got me motivated to reflect on my own goals and even write this post. In Mark’s post, he talks about our identities being built up by a bunch of habits, and goes on to state that some research shows that often habits only take about 30 days to form. In his opinion, using a whole year to set a goal of changing, adding, or dropping a habit just allows us to procrastinate for the entire year and then ultimately we fail.

His suggestion? Shorten the time frame.

If it takes on average 30 days to make a habit, why not have a “New Month’s Resolution”? Setting resolutions this way should then allow you to establish a new habit and then at the end of the month reflect on whether or not it worked well. You have less time to procrastinate. Your iteration is much shorter. Interesting.

My Own Goals

I figured I’d wrap this up by sharing some of my own goals publicly. I have a few things I’d like to work on coming up for the year, so I’ll outline them briefly:

  • Read more:
    • I’ve definitely dropped the ball on this one. I always had the excuse for myself that I don’t have time to do it. However, I found when I read the most consistently was when I found a decent book that I could read for a few minutes before I fell asleep every night. No pressure to get through it, but the books were there if I felt intrigued or needed to relax my brain a bit.
  • Try meditation:
    • I’ve always associated meditation with being spiritual or religious. Both of these things don’t really mesh well with me, personally. Mark Manson mentioned meditation in his post that I mentioned earlier, and it gave me a different perspective. I know I get stressed easily and I used to have pretty bad anxiety problems. Maybe this is something I could try out?
  • Write more:
    • I used to blog a lot. Between this blog, my fitness blog, and my car blog, I used to write content multiple times per week. It was always a bit of a social media experiment to get a better feel for how internet traffic works and where different types of content get the best visibility, but it also let me express myself. My content production has been almost nothing over the past year, and it’s something I’d like to look at more of.
  • Try public speaking:
    • This was something my HR Director had a chat with me about as a potentially cool opportunity. We were discussing getting more involved with the community and pushing boundaries, and she proposed speaking to students at local colleges or similar. I was turned off by it at first because I don’t like public speaking. But then the more I thought about it, I don’t know what public speaking is because I’ve never really done it. So why not try it?

But those aren’t my resolutions! Those are all just ideas for things I’m interested in improving. So taking some of Manson’s advice, I’m going to take ONE of those things and try to form a habit out of it for a month. Focusing on one thing at a time allows you to really give yourself an opportunity to establish the habit without worrying about too many other things, and ultimately setting yourself up for failure.

My first resolution is going to be to try out meditation. So for the first month, I’m going to try meditating four times per week for about 10 minutes at a time. I should be able to easily do this for two days on Saturday and Sunday where I don’t really have any external commitments, and then during the week I should be able to find at least two days before work where I can give this a shot.

Small steps, but small steps still take you forward.


How to Refocus: Getting Back in the Groove

How to Refocus: Getting Back in the Groove

Identifying when you need to refocus

It happens to everyone at some point to varying degrees, for various reasons, and at different times in our lives–but it’ll happen! You hit a period or a rut where you can’t keep your focus on continuing to be successful (and I’m over-generalizing that for a good reason).

Maybe this means you can’t focus at work to perform at an optimal level. Maybe you’re falling off the diet you’ve been working hard on. Maybe your training in the gym or for your sport is taking a hit because your head isn’t in the game. Maybe you find yourself unable to hit the books studying or completing your projects in school.

It can look different for everyone.

There are a bunch of different little warning signs that things aren’t quite on track and you need to refocus:

  • You’re losing interest in what you’re working on or have been working towards
  • You can’t seem to keep your mind on the goal(s) that you’ve set
  • You feel like you’re plateauing in your progress toward your goal(s)
  • You’re suddenly finding you’re not happy or not feeling fulfilled
  • You’re taking out stress on your co-workers, friends, or loved ones
  • You’re isolating yourself from friends and family
  • You find yourself overly concerned with things you can’t change (dwelling on the past or fearing a future event, like an exam)

But don’t freak out just yet… you need to see and acknowledge the signs before you can start to make any progress. Feeling pretty good about everything in your life? Then keep doin’ what you’re doin’! If any of those points seemed to resonate with you, then let’s continue on!

Don’t worry

If you’ve found that you’re in a bit of a rut, it’s important to not worry. You need to remind yourself that you were once on track and you’ll get back on track. You’ve already identified you need to refocus, so you have the power to get back on track.

Worrying about the fact you’ve identified you’re not in an ideal state of mind doesn’t help anything; in fact, it makes it worse.

“I can’t seem to find my focus at work… I’m going to be such a bad employee. I wonder if I can even get my work done now. My colleagues are going to notice… My manager will notice!”

“Training has really been kicking my butt… Why am I even doing this? I wonder if I should just give up. I haven’t seen any progress in my abilities in the past couple of weeks. I’m hopeless at this.”

“There’s a lot going on at school now and I can’t seem to keep up anymore. I’m going to fail this project that’s due next week because I can’t seem to get started on it. And my exams are coming up and I can’t seem to study. I’m going to fail this term.”

All of that kind of talk is negative and it’s not going to help you progress! So why are you continuing to focus on hampering your progress? Don’t do it. Instead, acknowledge you’re looking for a positive change, and then acknowledge that you’re in full control to start making that change.

And step one is to stop worrying and drop the negativity.

Analyze what’s getting you down

I get told that the engineer in me talks too much about analysis… but I think it’s a critical step! You need to understand the things that are getting you down. You’ve identified that you need to refocus because you’re not happy with your current behaviour or state of mind, but what are those things that are getting you down?

If you understand what’s getting you down you can start to take corrective actions. It’s got a (cue the fancy buzzword) synergistic effect with my previous point–Drop the negative thoughts and work on correcting them in parallel.

Let’s look at a couple of potential examples:

  • You’re unable to see any progress in your work, schooling, or training
    • How are you measuring progress right now?
      • Some things aren’t well suited for quantitative measurement
      • Try and identify a consistent mechanism for measuring progress
    • How often do you measure progress?
      • Some things don’t change very frequently so it’s hard to notice progress
      • Many things don’t progress in a totally linear fashion
    • Is it time to update your strategy for continuing success?
      • How long have you been doing the exact same thing expecting to get the same increase in results?
      • Have other environmental factors changed that suggest you should update what you’re doing?
    • Have you actually compared your current status to a previous point in time, or is it just how you feel?
      • Maybe it’s all in your head!
      • Try reflecting on where you were a month ago, 6 months ago, and a year ago.
  • You’re constantly comparing yourself to others
    • Do you actually know all the ins and outs of a person’s life?
      • Just because you observe certain things, it doesn’t mean they’re exactly as they seem
      • If you don’t have the full perspective and details on someone’s life, you’re guaranteed to be misunderstanding something
    • Can you change other people?
      • … Even if you could, you shouldn’t!
      • See the next major point 🙂
    • Are you comparing different subsets of your lives and expecting them to align a certain way?
      • Other people are not you and are living a different life
      • You can only truly compare yourself to your own self at various parts in your life
  • You’re dwelling on things you can’t change
    • Are you expecting to change something in the past that’s already happened?
      • Unless you have a time machine, you absolutely cannot change past events
      • Trying to understand past events can be helpful learning for the future
    • Are you dreading an event in the future that’s unavoidable?
      • If you can’t avoid it, then work at accepting it’s going to happen. (Things like exams or year-end reviews for work, for example)
      • Ask yourself why you’re dreading it. Try applying this example of analysis to THAT reason and dive deeper.
    • Are you focused on the thoughts and emotions of other people?
      • You can’t (and shouldn’t try to) control how other people think and feel
      • The best you can do is focus on yourself and live the values that you believe in
      • When it comes to thoughts and feelings, we all observe and interpret on our own
    • Have you considered whether this situation is temporary?
      • When you don’t know how long you’ll be out of control, it can make you feel helpless
      • Knowing there’s a point in time where there’s a change that can affect your situation can be a great help (i.e. money is tight for two weeks and you just need that next pay cheque to come through)

These are just a handful of examples, but hopefully you can see a pattern:

  1. Identify a particular thing that you know is getting you down.
  2. Ask yourself what effects it’s having and why you believe it’s having those effects on you.
  3. Dive deeper on each one of those by repeating these steps.

It’s nothing groundbreaking and I’m not claiming it will magically fix your problems… But analyzing things can lead to understanding, and understanding can lead to progress.

Remind yourself of your strengths

Everyone gets down on themselves at some point and this will cause you to lose focus on your goals. But I guarantee you if you stop and think about it, there’s a lot of great things that you got going on!

Don’t believe me? I challenge you to take a pen and something you can write on.

  • Write three things you’re proud of or that you’ve accomplished
  • Write three things about why your best friends like you
  • Write down the thing you love doing most or loved doing most before this point in time
  • Write down the thing you think you’re best at

Now step back for a second and think about the things you wrote.

  • It’s very likely the accomplishments you made or things you’re proud of required you to overcome something. Unless you got lucky or had some magic, odds are you used your strengths to achieve these things.
  • Your friends stay by your side because they admire you. They admire the qualities you have and see strength in you. You might not realize these strengths, but your friends perceive these about you.
  • If you love doing something, you’re probably pretty good at it, and if you’re not, odds are you’ll get good at it because you love to do it! Acknowledge and understand what you’re passionate about because it will tell you about your strengths.
  • Sometimes you’re good at things that you’re not totally passionate about. That’s cool too! What makes you good at this thing? Can you apply this to other areas in your life?

Set some goals

At this point you’ve:

  • Identified that you’re not content with your current state
  • Reminded yourself that you can make a change
  • Analyzed what’s getting you down so that you have a better understanding of some direction to take
  • Reflected on your own personal strengths

And now… It’s time to set some goals!

Goals you set should ideally align with SMART goals. Do yourself a favour and check that page out for a little bit more information so you can set yourself up for success. You want to make sure you’ve agreed your goal is achievable within a certain period of time and that you can measure progress in some way as you go. This is critical for a few reasons:

  • No time box? How will you know if you’re on track?
  • No way to measure? … Same problem!
  • Not realistic or achievable? You’re setting yourself up for failure.

It seems obvious when it’s laid out like that, but this will keep you from setting goals like “I’m going to do better at work”, “I’ll kick my training up a notch”, or “I’ll worry less about what’s going on in other peoples’ lives”. None of those goal statements indicate when you’ll be done by or how you’re going to measure progress.

Here’s a simple example:

In the next month, instead of missing on average three practices per week, I’ll reduce this to one. I’ll make sure that I have things put into my agenda ahead of time so I won’t schedule things over practice sessions, and if something critical comes up last minute, I can use the following week to compensate for it.

  • Specifically about not missing practices
  • Measured weekly by an average of missed practices
  • Achievable because it’s an improvement and not an expectation of perfection
  • Realistic and with the reward of getting to more practices
  • Time boxed to one month.

Start slow and set one or two SMART goals. As you build confidence that you’re progressing in your goals, try adding in another. You don’t want to overwhelm yourself!

Be brave enough to ask for help

If you’re reading this and you’re considering making changes then you’re already starting your path to progress. That’s AWESOME and you’re a strong person for being able to get started.

Sometimes things can get tough though. You might feel you’ve made progress over a few weeks or months and seemingly fall back to square one. You might feel like you’ve set SMART goals but you’re having trouble even getting started. Maybe you read this and still don’t even know how to get started.

There are a million reasons why getting started or continuing can be hard. Be brave though. Ask for help. I can guarantee you have some amazing friends and family that love you that want to see you be successful. There’s nothing to be ashamed of when asking for help! It’s a courageous thing to admit that you’d like assistance on your path for doing better, and people see that. You might feel embarrassed or ashamed, but other people see a brave person trying to move forward.

Summary

It’s a common thing for people to fall into a figurative rut in life. It happens to everyone at some point and it’s nothing to get down on yourself about. You’re not a bad human being if it happens to you, so don’t sweat it.

Analyzing your current situation and why you feel certain ways can help you gain an understanding of what’s going on. Focus on driving out the negativity and create actions to try making progress by leveraging your strengths.

In the end, remember that you control your life and you can make all the positive changes to it that you want to see. It takes time and hard work, but if you put in the effort, you’ll always get to where you want to be.

Now get out there and go kick some ass.


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
            .GetElementsByTagName(name)
            .Cast<XmlElement>()
            .First()
            .Value;
    }
}

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

private static int Main(string[] args)
{
    var obj = CreateObj();
    var stringLookup = CreateStringLookup();
    
    obj.DoStuff(stringLookup);
 
    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)
            {
                continue;
            }
 
            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


  • Subscribe to Blog via Email

    Enter your email address to subscribe to this blog and receive notifications of new posts by email.

  • Nick Cosentino

    Nick Cosentino

    I work as a team lead of software engineering at Magnet Forensics (http://www.magnetforensics.com). I'm into powerlifting, bodybuilding, and blogging about leadership/development topics over at http://www.devleader.ca.

    Verified Services

    View Full Profile →

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