• Skip to main content

Ethereal Bits

Tyson Trautmann's musings on software, continuous delivery, management, & life.

  • Archive
  • About
  • Subscribe
  • LinkedIn
  • Twitter
  • Search

Software

Dependency Injection (& Small Furry Animals)

March 16, 2012 by Tyson Trautmann Leave a Comment

Dependency Injection (DI) is a game changing design pattern that most programmers should have in their toolbox. DI was initially known as Inversion of Control (IoC), but because frameworks inherently invert some sort of control Martin Fowler proposed the naming switch to DI in his canonical post on the subject to better describe which aspect of control is being inverted. There are plenty of tutorials on DI that are extremely helpful when ramping up on the topic, although some of them are either tightly coupled to a particular language or framework while others can be a bit lengthy. For that reason I thought I would take the time to write a quick post that explains the concept of DI at a high level, in a (somewhat) concise fashion. I’ll try to explain things in a way that is language agnostic, but I will use Java for my initial example. After that I’ll touch on ways to use DI in a few common languages, and then I’ll close by listing a few reasons why DI is cool.

To illustrate what DI is all about, let’s suppose that I’m writing a Java application that makes small furry animals sing and dance on the screen (because everyone loves a minstrel marmot). I begin by creating a SmallFurryAnimal Interface like so:

Interface SmallFurryAnimal {
  void Sing();
  void Dance();
}

I then create a couple of animal Classes called Marmot and Squirrel that implement SmallFurryAnimal with their own animal specific implementation of Sing and Dance. I tie everything together in a main method that looks like this:

Class Application {
  public static void main(String [ ] args) {
    while (true) {
      Marmot.Sing();
      Marmot.Dance();
      Squirrel.Sing();
      Squirrel.Dance();
    }
  }
}

When I run javac to compile my application to bytecode I need to be sure to pass the source files for Marmot and Squirrel to compile Application because they are hardcoded compile time dependencies. When I run the application using java I also need to be sure that the ClassLoader is able to load Squirrel and Marmot. This is all fine and dandy until I realize that I want to give people who use my application the ability to design, implement, and plugin their own arbitrary small furry animals without having to worry about recompiling or even knowing about the rest of my application. Essentially I want to do the following:

Class Application {
  public static void main(String [ ] args) {
    while (true) {
      for (all the aniamls that I inject at runtime) {
        SmallFurryAnimal.Sing();
        SmallFurryAnimal.Dance();
      }
    }
  }
}

With these changes I’m only bound to the interface for SmallFurryAnimal, not any particular implementation. I’m free to code up animals to my heart’s content, and I can use DI to inject them into my application at runtime.

It turns out that this kind of ability to inject dependencies into an application at runtime is very common for all sorts of applications. One very common example is applications that run workflows and allow users to inject custom workflow tasks. Another similar example is a state machine application that allows users to inject custom states behaviors that relate to states. In fact almost any time you implement an interface or derive from a base class may be a candidate for injecting the dependency on the implementation at runtime unless the number of possible or necessary implementations is of a relatively small fixed size that isn’t likely to change.

It’s possible to use DI in Java without taking advantage of any additional frameworks by using Reflection to crack open Class Files and look for Classes that implement a specific interface. The most common way to use DI in Java is Spring, a popular Java Framework targeted at a wide array of Java deployment use cases. One of the things that Spring provides is an IoC container which provides the ability to load Java objects using Reflection (typically by specifying which objects to load in configuration) and handles managing the lifecycle of those objects.

C# is obviously very similar to Java, and it allows you to implement DI using Reflection. .NET has also introduced the Managed Extensibility Framework which allows usage of the DI pattern without configuration by using class attributes to tell the Composition Container what to load at runtime.

If you’re using dynamic programming languages like Perl or Ruby then DI is essentially baked in, you’re probably already using it whether or not you realize it.

There are a bunch of reasons why DI is super important, and why many programmers who first stumble on the pattern feel like it’s a game changer. It improves testability by providing the ability to inject mock objects during test execution. It improves reusability of code by allowing developers to build components once and dynamically injected them into multiple applications, and by allowing application consumers to inject objects that are specific to their requirements. It makes code more readable by making dependencies explicit in configuration or metadata. It makes applications easier to deploy or upgrade by guaranteeing loose coupling with dependencies so that either the application or any injected object can be deployed in isolation.

It’s not the only way to accomplish these objectives, but it’s certainly a great way to do so. Hopefully this quick overview has served to help introduce you to the DI pattern, and provided some useful links in case you want to dig deeper.

The "Base" Suffix

December 15, 2011 by Tyson Trautmann Leave a Comment

Came across some code today that seemed a bit backwards (and made me chuckle), it was effectively the following:

public class FooBase extends Foo { }

Bass ackward nomenclature aside, the code brings a separate point to mind on use of the Base suffix. Krzysztof Cwalina aptly points out that the Base type can lead to some ugly code in common cases where you want to return the base type. This also implicitly suggests that it shouldn’t be used in public facing interfaces. I would add the fact that words with the Base suffix aren’t usually descriptive of real objects (Dog extends Mammal extends… MammalBase?) and for that reason I often see examples where code in classes suffixed with the word Base would be a more natural fit either in the child class itself, in a separate utility class, or in a better thought out base class that represents a real object.

The Religion of Coding Style

August 10, 2011 by Tyson Trautmann Leave a Comment

