Archive for the ‘Architecture’ Category.

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 doer)
    {
        doer = 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 IDoSomething()); }
            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

Decoupling in all 7 areas of development

There are 7 main development areas and decoupling, especially decoupling using interface-based design, will be most successful when it occurs in all possible areas.

  1. Code – writing code, sharing code, linking to libraries
  2. Test Code – Unit Tests, Mocked tests, coded functional tests
  3. User Experience – UI design.  The UI should be decoupled from code.
  4. Source Control – Code repositories, branching
  5. Build – compiling, versioning, signing, publishing
  6. Install – Any install method such as MSI, EXE, RPM. Any updates or patches.
  7. Localization – Make this independent of build/compiling

If you decouple everywhere, it is easy to remain decoupled. This leads to good architecture – the overall design of your software.

Code

Code should be easy to write and maintain always.

Let’s face it. Coupled code is often the easiest to start with. However, while it is easy to start out using coupled code, it becomes very difficult to use coupled code as a project grows.

Interface-based design is one method of decoupling code. You are still coupled, just instead of coupled to code, you are coupled to an interface that rarely changes and the code that implements that interface is free to be refactored as long as the tests against the interface pass.

If your code is decoupled, you are free to write your code as you will.

Test Code

I often hear someone say they don’t need to use interface-based design because their code is never going to be an API.  This is not true. If you are Unit Testing properly, your code is always going to be an API even if only your Unit Tests and Functional Tests interface with your code/API.

In decoupled code using interface-based design, your interfaces should have 400% coverage.

100% for each of the following:

  • Expected values
  • Null values
  • Empty values
  • Exception causing values

Write Unit Tests that are exhaustive for your interfaces.  The object that implements the interface will be easier to refactor this way because the new refactoring can implement the interface either directly or through an adapter and you will know nothing can be broken in your refactored code because all the tests pass.

All code that touches the system or requires resources not on a clean build system should be mockable. If you use interface-based design your are mockable by default. For your development language, do a search for mocking libraries such as RhinoMocks for C#.  Also, be aware of how to use an adapter or wrapper to allow for mocking, such as SystemWrapper for C#.

User Experience

User Interfaces (UIs) should be developed independent of the back-end code. They should be developed first or at least simultaneously to the back-end code.  This allows for user experience tests to occur early in the process and changes based on the feedback to be easy and quick. Tools to design UIs that allow for customer feedback already exist, such as SketchFlow for rich Windows WPF UIs.

The UI should be decoupled from the code. You should probably have two separate UIs just so you can switch between them to show how the UI is not coupled to the code and can be switched at any time.

Source Control

Decouple your source control. I don’t mean that one team uses Subversion, another GIT, and another TFS. I mean that your project is in its own repository, and has few as possible prerequisites projects as possible. This is made possible by interface-based design. If you have a 10 features, all on top of core functionality, you should have one core functionality repository and 10 feature repositories.

Also, if you source is not decoupled you are tempted to couple your code with other code.  This lead us to build.

Build

Build does not just mean on a build system. Lets start with the developer building on their local machine. A developer should be able to check out a project and build it without any effort beyond the checkout.  Ok, maybe if you are C# developer you need to at least install Visual Studio. But then you should be able to check out a solution, open it, and press F5 to build it and the build should work. If not, your process is broken and developers’ time is wasted.

Now to the build system or CI builds.

Coupled code is hard to build. Dependency loops can occur. Builds have to occur in specific order, and this takes longer.

With interface-based design, you build your interface libraries first and they build almost instantly as they have no real code. Then you simultaneously build everything else.  Your build is extremely fast because you can build everything with different threads simultaneously (or even on different build machines), even for extremely large applications because they only link to the interfaces.

Different parts of your project can and should have different versions. Just because you release YourProduct 3.0 doesn’t mean that the a library hasn’t already matured beyond to 5.1.  And because of your decoupled interface-based design, you can upgrade YourProduct 3.0 to use version 5.2 of the library and it won’t know the difference. This leads right into install.

Install

Installing should be decoupled. If your project is big enough, it is ok to have 100 different installs. Sure, for Windows don’t show 100 items in Add / Remove Programs, just one or a few.  But that doesn’t mean that you don’t have each piece of your product separately installable, patchable, and upgradeable.

