Brendan Enrick

Daily Software Development

String Formatting BoundFields in Silverlight

Hi my name is Brendan E. While working with a Bindable Silverlight control I ran into a little bit of trouble because I have a dependence commonly found among Visual Studio developers. I am addicted to intellisense. When a property isn’t in intellisense I make the failing assumption that it does not exist.

So even though I have posted specifically about how we developers should be smart enough to know that we can’t always trust intellisense, I still make the mistake of trusting it.

I am binding to a control and it slipped my mind to use the DataFormatString property, because it didn’t show up in intellisense for me. So of course I look around for what else I might use. I bing a few times about what I am trying to do. When I find the answer I feel like an idiot once again. This must be how all addicts feel. I just need my intellisense.

So I was trying to format my bound field as a percentage. To do that I just needed to add the following code.

DataFormatString="{}{0:P}" 

 

Hooray! I’ve got working code now. So I repeat again. Don’t trust intellisense. Just because it says it isn’t there doesn't mean it isn’t there.

Transactional Data Persistence with OpenAccess

OpenAccess is an Object Relational Mapper (ORM) from Telerik, and as you might have noticed from my earlier post about building an OpenAccess enabled project on a build server, I am currently working with OpenAccess on one of my projects. I figure that since I am using this Object Relational Mapper that I should post regularly about using it so that others starting to use OpenAccess have a shorter learning curve.

Making modifications to persisted data needs to be done transactionally so that any issues which arise during the persistence can be responded to and handled correctly. For example if you are going to be updating a customer and that customer’s address then you will want to make sure that the save is an all or nothing situation since it could be bad if the address was saved but not the customer. With a transaction you have the ability to rollback so that you can be at the initial state once again. By doing this we can then handle the error and not have the transaction halfway committed.

OpenAccess has support for transactions using its ObjectScope. To begin a transaction you simply need to access the Transaction peroperty of the IObjectScope and call its Begin method. To complete the transaction you call the Transaction’s Commit method.

using (IObjectScope objectScope = MyScopeProvider.GetNewObjectScope())
{
    objectScope.Transaction.Begin();
    // Perform the persistence logic here
    objectScope.Transaction.Commit();
}

So this is pretty easy, right? Well what about rolling back the transaction if we have a problem. So the simple thing to do is to wrap a try-catch block around the transaction. Then in the catch portion we will need to make sure that if the transaction is still active that we roll everything back to the previous state. (We also handle the exception, but that’s your job not mine.)

using (IObjectScope objectScope = MyScopeProvider.GetNewObjectScope())
{
    try
    {
        objectScope.Transaction.Begin();
        // Perform the persistence logic here
        objectScope.Transaction.Commit();
    }
    catch
    {
        // UPDATE: This explicit rollback is only
        // required if you're crazy and don't trust
        // that things will wrap up nicely on their own.
        if (objectScope.Transaction.IsActive) 
            objectScope.Transaction.Rollback();
 
        // Make sure you handle the exception here
        // failing silently is often a problem
    }
}

So all we did is check to see if the Transaction is Active and if it is still active rollback the transaction. Wasn’t that easy?

Overloading Implicit Conversions with Generics in C#

Overloading operators in a language is an excellent tool in every developer’s tool belt. It allows us to design our code in ways feeling far more natural. For example if we didn’t implement operator overloading for addition of numbers we would have some strange code. Could you imagine if we still wrote this kind of stuff?

int x = 5;
int y = 4;
int z = x.Add(y);

When we teach addition the non-computer way we learn it as “5 + 4 = 9”. The language reverses things and we switch the expression into “9 = 5 + 4”, but this is no big deal since we’re still using our operators. Some things happen behind the scenes so often we really don’t even think about them. Implicit conversions of numbers happens all the time. If we have a method that returns an integer we can certainly assign that value to a double. Why? Since we don’t lose any information doing that conversion it is just able to happen. We know that it is easy to store an integer value in a double so it is allowed.

One thing that I’ve always loved about the Nullable objects in C# is their ability to trick many of their newer users. A lot of people really don’t know about Nullable objects. I think they are fooled by the type? syntax into thinking it is something special. When the only thing special is the syntax. Beneath the surface we are actually just using Nullable<type>. My favorite part about the object is that they were nice enough to overload the implicit conversion from your type T into the Nullable<T>. The nullable object is just a cleverly hidden use of C# generics.