I’ve been doing some investigation of different “Coding Style Enforcement” tools (primarily for C# code) recently on behalf of a Bing v-team on coding conventions and I’ve learned a few things:

1. ReSharper kicks ass.

2. Developers are willing to shed blood over coding style preferences.

3. ReSharper really kicks ass.

First a quick introduction on a few tools in the space:

ReSharper (or R#) is a Visual Studio add-on that does on the fly code analysis, and is also great for refactoring code. It gives you nice little squiggly lines that represent errors, warnings, suggestions, or hints for your code as you type. The thing that makes R# ‘leet is that it can also often fix issues for you.

StyleCop is a tool that was developed by Microsoft and is available under the MPL. It has a good stock set of rules that many Microsoft teams tend to follow (for the most part). Current versions now ship with a ReSharper add-on that really rocks, because R# can now automatically fix a lot of StyleCop issues and give R# style real time warnings as you type. The only downside is that as of right now StyleCop 4.6 hasn’t yet released (should come very soon), so there is no intergration with R# 6.0.

FxCop is a different breed of tool so I won’t go into great detail, but people often wonder what the difference is so I’ll touch on it briefly. FxCop analyzes built assemblies (not code) for design, localization, performance, or security issues. VS has built in FxCop integration that’s controllable via the Code Analysis tab at the project level.

CodeRush is a competitor to R#. Agent Smith is a competitor to StyleCop, only from what I can tell it is only available as a R# plugin. I don’t know much about either except that I’ve met people who use and think they’re cool.

That’s certainly not any kind of exhaustive list, but those are a few technologies that I’ve either played with or seen mentioned in the managed code style enforcement space. Some props go out to Scott Marlowe, I found his blog post to be a pretty good starting point for investigation.

Tools aside, the question that I hear posed on a fairly regular basis is “How much does adherence to coding conventions really matter?” My answer to this question has changed a bit throughout my development career. For the last few years I haven’t been huge on conventions, I’ve generally encouraged developers who work for me that the guiding principle should be to match the style of the project that you’re working in. I still believe this is probably the most important idea when contributing to a project, but I also find myself more compelled to accept coding standards for projects where more than a few developers are partying. There’s something beautiful about looking at code and not being able to tell who wrote it because the style is consistent across the board. It makes it easy to jump in on new projects because they’re always readable to me, not just the dude who wrote the code. It also avoids the kind of “should I use var or not” battles that tend to become religious crusades and can actually even fracture a team in extreme cases.

Speaking of var, I’ve become a huge believer lately in part because I started using QuickGraph which can result in some crazy nested generic types, but also because the default R# rules encourage it. I actually find myself agreeing with Michael Brennan’s arguments in favor of always using var. But then again, I’m not quite ready to shed anyone’s blood over it.

Calling into a Platform Specific COM Assembly from a Platform Independent .NET Application (for fun or profit)

June 22, 2011 by Tyson Trautmann Leave a Comment

When you’re working on a .NET application and you need to call into a platform specific COM Assembly there are a few issues in play that can be a bit confusing. In my own exploration I found a lot of different articles that were helpful/interesting to varying degrees (if a bit incomplete WRT my scenario and conflicting in a few cases), so I figured I would post my own notes.

The important thing to remember is that native code is always specific to a given platform, while managed code can either be specific to a platform or it can be set to ILONLY which allows JIT to compile to either architecture. If you want your app to be platform independent and you have both 32 and 64 bit flavors of the native COM Assembly you can register both versions and create a COM Interop assembly that isn’t platform specific and the Interop assembly will pick the correct COM object.

The following steps illustrate how to create a runtime callable wrapper for a COM assembly and reference it from your project (or you can just reference the COM assembly directly in Visual Studio and it will do essentially the same thing under the hood):

1. Use tlbimp.exe to create a RCW:

tlbim.exe foo.dll /out:Interop.Foo.dll

2. Register the COM assembly (not the RCW) if you haven’t already:

regsvr32.exe foo.dll

3. Reference the RCW (eg. Interop.Foo.dll) from your application.

GhostDoc & Comments

June 17, 2011 by Tyson Trautmann Leave a Comment

If you’re using Visual Studio, writing XML comments, and aren’t using GhostDoc then you’re wasting time. It’s one of the handful of tools that I install alongside VS first thing on any clean install. Just wrote a new method to solve world hunger? Ctrl + Shift + C and GhostDoc will take a stab at filling in the comments for you. The hit ratio isn’t perfect, but it’s always faster to tweak the results and fill in blanks than starting from scratch in my experience and another side effect is that it encourages you to give a bit more thought/consistency to method/variable names.

Strongly Naming a Third Party Assembly

May 13, 2010 by Tyson Trautmann Leave a Comment

At some point in your development career you’ve likely run into some kind of problem caused by working with strong named assemblies (typically by design). Today I was trying to compile my own strong named assembly, but my code was referencing an assembly that wasn’t strongly named. I didn’t have access to the third party assembly code, so recompiling it wasn’t an option. After searching around for a while I found this neat little trick to disassemble and reassemble a dll.

First, use “sn.exe -k myTest.snk” to generate a key for your assembly. Next, use “ildasm myTest.dll /out:myTest.il” to disassemble your dll into IL. Finally, use “ilasm myTest.il /res:myTest.res /dll /key:myTest.snk /out:myTestSN.dll” to reassemble the dll with a strong name. Not necessarily the prettiest solution, but it gets the job done!

  • « Go to Previous Page
  • Go to page 1
  • Go to page 2
  • Go to page 3
  • Go to Next Page »

Copyright © 2021 · Atmosphere Pro on Genesis Framework · WordPress · Log in