Think of a product with four different parts. You should be able to install, upgrade, and patch each of the four parts separately.  The product as a whole can be version 3.0 but different parts can be different versions. You may have a piece that is very mature, at version 5.1 and a piece that was just refactored for your 3.0 release and it is version 1.0.  Your four products could be: 3.0, 5.1, 1.0, 3.0.

If you are properly decoupled and using interface-based design, you can upgrade any of the four parts to a new version without the other three parts having any adverse affects at all.

Localization

It is frustrating to have to wait for a build to see and test your localization.  Sure some people only have to wait for the first build and then can generate their satellite assemblies from there. However, I disagree with any localization strategy that involves build. I cringe when I hear “localization lock down” because the release is soon.  Really? Does it have to be this way?

How can you do this? Decouple text from the software.

Text should stay where text belongs, in text files. Whether it be a property-value-list or an XML, localization should be dynamic. Let the software pull in text dynamically from a text file. Then switching language in a UI is just a matter of changing from one text file set to another (probably as simple as changing a two, three, or five-letter path).

And the text is patchable without build risk.  If you are 1 day from shipping and you realize you have a completely erroneous string, you can edit a text file to fix it without little to no risk.

Edit the text file(s) without a build and run time just picks up the corrected text.

Since the UI was done before or simultaneous to the back-end code, the localization will be done early and changing may be made often.

Conclusion

Decoupling is a massive undertaking and doesn’t just mean to decouple code. Decoupling is methodology that should be used everywhere in all aspects of the software development life cycle.

Feature branching fits the Kanban model – Branching by MMF

I have to say I am a fan of branching for feature or for team.  I think branching for feature, or branching for a Minimal Marketable Feature (MMF), really fits into the Kanban model.

However, decouple first. This article was really good about talking about a decoupling branching strategy.

http://continuousdelivery.com/2011/05/make-large-scale-changes-incrementally-with-branch-by-abstraction/

Once decouple, branch by feature or in the Kanban world, Branch by MMF.

Here are the positive and negatives.

Branch by feature or team (team and feature are similar)

Positive

Indifferent

Negative

Having read all of these. The negatives are important to read.

