Avoiding Dependency Injection’s Constructor Injection Hell by Using the Custom or Default Pattern

Dependency Injection makes the claim that a concrete implementation of an interface is going to change. The problem is that theory rarely meets reality. In reality, there usually exists one single concrete implementation of most interfaces. Usually there exists one Test implementation. Other than those two concrete interfaces, a second production implementation of an interface almost never exists. When there are multiple concrete implementations of an interface, it is usually in a plugin situation and is handled differently, using plugin loading technology. So we can exclude plugin scenarios, whether UI or other, and focus on day-to-day dependency injection.

In some projects, 100% of the objects have a single production implementation and a single test implementation. Other projects, you may see 90%/10%, but again, rarely are their multiple.

In other projects, you will find a second production concrete implementation, but it is replaces the previous implementation, not running alongside it.

So why are we not coding to the common case?

Construction Injection

Constructor Injection assumes a few things:

  1. Your class should not even instantiate without something injected into the constructor.
  2. Your class should not work without something injected in.
  3. Your class should have zero dependencies, except of standard types and simple POCO model classes.

It sounds great in theory, but in practice, it usually leads to constructor injection hell. If you are wondering what Constructor Injection hell is, have a look at this previous post: Constructor Injection Hell.

Property Injection Issues

Property Injection or Method injection are also assuming a few statements are true.

  1. Your class can be instantiated without something injected into the constructor.
  2. Your methods should throw exceptions if a required property has not yet been injected.
  3. Your class should have zero dependencies, except of standard types and simple POCO model classes.

Method Injection Issues

Method Injection or Method injection are also assuming a few statements are true.

  1. Your class can be instantiated without something injected into the constructor.
  2. Your methods should throw exceptions if a required property is not injected when the method is called.
  3. Your class should have zero dependencies, except of standard types and simple POCO model classes.

Dependency Injection Problems

There are problems caused with Dependency Injection.

  1. Dependency Injection Hell
  2. Your code doesn’t work without an injected dependency
  3. You cannot test your code without an injected dependency.

Should You Stop Using Dependency Injection

So now that you’ve been educated on the truth that theory and reality never mix, and most of Dependency Injection is a waste of time, let me tell you: Keep doing it because you still will benefit from Dependency Injection.

Don’t stop doing it, but instead add to it a simple pattern. The Custom or Default pattern.

Custom or Default Pattern

This pattern is so simple that I cannot even find it mentioned in any list of software development patterns. It is so simple and obvious, that nobody talks about it. But let’s talk about it anyway.

Make everything have a default value/implementation. If a custom implementation is supplied use it, otherwise use the default.

It is a simple pattern where all the Dependency Injection rules are simplified into two:

  1. Your class should instantiate without something injected into the constructor.
  2. Your class and method should work without something injected in.
  3. Your class should have zero dependencies, except of standard types and simple POCO model classes or default implementations.

Notice the rules change. And these changes make your life so much easier.

What adding this pattern says is that it is OK to depend on a default implementation. Yes, please, support Dependency Injection, but don’t forget to provide a default implementation.

Constructor Injection with the Custom or Default Pattern

This pattern could be implemented with Constructor Injection.

public class SomeObjectWithDependencies
{
    internal IDoSomething _Doer;
    public SomeObjectWithDependencies(IDoSomething doer)
    {
        _Doer = doer ?? new DefaultDoer();
    }

    public void DoSomething()
    {
        _Doer.DoSomething();
    }
}

However, you didn’t solve Constructor Injection hell. You could solve that with a Service Locator. Here is the same pattern with a Service Locator. I’ll only do one Service Locator example, though it could be done a few ways.

public class SomeObjectWithDependencies
{
    internal IDoSomething _Doer;
    public SomeObjectWithDependencies(IDoSomething <span class="hiddenGrammarError" pre="">doer)
    {
        doer</span> = doer ?? ServiceLocator.Instance.DefaultDoer;
    }

    public void DoSomething()
    {
        _Doer.DoSomething();
    }
}

Many developers will immediately react and say that both example result in coupled code. SomeObjectWithDependencies becomes coupled to DefaultDoer or ServiceLocator.

Well, in theory, this is coupling. Your code will never compile, the earth will stop moving, you will rue the day you made this coupling, and your children will be cursed for generations, blah, blah, blah. Again, theory and reality aren’t friends. The code always compiles. The coupling is very light. Remember, it is only coupled to a default. You have now implemented the Custom or Default pattern. With one line of code, you solved a serious problem: With regular Dependency Injection, your code doesn’t work without an injected dependency.

Guess what, you had coupling anyway. Usually you had to spin up some third library, a controller or starter of some sort, that hosted your dependency injection container, and then you had to couple the two objects of code together and now you have an entire third library just to keep two classes from being friends.