If you use .NET Reflector to examine the code for their implementation you will see this method.

public static implicit operator T?(T value)
{
    return new T?(value);
}

 

Sure that seems kind of boring. This is basically like a constructor in that it creates a new instance of the Nullable type and accepts an object of type T. The power comes from the fact that the user doesn’t need to realize he is changing types. It lets us do this.

int regularInteger = 3
int? nullableInteger = regularInteger;

 

Now to make things a little bit clearer I will change how their operator works so we don’t use their “?” shorthand. We will qualify things in the code so it is clear how the generic is working for us.

public static implicit operator Nullable<T>(T value)
{
    return new Nullable<T>(value);
}

 

So now if you want to use this for your generic object you can do the same thing as above. All you need is a constructor for your object that takes in a value of T, and then you write this method with your class name instead of Nullable. There is one thing to keep in mind though. There is one thing that could catch you off guard if your generic object contains state. That is that using this operator will create a new object.

If your generic is being exposed using a property, Value, like with Nullable then you could just set Value equal to the object. That approach is not as elegant, so if you can avoid having to set the value of the Value property I recommend it.

You can also perform an implicit conversion the other way, but that can potentially lose information if your object has state. If it does not then it is safe to perform that one. To achieve it just switch things around so you have this instead.

public static implicit operator T(Nullable<T> value)
{
    return value.Value;
}

So have fun assigning objects to the implicitly-converting, generic objects.

If you have questions or concerns or you just plain think I am wrong. Tell me about it! :-)

Build OpenAccess Project Using MSBuild on a Machine Without OpenAccess Installed

OpenAccess ORM is a powerful ORM tool that integrates very well into Visual Studio. It uses wizards and is tightly integrated, which makes it easy to pick up and start using. However, this same asset also provides a challenge when using this tool along with MSBuild on a machine without OpenAccess installed. There are some adjustments that needs to be made, since it is designed to be used with Visual Studio, so we have to add a couple of extra bits to get MSBuild to be able to build a project correctly.

So if you’re using the OpenAccess ORM tool and you want to use a build server you’ll need to make a couple of configuration changes to allow you to achieve this. Since I use a continuous integration server on pretty much every project I work on, I ran into this issue. There are a few things you need to do to get this working.

The first step to getting this working is to get the required dlls copied to a local directory. This is important because the build server will need to have these references for the project. To get these files all you need to do is look to see where the reference is coming from in your projects. In my case the location is.

C:\Program Files (x86)\Telerik\OpenAccess ORM\bin

So I copied the files being referenced by my project from here and put them into a lib folder in a relative directory for my project. I then removed all of the references to the libraries in their install directories and added the references back in this time pointing to the local directory.

AddLocalReferences

Once you have everything local you’ll want to make sure you got all of the required libraries by building your solution. The build should succeed.

When working with OpenAccess, it is important to know that the assembly used for persistence is going to be Enhanced by OpenAccess ORM. After Visual Studio builds that project it kicks off VEnhance.exe to inject IL into the library with added functionality.

This is the step that we next need to add in to our build so that we can achieve the desired result.

Find the VEnhance.exe file on your development machine. It should be located in a directory similar to this one.

C:\Program Files (x86)\Telerik\OpenAccess ORM\sdk

Copy that directory somewhere local to your project. We will need it in a minute. You also need to copy your Telerik.OpenAccess.dll into the local directory you created with the VEnhance.exe file. The executable will need that dll to be there in order for it to do the enhancement.

We will need to create a targets file which we will import into our project file. You can copy the one I have listed here and customize it to your needs. It is basically just the instructions to tell your project how to call the VEnhance executable. You will need to change the relative directory to your OpenAccessToolsDirectory in this targets file to reflect where you put the VEnhance.exe file.

enahnce.targets

<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
 <PropertyGroup>
   <OpenAccessToolsDirectory>$(SolutionDir)..\util\Telerik</OpenAccessToolsDirectory>