It seems that a lot of the negatives are eliminated by the following.

  1. Decoupled code
  2. Using Interface-based design (which is a method for decoupling code)
  3. Keeping MMFs as small as possible (which they should be anyway: “Minimal” marketable feature
  4. Merging main to the feature branch daily/weekly
  5. Running tests on CI on feature branches as well as on main
  6. Checkin’s are gated so a failed build/test prevents check in.

Also read the comments as there are real experiences shared there (assuming the author of the comments are sincere).

A successful branch by MMF strategy can be done with any source control tool.

Side Note 1:

I’ve been using GIT lately for a project in my Masters of Computer Science’s Security course. I finally understand why GIT has become the de facto source control for Open Source, because branching on your local machine can be helpful and efficient. The local check out on your dev box IS A BRANCH and can be branched and you can branch by feature or by task locally.

I recently wrote something I couldn’t check in and couldn’t branch it locally with our source control, but I could have with GIT.

Side Note 2:

Another side note: TortoiseGit and TortoiseSVN are both on my dev box now and explorer.exe is constantly at 45% CPU slowing my system.

Architecting a large application with interface-based architecture

Design and architect and write your software solution so that its different pieces can be independent in the following ways:

  1. Develop Independently
  2. Build Independently
  3. Install Independently
  4. Test Independently
  5. Refactor/Replaced Independently

Don’t just separate the concerns in one way and call it good. Separate your concerns all the ways listed above.

What will this do for your project?

  • It will make it so it can be easily unit tested.
  • It will make it so it can be easily built.
  • It will make it so it can be easily installed.
  • It will make it so it can be easily changed: Patched, Refactored, or Replaced.

Wow, all that sounds great, why doesn’t everyone do this?

Because the one area that is harder is the initial development. You have to design a lot more. You have to code different. It can be hard.

However, it is the easiest way overall, just not the easiest way at the start developing.

How do I separate my code into pieces?

There is a though among many that a software tool should do one thing only, but it should do it really well. When you think of your entire project, that should be kept in mind.

The smallest item in a project is the likely the “object”.

The term object is very abstract. It is like the work “thing” in that it can be anything.

So look at it from a high level view. Imagine your software has four pieces.

Decoupled Architecture

Ok, how do these pieces interact? Can you build each piece without having to link to another piece? You should be able to do this.

However, you have to link to something in someway in order to use its code so what do you link to?

Interfaces.

Ok, so you double the size of your pieces by having a piece and an interface for it. These could be eight separate dlls.

If Piece1 needs Peice2, it should link to IPiece2 and not to Piece2. This allows for Piece2 to be:

  1. Any version of Piece2 that implements the interface.
  2. Refactored without breaking the Piece1 build.
  3. Replaced by a completely different implementation
  4. Mocked for testing (really the same as three but used for Unit tests)

Real life example

In real life, applications are database driven. So what if your Piece2 is a database tool and Peice1, Piece3, and Piece4 all need to access the database using Piece2.

If you link directly to Piece2, you have a problem where you must have a real database in order to test your code in Piece1, Piece3, and Piece4.

This is a huge testing burden. This prevents your tests from running as Unit Tests and instead they must be run as Functional Tests.

However, by designing properly using interfaces, you can get back to Unit Tests for Piece1, Piece3, and Piece4 by mocking Piece2.

You use IPiece2 to create a new block called Mock2, which is just a Mock of Piece2, which can be run during a Unit Test. Now all the other blocks are testable.

Lets look at our Independent Architecture rules and see if this design works.

  • Yes – It will make it so it can be easily unit tested.
  • Yes – It will make it so it can be easily built.
  • Yes – It will make it so it can be easily installed.
  • Yes – It will make it so it can be easily changed: Patched, Refactored, or Replaced.

If you have a large application, this is one design pattern you should look at.

Other Resources

A snippet for Properties in a ViewModel

If you are using MVVM you probably should create a snippet very similar to the following to save time.

C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC#\Snippets\1033\Visual C#\propvm.snippet

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
	<CodeSnippet Format="1.0.0">
		<Header>
			<Title>propvm</Title>
			<Shortcut>propvm</Shortcut>
			<Description>Code snippet for property and backing field for a ViewModel that calls NotifyPropertyChanged.</Description>
			<Author>Jared Barneck</Author>
			<SnippetTypes>
				<SnippetType>Expansion</SnippetType>
			</SnippetTypes>
		</Header>
		<Snippet>
			<Declarations>
				<Literal>
					<ID>type</ID>
					<ToolTip>Property type</ToolTip>
					<Default>int</Default>
				</Literal>
				<Literal>
					<ID>property</ID>
					<ToolTip>Property name</ToolTip>
					<Default>MyProperty</Default>
				</Literal>
			</Declarations>
			<Code Language="csharp"><![CDATA[public $type$ $property$
	{
		get { return _$property$;}
		set 
		{ 
			_$property$ = value;
			NotifyPropertyChanged("$property$");
		}
	} private $type$ _$property$;
	$end$]]>
			</Code>
		</Snippet>
	</CodeSnippet>
</CodeSnippets>

A quick overview of MVVM

Model View ViewModel (MVVM) is a design pattern based on Model View Controller (MVC) but specifically tailored to Windows Presentation Foundation (WPF).

MVVM is not a framework per se but many frameworks have been created. Here is a list of MVVM Frameworks from Wikipedia.

See the Wikipedia site here: Open Source MVVM Frameworks.

Another blog, has some basic information on many of these here: A quick tour of existing MVVM frameworks

A framework is actually not necessary to implement MVVM and you should seriously consider whether using one is right for your WPF application or not. Many applications do not need much of the features the frameworks provide. However, there are two common classes that all MVVM frameworks contain. These are ViewModelBase and RelayCommand. Though some frameworks may give them different names or implement them slightly differently, they all have these classes. For example, MVVM Foundation names the ViewModelBase differently. It is called ObservableObject, which is more appropriate because it is incorrect to assume that all objects that implement INotifyPropertyChanged are going to be ViewModel objects.

Instead of installing and using an MVVM framework, you could simply include these classes in your application, as these are all you need to implement MVVM.

  • ObservableObject
  • RelayCommand

While these two classes are enough, you may want to investigate how different MVVM Frameworks implement and what else they implement and why. You may find that another feature implemented is exactly what you need in your application and knowing about it could save you time.

A WPF front-end for LDPing

I wrote a front-end to LDPing last week-end. You can check it out here:

LDPing

So I was writing a WPF front-end for LDPing, which is a method of querying a LANDesk Agent for its computer name and Inventory Id. There is a button that you click to launch the ping and I couldn’t get the thing to enable…Anyway, I figured it out and posted the resolution here:

Refreshing a button enabled/disabled by RelayCommand.CanExecute()

So here is a screen shot of LDPing.

10 Step process for developing a new WPF application the right way using C#

It makes a difference if you do something the right way from the beginning.  Everything seems to work out so much better and takes less time over all.

Here are some basic steps that I have learned will help you do it right the first time. These steps are from my experience, mostly because I did it wrong the first few times.  These are not exact steps. They are subject to change and improve.  In fact, you might have improvements to suggest immediately when you read this. But if you are new to WPF, then reading these steps before you start and following them, will have you closer it doing it the right way the first time.  It is much more pleasant to tweak a pretty good process than it is to go in with no idea for a process and do it wrong.

Step 1 – Prepare the idea

  1. Some one has an idea
  2. Determine the minimal features for release 1.
  3. Determine the minimal features for release 2.
    1. Alter minimal features for release 1 if it makes sense to do so.
  4. Determine the minimal features for release 3.
    1. Alter minimal features for release 1 and 2 if it makes sense to do so.

Step 2 – Design the Application’s back end business logic (simultaneous to Step 3)

  1. Design the backend
  2. Apply the “Keep it simple” idea to the business logic and makes changes as necessary.
  3. Apply the “Keep it secure” idea to the business logic and makes changes as necessary.
  4. Repeats steps 2 and 3 if necessary.
  5. Backend development can start now as the UI and the back end should not need to know about each other, though this coding is listed as the Step 5 item.

Step 3 – Design the UI using WPF (simultaneous to Step 2)

  1. Determine what development model should be used to separate the UI from the business logic.
    1. Model-View-ViewModel (MVVM) is the model I recommend for WPF.
    2. Gather libraries used for the model (such as common MVVM libraries that include the common ViewModelBase and RelayCommand objects)
  2. Consider using a 3rd party WPF control set will be used.  Many 3rd party companies provide WPF controls that are better and easier to use than those included by default.
    1. If you decided to use 3rd party controls, purchase or otherwise obtain the libraries for these 3rd party controls.
  3. Consider designing two WPF interfaces or skins (I will call these Views from here on out) for each screen. This will help drive the separation of the back end code from the WPF code. Also if developing two Views is not simple, it indicates a poor design.
  4. Design the interface(s) (you may be doing two Views) using SketchFlow (take time to include the libraries for the 3rd party WPF Controls in your SketchFlow project and design with them)
    1. SketchFlow allows you to design the UI, which is commonly done in paint, but instead does this in XAML, and is actually the WPF code your application will use.
  5. SketchFlow allows you to deliver the design (or both Views if you did two) as a package to the customer.
    1. Deliver it immediately and get feedback.
    2. Make changes suggested by the customer if in scope.
  6. Take time to make the XAML in SketchFlow production ready.
  7. Deliver the XAML to the customer again, to buy of that the design changes are proper.
    1. Make changes suggested by the customer if in scope.

Step 4 – Determine the delivery or install method

  1. Determine the delivery method.
  2. Determine when to develop the delivery method.
    1. The easier the application is, the longer you can wait to determine the installer or delivery method.
    2. The more complex the install or delivery method, the sooner this should be started.

Step 5 – Develop the business logic

  1. Develop the application designed in step 2.
  2. Get the application working without UI or silently. Note: Start the next step, Develop the UI, as soon as enough code is available here.

Step 6 – Add Bindings to the UI

  1. Start the UI project by copying the XAML from the SketchFlow document to your Visual Studio or Expression Blend project.
  2. Determine a method for setting the DataContext without linking the View to any ViewModel or Model dlls.
  3. Create a project for the ViewModel code and develop it to interact with the business logic using Binding.
  4. Remember to develop two Views for every UI screen as this will help, though not guarantee, that the the MVVM model was correctly used.

Step 7 – Develop the View Model

  1. You should now have a backend code and a View, and now you start creating the View Model.
  2. This should be in a separate dll than the View or ViewModel.
  3. The ViewModel should never link to the View but can link to Model and Business libraries, though you may consider interface-based design and only link to an interface library.
  4. Make sure to use the properties that the View is binding to.

Step 8 – Consider a other platforms

Macintosh

Macintosh owns a significant market share.  Determine if this application needs to run on Macintosh as well. Sure, since we are running C# your options are limited to either rewriting in objective C and Coca, or using Mono with a MonoMac UI.  I recommend the latter.

Note: It is critical that the UI and business logic are separated to really make this successful.

  1. Completely ignore the WPF design and have Macintosh users users assist the design team in designing the new UI.  Macintosh’s have a different feel, and trying to convert the same UI is a mistake.
  2. Create the MonoMac UI project.
  3. Create a project similar to the ViewModel project in Windows, to link the UI to the business logic.

BSD/Linux/Unix

BLU (BSD/Linux/Unix) doesn’t exactly own a significant market share. However, it is still important to determine if this application needs to run on on BLU as well. Sure, since we are running C# your options are limited to either rewriting in C++, or using Mono with a GTK# or Forms UI.

  1. Completely ignore the WPF and Macintosh designs and have Linux users assist the design team in designing the new UI. Linux have a different feel, and trying to convert the same UI is a mistake.
  2. Create the GTK# project.
  3. Create a project similar to the ViewModel project in Windows, to link the UI to the business logic.
  4. GTK# doesn’t support binding, but still keep the UI separate from the business logic as much as possible.
  5. Also, don’t develop for a single open source flavor, but use standard code that compiles and any BSD/Linux/Unix platform.

Mobile Platforms

  1. Do you need to have this app on IOS or Android or Windows Phone?
  2. Completely ignore the WPF and Macintosh and Linux designs and have Android or IOS users assist the design team in designing the new UI. Mobile platforms have a different feel, and trying to convert the same UI is impossible as the screens are much smaller.

Step 9 – Develop the delivery method

Again, you may need to do this way sooner if the application is complex.

  1. Develop the install or delivery method.
  2. If you decided to deploy to Macintosh or BLU you may have to develop separate install or delivery methods for those platforms as well.
  3. Remember to have a plan and a test for your first patch even if you have to mock a sample patch before you release.
  4. Remember to have a plan and a test for upgrading your application even if you have to mock a sample upgrade version before you release.

Step 10 – Deliver the finished Products

  1. Once finished, deliver this product.
  2. If you decided to create a Macintosh or BLU version, deliver them when ready as well.  It is OK and maybe preferred to deliver these at different times.

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

I am using three things that are just not friends:

  • Pages and NavigationService
  • Model-View-ViewModel design
  • The PasswordBox control

Problem 1 – PasswordBox.Password is not a DependencyProperty

First off, Model-View-ViewModel is design centered around data binding. But PasswordBox.Password is not a DependencyProperty and therefore does not support binding. That is ok, a PasswordBoxAssistant (alternately I have seen it named PasswordHelper or PasswordBoxHelper) as described originally here and also here fixes seems to fix this.

That is, it fixes it unless you are using the NavigationService.

Problem 2 – NavigationService blanks PasswordBox.Password

See when the NavigationService navigates to another page, it somehow know that the current page has a PasswordBox and if it finds a PasswordBox, it blanks the password out.  So since we are using PasswordBoxHelper to make MVVM and data binding work, the value is blanked in the ViewModel and Model as well.

For now, I happen to be using a custom button for navigation so I can simply do this in my ViewModel:

String tempPw = MyPassword;
NavigationService.Navigate(NewPage);
MyPassword = tempPw;

However, this is not the best solution. What if there were multiple links and different ways to navigate?

I think the best solution would be to figure out how to make PasswordBoxAssistant handle this. But I am not sure how or if there is anyway to tell that the password was blanked by the NavigationService and to ignore binding in this instance.

Resource:
http://social.msdn.microsoft.com/Forums/en/wpf/thread/d91aec90-1476-41c0-a925-7661745094c5

Navigation and Pages using Model-View-ViewModel (MVVM)

I am working on a project at work that is a navigation application.

I wanted to use MVVM. I also wanted to document for others how I designed this, as there wasn’t much online about using MVVM with Navigation and Pages.

Here is my project. I will post an explanation of this project as soon as I can get to it, so look for it.

Project Download – Small: Navigation-Pages-MVVM.zip

Project Download – More complete: Navigation-Pages-MVVM 2.0

Binding Visibility to a bool value in WPF

Please go here for updates to this post:

Binding Visibility to a bool value in WPF

I was putting code in my ViewModel that returns Visibility but I didn’t really like that very much. If the UI is created with something other than WPF, that is really not going to work. Since I intend to do cross compile my code in Mono, which doesn’t have WPF but uses either Forms or GTK#, I have already encountered this issue. What I really want to use is bool.

The solution is IValueConverter. If you just want the code and don’t want to read this post, just scroll to the bottom and grab the

IValueConverter is part of PresentationFramework (in PresentationFramework.dll) so it isn’t available in Mono, but that is OK because you don’t instantiate it in the ViewModel, you use it in the View so it will only be used when the GUI is part of WPF. So if you are separating your View into a separate DLL, this would be included in the View DLL, that way when you compile everything else, with say a different GUI that uses GTK#, you won’t get a compiler error because PresentationFramework doesn’t exist in Mono.

BooleanToVisibilityConverter

Well, there is an object already created for you called BooleanToVisibilityConverter, but it is limited. True is converted Visibility.Visible. False is converted to Visibility.Collapsed.

Here we see a problem. Visibility has three possible values but a Boolean only has two.

BooleanVisibility
TrueVisible
FalseCollapsed
Hidden

This will cover many of the scenarios, but not all.

Here is how it would be used.

For this example, I have this Person class.

    public class Person
    {
        public Person() { }
        public String FirstName { get; set; }
        public String LastName { get; set; }
        public String Age { get; set; }
    }

Here is a simple View for this object. It has a Grid that has a Label and TextBox for each property in the Person object. It also has a CheckBox. The CheckBox gives us a easy bool value, IsChecked. This works similar to a bool property in a ViewModel.

<Window x:Class="TestBooleanToVisibilityConverter.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:TestBooleanToVisibilityConverter"
        Title="MainWindow"
        SizeToContent="WidthAndHeight"
        >
    <Grid Margin="20">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid Name="PersonViewGrid">
            <Grid.Resources>
                <BooleanToVisibilityConverter x:Key="BoolToVisConverter"/>
            </Grid.Resources>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="Auto" />
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>
            <Label Content="First Name:" Grid.Column="0" Grid.Row="0" />
            <TextBox Grid.Column="1" Grid.Row="0" Name="firstNameTextBox"
                     Text="{Binding Path=FirstName, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" MinWidth="175" />
            <Label Content="Last Name:" Grid.Column="0" Grid.Row="1" />
            <TextBox Grid.Column="1" Grid.Row="1" Name="lastNameTextBox"
                     Text="{Binding Path=LastName, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" MinWidth="175" />
            <Label Content="Age:" Grid.Column="0" Grid.Row="2"
                   Visibility="{Binding IsChecked, ElementName=ShowAgeCheckBox, Converter={StaticResource BoolToVisConverter}}"/>
            <TextBox Grid.Column="1" Grid.Row="2" Name="ageTextBox"
                     Text="{Binding Path=Age, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" MinWidth="175"
                   Visibility="{Binding IsChecked, ElementName=ShowAgeCheckBox, Converter={StaticResource BoolToVisConverter}}"/>
        </Grid>
        <Grid Grid.Row="1">
            <CheckBox Name="ShowAgeCheckBox" Content="Show Age" />
        </Grid>
    </Grid>
</Window>

I am not using MVVM for this example, but instead there is a just a single object created in the code behind for demo purposes.

using System;
using System.Windows;

namespace TestBooleanToVisibilityConverter
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent(); Person p = new Person() { FirstName = "Michael", LastName = "Michaels", Age = "33" };
            PersonViewGrid.DataContext = p;
        }

    }
}