The above is still very loose coupling. It is only coupling a default. It still allows for a non-default concrete implementation to be injected.

Property Injection with the Custom or Default Pattern (Preferred)

This pattern could be implemented with Property Injection. However, this pattern suddenly becomes extremely awesome. It is no longer just a standard property. It becomes a Lazy Injectable Property.

A Lazy Injectable Property becomes key to solving most of your Constructor Injection hell.
Since it is very rare that a implementation other than the default is ever used, it is extremely rare that a Dependency Injection container is ever really needed to inject a dependency. You will find yourself doing Dependency Injection with a container.

This item

public class SomeObjectWithDependencies
{
    public IDoSomething Doer
    {
        get { return _Doer ?? (_Doer = new IDoSomething()); }
        set { _Doer = value; }
    } private IDoSomething _Doer;

    public void DoSomething()
    {
        _Doer.DoSomething();
    }
}

Or if you have a lot of such dependencies, you can move them into a DefaultServiceLocator .

public class DefaultServiceLocator() : 
{
        public IDoSomething Doer
        {
            get { return _Doer ?? (_Doer = new ConcreteDoSomething()); }
            set { _Doer = value; }
        } private IDoSomething _Doer;

        // more lazy injectable properties here
}

public class SomeObjectWithDependencies(IDoSomething doer)
{
    public IDefaultServiceLocator ServiceLocator
    {
        get { return _ServiceLocator ?? (_ServiceLocator = new DefaultServiceLocator()); }
        set { _ServiceLocator = value; }
    } private IDoSomething _ServiceLocator;

    public void DoSomething()
    {
        ServiceLocator.DefaultDoer.DoSomething();
    }
}

Using slideToggle with Knockout’s MVVM

I recommend you use the third option: Option 3 – Boolean binding using a custom binding handler called slideToggle

See it live here: http://plnkr.co/edit/1YGchAyjkNSjYzmXFfK2

<!-- Step 1a - Create the HTML File or the View -->
<!DOCTYPE html>
<html>
<head>
    <!-- Step 2 - Include jquery and knockout -->
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
    <script type="text/javascript" src="http://knockoutjs.com/downloads/knockout-3.0.0.js"></script>
     
    <!-- Step 3 - Add script to run when page loads -->
    <script type="text/javascript">
        $(document).ready(function(){
         
            <!-- Step 4 - Create a ViewModel -->           
            function viewModel() {
                _self = this;
                _self.showHideChild = function(viewModel, event) {
                    $(event.currentTarget).children('div').slideToggle()
                };
                _self.showHideNextSibling = function(viewModel, event) {
                    var siblings = $(event.currentTarget).siblings('div');
                    for (var i=0;i<siblings.length;i++) {
                        if (siblings[i].previousElementSibling == event.currentTarget ) {
                            $(siblings[i]).slideToggle();
                        }
                    }                 
                };
                _self.isVisible = ko.observable(false);
                _self.showHide = function() {
                    _self.isVisible(!_self.isVisible());
                }
            };
           
            ko.bindingHandlers.slideToggle = {
                init: function (element, valueAccessor) {
                    var value = valueAccessor();
                    $(element).toggle(ko.utils.unwrapObservable(value));
                },
                update: function (element, valueAccessor) {
                    var value = valueAccessor();
                    var isVisible = element.offsetWidth > 0 && element.offsetHeight > 0;
                    if (ko.utils.unwrapObservable(value) != isVisible) {
                        $(element).slideToggle();
                    }
                }
            };
           
            <!-- Step 5 -  Activates knockout.js bindings -->
          ko.applyBindings(new viewModel());
        });
    </script>
</head>
<!-- Step 4 - Create a HTML Elements with bindings -->
<body style="">
    <div>
        Option 1 - Child div
        <div id="child1" data-bind="click: showHideChild" style="border:2px solid;">
        Click me
            <div id="child2" style="display: none;">
              Now you see me!
            </div>
        </div>
        
        Option 2 - Siblings div
        <div id="sib1" style="border:2px solid;">
            <div id="sib2" data-bind="click: showHideNextSibling" >
            Click me
            </div>
            <div id="sib3" style="display: none;">
            Now you see me!
            </div>
            <div id="sib4">
            You should always see me.
            </div>
        </div>
        Option 3 - Boolean binding using a custom binding handler called slideToggle 
        <div id="bool1" style="border:2px solid;">
            <div id="bool2" data-bind="click: showHide" >
            Click me
            </div>
            <div id="bool3" data-bind="slideToggle: isVisible">
            Now you see me!
            </div>
        </div>
    </div>
</body>
</html>

The 10/100 Rule – Following this one development rule will improve your code