</PropertyGroup>
 
 <Target Name="EnhanceAssembly" Condition="'$(_AssemblyTimestampBeforeCompile)'!='$(_AssemblyTimestampAfterCompile)'">
   <Copy SourceFiles="$(TargetPath)" DestinationFiles ="$(TargetPath).notenhanced"/>
   <Copy SourceFiles="$(PdbFile)" DestinationFiles ="$(PdbFile).notenhanced"/>
   <Exec IgnoreExitCode="false"
         WorkingDirectory="$(TargetDir)"
         Command="&quot;$(OpenAccessToolsDirectory)\venhance.exe&quot; -verboseMode:1 -signAssembly &quot;-keyFile:$(ProjectDir)$(AssemblyOriginatorKeyFile)&quot; &quot;-assembly:$(TargetPath)&quot;"
         Condition="'$(AssemblyOriginatorKeyFile)'!=''" />
   <Exec IgnoreExitCode="false"
         WorkingDirectory="$(TargetDir)"
         Command="&quot;$(OpenAccessToolsDirectory)\venhance.exe&quot; -verboseMode:1 &quot;-assembly:$(TargetPath)&quot;"
         Condition="'$(AssemblyOriginatorKeyFile)'==''" />
   <Copy SourceFiles="$(TargetPath)" DestinationFolder ="$(IntermediateOutputPath)"/>
   <Copy SourceFiles="$(PdbFile)" DestinationFolder ="$(IntermediateOutputPath)"/>
 </Target>
 <Target Name="PeVerify" Condition="'$(_AssemblyTimestampBeforeCompile)'!='$(_AssemblyTimestampAfterCompile)'">
   <GetFrameworkSdkPath>
     <Output TaskParameter="Path" PropertyName="SdkPath" />
   </GetFrameworkSdkPath>
   <Exec WorkingDirectory="$(SdkPath)bin" Command="peverify.exe /nologo &quot;$(TargetPath)&quot;" />
 </Target>
 <PropertyGroup>
   <PdbFile>$(OutputPath)\$(AssemblyName).pdb</PdbFile>
   <RunPostBuildEvent>OnOutputUpdated</RunPostBuildEvent>
   <PrepareForRunDependsOn>
     $(PrepareForRunDependsOn);
     EnhanceAssembly;
     PeVerify
   </PrepareForRunDependsOn>
 </PropertyGroup>
</Project>

This file needs to be imported at the end of your project file. So you’ll want to open your project file using a text editor not Visual Studio. Remember that project files are really just XML so we can go in and made changes to their source code. We need to do this if we want to get our targets file included.

At the bottom of the file you should see XML that looks roughly like this.

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" DefaultTargets="Build" 
  xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- Pretend this is all of the rest of the project file -->
  <ProjectExtensions>
    <VisualStudio>
      <UserProperties OpenAccess_ConfigFile="App.config" 
          OpenAccess_ConnectionId="SilverlightAnalyticsExpressConnection" 
          OpenAccess_Enhancing="true" 
          OpenAccess_UpdateDatabase="false" 
          OpenAccess_EnhancementOutputLevel="1" 
          OpenAccess_UseMSBuild="True" />
    </VisualStudio>
  </ProjectExtensions>
</Project>

 

All we have to do is add in one line and change it to this using a relative path to where we placed the targets file. I admit I didn’t really know the best place to put it so I put it with the Telerik class libraries for my project.

<Import Project="..\..\lib\Telerik\enhance.targets" />
<ProjectExtensions>
  <VisualStudio>
    <UserProperties OpenAccess_ConfigFile="App.config" 
        OpenAccess_ConnectionId="SilverlightAnalyticsExpressConnection" 
        OpenAccess_Enhancing="true" 
        OpenAccess_UpdateDatabase="false" 
        OpenAccess_EnhancementOutputLevel="1" 
        OpenAccess_UseMSBuild="True" />
  </VisualStudio>
</ProjectExtensions>

And now we should be able to commit our changes and everything should work correctly on the build server. Cross your fingers. Make sure that all of your relative paths are correct. If you have any questions just post a comment below, on the Telerik forums, or both.

Silverlight 3 Out of the Browser

Running a Silverlight application out of the browser is very powerful. This lets users install a Silverlight application locally with a quick right click on the app in the browser. In earlier versions of Silverlight this was still pretty easy, but now you don’t even have to open up an xml file to do it.

So here is my simple Silverlight application running in the browser.

InitialMessageInBrowser