Ok, now build the project and you will see that the Label and TextBox for Age are hidden until you check the box.

Writing your own Bool to Visibility Converter

Sometimes you may need to write you own Converter.  For example, in the above project, it is annoying how the CheckBox moves up and down in position because Visibility.Collapsed is used instead of Visibility.Hidden.  You may want to use Visibility.Hidden instead.

You can write your own Converter that returns Visibility.Hidden instead of Visibility.Collapsed.

BooleanToVisibleOrHidden.cs

using System;
using System.Windows.Data;
using System.Windows;

namespace TestBooleanToVisibilityConverter
{
    class BoolToVisibleOrHidden : IValueConverter
    {
        #region Constructors
        /// <summary>
        /// The default constructor
        /// </summary>
        public BoolToVisibleOrHidden() { }
        #endregion

        #region IValueConverter Members
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            bool bValue = (bool)value;
            if (bValue)
                return Visibility.Visible;
            else
                return Visibility.Hidden;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Visibility visibility = (Visibility)value;

            if (visibility == Visibility.Visible)
                return true;
            else
                return false;
        }
        #endregion
    }
}

Here we do the conversion ourselves and now we have a different conversion table.

BooleanVisibility
TrueVisible
Collapsed
FalseHidden

Now replace the Converter object in your XAML.  We only change Line 15.

      <local:BoolToVisibleOrHidden x:Key="BoolToVisConverter"/>