There is a simple guideline that every developer can follow that will make their code easier to manage and easier to test.

The 10/100 rule

Question: What is the 10/100 rule?

Answer: It is a simple rule that developers should follow to keep their code concise and clean. It involves keeping in mind two warning signs for bad code.

  • Warning #1 – If a method reaches 10 lines, you need to stop and consider refactoring the method.
  • Warning #2 – If a class reaches 100 lines (comments and brackets included) you should stop and consider refactoring.

Like me, you have probably heard both rules before. I see the rule to keep methods short written over and over again in other blogs and other software engineer’s guidelines. But I rarely see this touted as the #1 most important rule that all developers should learn first.

Why should developers learn the 100/10 rule first?

Because it is the single most effective rule to improve code that any developer can learn in less than a minute. No other rule can be learned in other a minute and improve a developers code as much.

I gave this rule to a first year developer (not college educated) and after following this rule, he wrote “proof of concept” code. As many more experienced engineers know, proof of concept code sometimes becomes release code. It is usually a horrible tragedy when this happens. The code is usually rough and untestable and filled with scripting or linear processing. However, in this case, that issue didn’t occur. All the classes were under 100 lines (most considerably under 100 lines). All the method were easily testable and under 10 lines. Sure there were a few that needed to be broken up. The code wasn’t perfect. But the most important and amazing thing about his code were the design patterns he used without even knowing them. He used the proxy and bridge patterns. He used the builder pattern. He used a rudimentary version of the Factory Pattern. He had small and easily manageable singletons. I even found the chain of responsiblity pattern in his code. He also had a number of “Extension methods” since he was using C# which further increased the easy of testing and the readability of his code.

When a developer asks me if they should study design guidelines and learn the many design patterns common to the industry I say, “Yes, of course study them.” However, if a developer follows the rules above, they will naturally find themselves using many of these patterns without even knowing them. It is the perfect rule to keep your code inline until you are an expert.

Why does the 100/10 rule work?

Look at the first year developer’s experience. His code wasn’t perfect, but just the effort he took to keep the classes under 100 lines the methods under 10 lines forced him to create other objects that made more sense for the task at hand. These other objects naturally fell into the realm of well-known design patterns. It works because all the classes are kept small.

The 100/10 rules helps with the Keep it simple stupid (KISS) rule.

The 100/10 rule helps with the Single Responsibility Principle (SRP),  though it doesn’t guarantee the SRP, it helps users naturally stay close to that rule. Sure they may have C# class do two things instead of one because two things fit in the 100 lines allowed for a class. However, how many times have you touched someone else’s code and found a class doing a dozen things in a class that is more than 500 or 1000 lines. To fix this code you have to redesign and break this class into a dozen or more other objects. I think you would be more than happy to only have a class doing two things. Sure you need to break it still, but you only need to break it in half, which is much easier.

It is a guideline that can be broken

The 100/10 rule is a guideline. When a class reaches 100 lines you stop and think. When a method reaches 10 lines, you stop and think. However, thinking is the most important part. Should this method take 10 lines? Maybe it should. Should this class be longer than 100 lines? Maybe it should.

You may have to implement an interface (such as IList) and when you are done, your class is already over 100 lines and you haven’t even added any methods other than the interface’s methods. Well, some might argue that the developers of your interface could have used a smaller interface but there is usually nothing you can do about that. This class isn’t going to be able to follow that 100/10 rule. That is OK.

Keep studying

Remember the 100/10 rule takes less than one minute to learn. It is the single most effective rule a developer can learn in 1 minute to improve their code. It is not the end.

Sure, this rule is always good to follow, even for senior developers, however, this rule doesn’t solve everything. It doesn’t teach interface-based design and good decoupling. It doesn’t make developers follow the open/closed principle or the substitution principle. However, it usually prevents code from becoming spaghetti code. The 100/10 rule keeps the blocks small and easily to work with and easy to fix. So when you see the code and you have to revamp it to include dependency injection and decouple it, you will have a much easier time.

Senior Developers Benefit too

New developers aren’t going to have any idea what cross-cutting concerns are. They will accept that some instance where the 100/10 rule is broken that maybe a senior developer shouldn’t accept. Senior developers should have heard of cross-cutting concerns and should have at least heard of Aspect Oriented Programming (AOP). Often when a method is probably kept in scope, but still reaches over 10 lines, it may be using a try/catch block.

Check out this code found in a single method. The stub code alone is 35 lines. With the missing log, the method was over 50 lines. Is this acceptable just because it is doing a try/catch block?