After I click that Button the app makes a web service call to change the text, which isn’t that important to this demo. I figured it was better than having it do nothing.

AfterClickInBrowser

Hooray we have a working Silverlight application. Now in order to get it running out of the browser we have only a couple of steps to take. None of which involve going into the AppManifest.xml file like was required in previous versions. Now we simply right-click on the Silverlight project in Visual Studio and select Properties.

SilverlightProperties

After enabling the ability to run out of the browser you just need to change the Out-of-Browser Settings. Doing this will create a file in the properties folder of the Silverlight application which has XML defining all of the settings configured here. This GUI just makes it easy to set up.

OutOfBrowserSettings

I like how simple this is. Not overloaded with tons of options. Just easy to use.

Now when we run the app we can right-click on the application and we are able to install the app locally.

RightClickInstall

When we click on the Install option we get a nice installation wizard with no complexity.

InstallApp

All the user has to do is decide where to put a shortcut. Once they click this the app will be installed and running. The application will look a little bit like this.

InitialMessageOutOfBrowser

And when we click out button we get another web service call and this time we pass a different parameter to the service call and get a different message. Take a look.

AfterClickOutOfBrowser

So how easy was that? Say that the user wants to uninstall the application now. That is also easy. All they have to do is right-click on it and select the option to remove the app and it is gone. They can do this in or out of browser.

RemoveApp

So now you know how easy it is to set up an out of browser Silverlight application.

Time-Tested Testing Tips – Part 7

At last night’s Cleveland .NET Special Interest Group I met Russ Nemhauser who gave a great beginners’ talk on Testing, TDD, and Mocking. One thing I noticed that he did when he was showing how to write unit tests was kind of interesting. I admit I usually take tests one at a time when I get my idea for the test I want to write I just go ahead and start writing it. When he was demoing he started by brainstorming a handful of tests and made comments for each test name.

Normally what I would do is sit for a second and think of the few cases of each type I want to test. So I might sit and think, “OK, which edge-cases exist that I need to watch out for”. Then I would go and write just the ones I deem likely to ever come up. I’m obviously not going to test every case out there.

So I tried combining his technique with mine to see what kind of result I would get, and it worked out pretty well. Even though I’ve not been using it long I’ll post this technique here.

Brainstorm and Prune

Start by coming up with some functionality you want to add. brainstorm a bunch of tests you could write to check a lot of different cases. Make a bunch, because it doesn’t take much time. Write the names of these stormed tests as commented lines as you come up with them.

Make sure when brainstorming that you’re getting some important types of tests: some testing the happy path, some testing the sad path, and some testing edge-cases. This will get you a good mix to choose from. Now obviously if you came up with only a few things to test then write them all! If you came up with a lot of tests then pick which ones are most likely to cause problems if they misbehave and also the ones which are most likely to occur and write them.

Don’t Write Too Many Tests For One Method

I need to be careful how I say this. I want people to write a lot of tests, however, a lot just means you should be testing pretty much everything you can. You need to be careful not to write too many. This is why I say to prune in the previous suggestion. Certainly it takes very little time to add a few extra test cases, but you’ll be unhappy if the method signature changes. Or if the business logic changes. Remember that one of the big reasons we test is to mitigate the cost of change. Testing should make it easier to change the code, but if you write to many it will make things harder.

If you wrote a dozen tests for a method and then you add in a new parameter then congratulations you now have a dozen tests which you need to modify. That is kind of painful. Perhaps if you had only written six tests and left off some of the redundant ones you could have saved yourself a lot of extra work there.

As a general rule I think that if you ever need more than about a handful of tests then your code is probably too complex. It is time to think about the single responsibility principle and figure out how you can break things apart, because perhaps you were correct that a dozen tests were needed. It just happened that those dozen tests should have been testing three different methods with four for each one.

Let Pain Guide Your Learning

When I was learning to test I did a lot of stuff wrong. Testing was painful. I knew that it was beneficial, but I didn’t usually like doing it. Why? Well because I was not doing it correctly. When I first started testing I was using unit and integration tests without really realizing that I was doing too many integration tests. Why? Because I didn’t know how to do things correctly. After a while I learned how to write more unit tests and it was great for a while, but I did a mistake that I have now seen many others make. I shifted my dependency onto something else. After a lot of work I now think I know how to test reasonably well, and I avoid making mistakes by remembering how painful a similar approach has been in the past.