This works, but it could be improved. This still leaves us having to choose between two objects.

Creating a Converter that supports a choice of Hidden or Collapsed.

Here we will provide a property that determines if we should collapse or not.

Add a property called Collapse and return the appropriate Visibility based on that property. Here is the new object. As you see, the code changes to add this feature is really just an empty bool property and an if statement that used the bool property.

using System;
using System.Windows.Data;
using System.Windows;

namespace TestBooleanToVisibilityConverter
{
    class BoolToVisibleOrHidden : IValueConverter
    {
        #region Constructors
        /// <summary>
        /// The default constructor
        /// </summary>
        public BoolToVisibleOrHidden() { }
        #endregion

        #region Properties
        public bool Collapse { get; set; }
        #endregion

        #region IValueConverter Members
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            bool bValue = (bool)value;
            if (bValue)
            {
                return Visibility.Visible;
            }
            else
            {
                if (Collapse)
                    return Visibility.Collapsed;
                else
                    return Visibility.Hidden;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Visibility visibility = (Visibility)value;

            if (visibility == Visibility.Visible)
                return true;
            else
                return false;
        }
        #endregion
    }
}

Now in your XAML you have the option to do nothing, which uses the bool default value false, or to set the Collapse property to true as shown below.

      <local:BoolToVisibleOrHidden x:Key="BoolToVisConverter" Collapse="True"/>