public StreamReader TryReadFile(string path)
{
    try
    {
        return File.OpenText(path);
    }
    catch (UnauthorizedAccessException ane)
    {
        // handle exception
    }
    catch (ArgumentNullException ane)
    {
        // handle exception
    }
    catch (ArgumentException ane)
    {
        // handle exception
    }
    catch (PathTooLongException ane)
    {
        // handle exception
    }
    catch (DirectoryNotFoundException ane)
    {
        // handle exception
    }
    catch (FileNotFoundException ane)
    {
        // handle exception
    }
    catch (NotSupportedException ane)
    {
        // handle exception
    }
}

Well, if you don’t accept this as OK, (well, the cyclomatic complexity is high why would you accept this as OK?) and you seek out how to resolve this, you are going to run across AOP solutions. With AOP, this method could look like this:

[HandeFileReadExceptionsAspect]
public void TryReadFile(string path)
{
    File.OpenText(path);
}

The HandeFileReadExceptionsAspect is now a separate class that is reusable for every instance where you read a file. You now have common code handling the File.Read exceptions and your method that was 50 lines is now 5 lines. Your HandeFileReadExceptionsAspect class will most likely be under 100 lines. So your codes is now cleaner, more decoupled, easier to read, easier to use, and follows the 100/10 rule.

Conclusion

I preach the 100/10 rule to all developers, new and old. I am not sure that anyone else calls it the 100/10 rule. If you call it something else, let me know.

HTML Search using MVVM with knockout.js

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
    <script type="text/javascript" src="http://knockoutjs.com/downloads/knockout-3.0.0.js"></script>
     
    <script type="text/javascript" >
        $(function(){
         
            // custom binding handler so pressing enter in a textbox is the same
            // as clicking the button.
            ko.bindingHandlers.enterKey = {
                init: function(element, valueAccessor, allBindings, vm) {
                    ko.utils.registerEventHandler(element, "keyup", function(event) {
                        if (event.keyCode === 13) {
                            ko.utils.triggerEvent(element, "change");
                            valueAccessor().call(vm, vm);
                        }                        
                        return true;
                    });
                }         
            };
         
            var fakeSearch = function(args, callback) {
                var data = args;
                callback(data);
                return args;
            };

            var ButtonViewModel = function(text, searchMethod, canSearchMethod) {
                var _self = this;
                _self._canSearchMethod = canSearchMethod;
                _self.text = ko.observable(text);
                _self.onClick = searchMethod;
                _self.canClick = ko.computed(_self._canSearchMethod);                
            };

            var SearchParametersViewModel = {
                'SearchTerm': ko.observable(''),
                'SearchOption': ko.observable(''), // Not used in example
                'StartDate': ko.observable(''),    // Not used in example
                'EndDate': ko.observable('')       // Not used in example
            };

            var SearchViewModel = function(searchMethod, searchArgs) {
                // private properties
                var _self = this;
                _self._searchMethod = searchMethod;
                _self._searchArgs = searchArgs;
                _self._canSearch = function() {
                    return _self.searchParameters.SearchTerm() != null && _self.searchParameters.SearchTerm() != '';
                };

                // public properties
                _self.searchParameters = SearchParametersViewModel;

                _self.results = ko.observable('');
                
                _self.searchCallBack = function (data) {
                    _self.results(JSON.stringify(data));
                };

                _self.searchButton = new ButtonViewModel("Search", 
                function () {
                    _self._searchMethod(_self._searchArgs, _self.searchCallBack);
                }, _self._canSearch);
                
            };
           
          ko.applyBindings(new SearchViewModel(fakeSearch, {a: "1", b: "2"}));
        });
    </script>
</head>
<body>
    <input data-bind="value: searchParameters.SearchTerm, valueUpdate: 'afterkeydown', enterKey: searchButton.onClick" />
    <button type="button" id="btnSearch" data-bind="text: searchButton.text, enable: searchButton.canClick, click: searchButton.onClick"></button>
    <p data-bind="text: results"></p>
</body>
</html>

WPF MVVM Tutorial

Hey all, here is my WPF MVVM knowledge. You should read these articles, whether mine or sites I link to.

However, you may want to skip my stuff and go straight to this nice little training by Karl Shifflett.
In the Box – MVVM Training

  1. A quick overview of MVVM
  2. Binding Visibility to a bool value in WPF
  3. A Hello World template of a WPF application using MVVM
  4. How Do I: Build Data-driven WPF Application using the MVVM pattern
  5. Binding to methods encapsulated in an ICommand
  6. Simplifying the WPF TreeView by Using the ViewModel Pattern
  7. A Progress Bar using WPF’s Progress Bar Control, BackgroundWorker, and MVVM

Visual Studio Helps

  1. A Hello World template of a WPF application using MVVM
  2. A snippet for Properties in a ViewModel

WPF and MVVM Problems

  1. WPF NavigationService blanks PasswordBox.Password, which breaks the MVVM PasswordHelper