I think that if you haven’t felt the pain of testing badly you’ll never understand how to do it write. When testing is painful you’re probably doing something wrong. This is the sign that you should try something else on your own or ask someone else how to better handle your current situation. Someone can sit here like I am now and tell you how to do something, but until you see why you need to do it that way it is hard to agree. I hope someone uses my testing advice here and when they run into some problem that they remember something in these testing posts and adjusts what they’re doing accordingly.

Windows 7 Keyboard Tips

Anyone who would be reading my blog probably already knows that you can use the keys [alt] + [tab] to switch between programs running on your windows system. This functionality has been around for a while. There are a lot of new and beneficial keyboard shortcuts that you might not know. Some came with Windows Vista and some with Windows 7, but after some time using the new Windows 7 interface I deem a lot of these shortcuts to be essential.

Opening Applications Using the Keyboard in Windows 7

Opening an application takes a good amount of time if you don’t have quick easy access to a lot of applications. I believe keyboard access is essential. Certainly I use quick-launch still, but I use it in combination with a keyboard in Windows 7, because of a slight deficiency in the new taskbar.

Win-Search

Searching for the application is a pretty good one if you haven’t set the app as a quick-launch one. Just press the [Win] key and start typing. Windows will display the results grouped in the start menu and you’ll be able to select the one you want to open. This is quick, but there are faster solutions.

Win-Number

The quick-launch bar is faster than most people realize. This isn’t new to Windows 7, but is relatively unknown as far as I can tell. Try holding down the [Win] key and press the number starting from the left of the app you want to run. For the application closest to the start menu you would hold [Win] and press [1]. In my case 1 opens Internet Explorer 2 opens FireFox and 3 opens Chrome. The order doesn’t really matter, but the point is that I know the numbers for the apps I use most often and I don’t change those numbers so they’re easy to use.

Win-Shift-Number

Just like using Win-Number you can also hold [Win] and [Shift] and press the corresponding quick-launch number to open another instance of an application that is already running.

 

Quick-Launch

Someone is probably wondering why quick-launch is in this post talking about using the keyboard. Well it is here because quick-launch now requires the keyboard if you want to quickly and easily open a second instance of the same application. Since the task-bar and quick-launch are combined now if we click on an application that is already open all it does is bring that app to the front of the screen. To open another instance just hold the [Shift] key when you click on the icon and you’ll get a new instance.

Ctrl-T

This is another quick-launch related shortcut. By holding [Ctrl] and clicking [T] you will be selecting quick-launch items. When you get the app you want to open just click [Enter]. If the application is already open then you can use the shortcut I mentioned before this one in combination. Once you have the app selected just hold [Shift] and click [Enter] while selecting the desired application.

Switching Windows Using the Keyboard in Windows 7

We “multitask” when we use computers or at least we think we do. Since we don’t really multitask we get stuck context switching all the time. This can really drain our ability to get things done, so we should make sure the switch happens quickly. There are plenty of shortcuts in place to make this easier.

Alt-Tab

By holding down the [Alt] key and pressing the [Tab] key we are able to browse through the set of running applications. These applications will be displayed with thumbnails of what the window looks like so we can decide if it is the one we want.

Win-Tab

Similar to the previous one, holding the [Win] key and pressing the [Tab] key will allow you to cycle through the running windows also. This garners a different view. Instead of having thumbnails in a rectangle in the center of the screen we instead get a sort of diagonal cascading line of windows that have been shrunken a little bit smaller so they can line up. This view in my opinion is kind of neat, but I still tend to use Alt-Tab. If you expect to often have difficulty differentiating applications from a thumbnail then this view is probably better for you.

Ctrl-Tab

Those familiar with tabbed applications know this common method of switching between tabs. This is available in a large number of Windows 7 applications. Hold [Ctrl] and press [Tab] to switch between tabs in an application. This functionality exists in most web browsers and a handful of other applications.

Ctrl-T

Windows 7’s new taskbar has added a very new interface to Windows. To select apps in the task bar you can hold [Ctrl] and press the [T] key which will select the applications in the taskbar. Once on the desired application simple press [Enter] to select that app. If only one window exists for that app right now it will open. If there are more then you will then use the left and right arrow keys to select the one you want and then press [Enter] again to bring it to the front.