We now support either feature with the following table. We probably at this point would rename the object to BooleanToVisibilityConverter, but Microsoft already took that object name so I will leave it named as is.

BooleanVisibility
TrueVisible
False – Collapse=TrueCollapsed
False – Collapse=FalseHidden

We are starting to get a little more usability from one object.

Adding the Reverse feature so False is Visible and True is Collapsed or Hidden

Lets say we want to change the CheckBox so that instead of saying “Show Age” it says “Hide Age”.

            <CheckBox Name="ShowAgeCheckBox" Content="Hide Age" />

Now we have to reverse the mapping. If Reverse=”True” we want the mapping to be like this:

BooleanVisibility
FalseVisible
True – Collapse=TrueCollapsed
True – Collapse=FalseHidden

This is also quite simple. We add another bool property called Reverse. Then key of that in another if statement.

using System;
using System.Windows.Data;
using System.Windows;

namespace TestBooleanToVisibilityConverter
{
    class BoolToVisibleOrHidden : IValueConverter
    {
        #region Constructors
        /// <summary>
        /// The default constructor
        /// </summary>
        public BoolToVisibleOrHidden() { }
        #endregion

        #region Properties
        public bool Collapse { get; set; }
        public bool Reverse { get; set; }
        #endregion

        #region IValueConverter Members
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            bool bValue = (bool)value;

                if (bValue != Reverse)
                {
                    return Visibility.Visible;
                }
                else
                {
                    if (Collapse)
                        return Visibility.Collapsed;
                    else
                        return Visibility.Hidden;
                }
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Visibility visibility = (Visibility)value;

                if (visibility == Visibility.Visible)
                    return !Reverse;
                else
                    return Reverse;
        }
        #endregion
    }
}

Now you can reverse this very easily in the XAML.

      <local:BoolToVisibleOrHidden x:Key="BoolToVisConverter" Collapse="True" Reverse="True" />

And now you have a much more full featured converter.

Additional Thoughts

I have to wonder why the developers didn’t do this originally with the BooleanToVisibilityConverter object. It is so simple. This is a perfect example of where Microsoft would benefit from Open Sourcing some of their code. A dozen people would have contributed this change by now if they had and all Microsoft would have to do is look at the submitted code, approve, and check it in.