Win-Number

This is one of the ones I mentioned for opening an application, but if the app is already open using it will select the application. Just hold [Win] and press the corresponding number of the application. Also if you want to switch between windows of that application just press the number multiple times until the correct one is selected.

There is another window switching option I really want in Windows 7 and that is the ability to switch between the same type of application. By this I mean that if I have an Explorer window open I want to be able to switch between the current explorer windows with an easy works-for-everything keyboard shortcut. I understand that the ones I’ve mentioned work, but they are clunky if I know that I want to restrict to just one application type. Win-Number seems like it is the best, but some applications I don’t keep pinned to the taskbar so I don’t know their number.

If you know any more cool shortcuts or know of a way I can switch easily between the same application please post them in the comments.

Time-Tested Testing Tips – Part 6

If you haven’t seen my earlier posts on this topic. I’ve mentioned a bunch of tips which should make your testing easier and more effective. If you’re looking for more tips check out these previous posts.

Time-Tested Testing Tips - Part 1

Time-Tested Testing Tips - Part 2

Time-Tested Testing Tips - Part 3

Time-Tested Testing Tips - Part 4

Time-Tested Testing Tips - Part 5

Don’t Repeat Yourself

I am sure a lot of you have heard this before and know that Don’t Repeat Yourself (DRY) means that you should reuse code so that you’re not repeating the same code all of the time. This also applies to testing. Sure we know to extract the logic in our tests, because we know that test code should be treated very well.

I am not talking about the logic in your tests not being repeated. I am saying that you should not test the same thing twice. Try to only test each thing once. This makes identifying the issue a lot easier. This is extremely important for edge cases. Make sure you’re only testing your edge cases in your edge case test.

You should have a test for each edge case and preferably it is the only test using parameters for the edge case. If something else is using it you’re creating difficulties in maintenance as well as tracking down bugs.

If you break a piece of code dealing with an edge case it will be harder to track down since two tests will be failing as a result. If there were only one it would be easier to find and fix the issue. Also there is the simple fact that things change. What happens if later on the desired logic of the program changes and the handling of the edge case changes. Well now you have to change the code in two places instead of just the one. This makes it more difficult to change the logic of your program. repetition == bad

Start Writing Tests For Everything

When you’re going to try some new piece of code how do you go about it? I am sure a lot of people will create a small sample Console Application and try something and have it print out results to the Console. This works very well, but if you’re really trying to pick up testing you should try writing a test instead. If you want to see how some new functionality works give it a shot in a test. Write a test to see what happens. Assert on the results and try to predict the output. This is a fun little way to work with things and you’ll get more experience using your testing framework.

It is important when learning to write tests that you do it as often as possible. Get used to writing them whenever you write code, so when you’re looking at something new you might as well look at it with a test. What better way to “test it out” than using your unit tests to do it.

Have a great day! Keep testing!

Constructors Should Be Simple and Stupid

There are plenty of commonly known and upheld ideas about how software should be written. There are rules and guidelines professed by many developers which recommend following this design principle or that one. Some are more important than others. Some are easier to find and correct than others.

One such rule that I believe is important to follow is that all constructors remain simple and stupid. This is about as advanced as I believe a constructor should even be.

public SomeObject(int someValue, int someOtherValue, 
    ISomeKindOfInterface someKindOfInstance)
{
    _someValue = someValue;
    _someOtherValue = someOtherValue;
    _someKindOfInstance = someKindOfInstance
}

These are merely assignment statements which use the local variables (parameters). We never ever want to call methods in our constructors. This includes calling constructors inside of our constructor. There are very good reasons for this which I will explain in detail.

 

 

Reasoning for keeping constructors simple

It is difficult to test classes which do work in their constructors. When work is done in the constructor it becomes more difficult to manage the object. This is because the mere creation of an instance causes something to happen. This is difficult to handle in unit-testing because you’re trying to keep control of all aspects of the code while testing. Control is required in order to test effectively, because you need to be able to expect certain behavior to exist based on carefully controlled circumstances.

Otherwise dependencies are hidden. When we instantiate variables inside of a constructor we are “taking a dependency” on the object we are creating. By depending on that code we are limiting ourselves greatly because we are not able to inject anything else. We are not coding against an interface we are working with a concrete class that will be difficult to change or remove.

When we go to test it will be difficult to do so because of these dependencies which have been hidden away in our constructor. Classes should be honest with you. They should tell you up front what else they are dependent on. This honesty is given by having constructors which are open and giving information freely by asking for the dependent objects through constructor parameters.

Otherwise we are adding an extra responsibility. The Single Responsibility Principle is another commonly held principle that states than any object should have one responsibility. This is powerful because it means that any object should have only one reason to change. When we add code to the constructor we have given the object the responsibility for knowing how to construct the object graph for this type of object. If the object is complicated to construct then there should be something else with that responsibility.

What to look for

Keep your eye out for any and all method calls. If any code other than a field or property is being called from within a constructor this is bad.

Instantiation of other objects is a sure sign of a dependency. This goes for anywhere not just in constructors. If you have the “new” keyword it means you’re dependent on the object being created.

Any “logic” in the constructor. If there are conditional statements then you probably have something to fix.

More than a handful of lines is probably too many as well, and is a sign that the constructor is doing more than it should.

 

Example bad code

public SomeObject(int someValue)
{
    _myKindOfTown = new Chicago();
 
    if (someValue > 5)
    {
        _myKindOfTown.HandleMyKindOfRazzmatazz();
    }
}

How to solve the problem

Removing the Object Initialization

One of the easiest ways to improve things is to get rid of the object initialization from the constructor. Passing the values for these objects as parameters is how we get around the issue of initialization. This makes it so that we do not do the work in the constructor.

In some cases we know we will not use that object, for example in our tests, so we can pass in a NullObject.

This process is called Dependency Injection, and it allows us to “inject” our dependencies into our objects.

Create a class to handle the construction

If your object has some complicated requirements involved in the construction that need to happen every time the object is created, you should think about creating an object whose sole responsibility is to create these other objects. As we said earlier a complicated initialization task is another responsibility, so we can have an object who owns that responsibility.

These are often Factory classes who know how to build other objects.

Fixed Code

// Object creation method in another class
public SomeObject CreateSomeObject(int someValue)
{
    ITown chicago = new Chicago();
    if (someValue > 5)
    {
        chicago.HandleMyKindOfRazzmatazz();
    }
    return new SomeObject(chicago);
}
 
 
// ctor for SomeObject
public SomeObject(ITown myKindOfTown)
{
    _myKindOfTown = myKindOfTown
}

Everyone Should Have a Continuous Integration Server

Have you ever heard another developer say, "it works on my machine"? Well I am sure a lot of people have heard that common phrase. Heck I've used it, but a lot of the time I will point out that it also works on the build server. That last part is what really counts in my opinion.

Any and all code you write should be checked into a source control repository. I think most people agree with that statement. Another very important thing is that your code actually work after being checked out from the repository. I wrote a blog post a while back about how to structure software projects.

One of the most important aspects of a well-organized project in my opinion, is the ability for a new developer on a project to be able to sit down and have a working solution as soon as they get the latest version of the application from the source control repository. Not only should that person be able to have a working solution, but that working copy should assist the developer in setting up the local environment. The solution should also be in a state which allows all of the project's tests to run without the user having to jump through a bunch of hoops.

I feel strongly that working on a project should be as simple as a checkout and a few more clicks to see the app running. Having a build server is a great way to maintain this on a project. Everything you need to be able to run your app needs to be in source control. This will be how the build server will get the application, so if it isn't in there, the server will not build it.

The build server is the ultimate answer to the question of, "does this code work on another machine?" You'll keep your code working everywhere, and you make sure that all of the pieces are integrated and working together effectively.

Have you ever had a developer commit their changes at the end of the day and commit code that breaks the build for everyone else? It is a lot harder to check in broken code without realizing it if the build server informs you right after checking in. Sometimes it is the compilation which fails and other times there are tests failing. It doesn't matter how it was broken, but it is broken now. Luckily you've got a build server to save you.

With a build server in place, everyone will know when the build breaks. If the offending developer is not around to fix it, you can always revert the changes until such time that the offender is available to fix the issue. Everyone continues on, because they knew of the issue and corrected it by reverting immediately. No one continued on thinking that broken code was really working code.