My name is Juri Strumpflohner and this is my technical blog. I'm a kind of jun. software architect, .Net, Android, Web and Java dev, TDD and best practices promoter and martial arts practitioner.

Recent Posts Subscribe

Testing Newbies: Some Thoughts about Test First

A quick post just before diving into the weekend filled with Yoseikan training, swimming, going out with friends and - of course - Android coding :) . But before, I'd like to post some thoughts about software testing I found on the web. These are mainly for those of you which didn't yet get into unit tests :)

First, the twelve benefits of test-first..

  1. Unit tests prove that your code actually works. That means you have fewer bugs. No, unit tests can’t replace system and acceptance testing. But they do supplement it. The fewer bugs that make it to SQA, the better.
  2. You get a low-level regression-test suite. You can go back at any time and see not only what broke but where the bug is. Many teams run the unit test suite as part of the nightly build. It’s a low-effort way to catch bugs before the build goes off to SQA.
  3. You can improve the design without breaking it. This is actually part of step 3 above, the refactoring step. So test-first code usually doesn’t need to be refactored. I have worked on some systems that were so screwed up, like a psychotic individual, you just couldn’t untangle them. Having unit tests in place, you can do powerful refactorings that can untangle the most challenging of system psychoses.
  4. It's more fun to code with them than without. You know what your code needs to do. Then you make it do it. Even if you don’t have a working system, you can see your code actually run and actually work. You get that great “I’ve done it!” feeling. Now repeat every minute or so. Just try test-first if you want to be high on endorphins, proud about your work, and motivated to do more.
  5. They demonstrate concrete progress.You don’t have to wait a month for all the pieces of the system to come together. You can show progress even without a working system. Not only can you say you’ve written the code, you can actually demonstrate success. Of course, this is another distinction that traditional programming teaches us to ignore. “Done” doesn’t mean you’ve written the code and checked it in. “Done” means the code actually runs in the system without bugs. Running unit tests is a step closer to the latter.
  6. Unit tests are a form of sample code. We all encounter library functions and classes we don’t know how to use. And one of the first places we go is the sample code. Sample code is documentation. But we don’t usually have samples for internal code. So we’re left sifting through the source or through the rest of the system. Because Bob, the guy who wrote that code, is no longer with the company, so we can’t actually ask him how it’s supposed to work. But unit tests are documentation. So when you can’t remember how to use class Foo, read the unit tests to find out.
  7. It forces you to plan before you code. Writing the test first forces you to think through your design and what it must accomplish before you write the code. This not only keeps you focused, it makes for better designs.
  8. It reduces the cost of bugs. Bugs detected earlier are easier to fix. Bugs detected later are usually the result of many changes, and we don’t know which one caused the bug. So first we have to hunt for and find the bug. Then we have to refresh our memories on how the code is supposed to work, because we haven’t seen it for months. Then finally we understand enough to propose a solution. Anything that reduces the time between when we code the bug and when we detect it seems like a obvious win. We consider ourselves lucky to find out about bugs within a few days, before the code is shipped to SQA or to customers. But how about catching them within a few minutes? That’s what test-first accomplishes with the bugs it catches.
  9. It's even better than code inspections. Code inspections, they say, are better than testing, because using them to detect and fix bugs is cheaper than testing. After the code ships, it’s much more expensive to fix the bugs. The earlier we can detect and fix bugs, the easier and cheaper and better. That’s the advantage of having code reviews: Code inspections catch more bugs within a few days, rather than a few months. But test-first catches some bugs within a few minutes instead of a few days. It is even cheaper than code inspections.
  10. It virtually eliminates coder's block. Ever wonder what statement to write next? Like writer’s block, coder’s block can be a real problem. But test-first systematizes the structured part of coding, allowing you to concentrate on the creative part. You may get stuck on how to test the next bit or how to make the test pass, but you’ll never be left puzzling over where to go next. In fact, usually you’re left with the opposite problem: You know you need to take a break before you burn out, but you’re on a roll and don’t want to stop.
  11. Unit tests make better designs. Testing a piece of code forces you to define what that code is responsible for. If you can do this easily, that means the code’s responsibility is well-defined and therefore that it has high cohesion. And if you can unit-test your code, that means you can bind it as easily to the test as to the rest of the system. Therefore, it has loose coupling to the pieces around it. High cohesion and loose coupling is the definition of good, maintainable design. Code that is easy to unit-test is also easy to maintain.
  12. It's faster than writing code without tests. Or to put it another way, skipping unit tests is faster, unless you actually need the code to work. Most of the effort we spend on code, we spend fixing it after we’ve checked it in to the source-code repository. But test-first eliminates much of that waste by allowing us to get more of it right to start with and by making bugs easier to fix.
These points pretty much include most of the benefits. Btw I found them here in case you want to read the whole post.

Second, I recommend you to also read Codinghorror's post which basically discusses the one above listing the twelve points.

Have a nice weekend!

Passing Property Names the "compiler-safe" Way

A common bad practice which I often find when browsing through code is to see people directly hard-code strings in their source code. I've also proposed some refactorings in some of my previous posts. Today I'd like to blog about a similar issue which targets the issue of object property referencing within code.

I guess most of us already had the case where you give a property of your entity like

SomeHelper.Validate(entityObject, "somePropertyName", value);
SomeHelper.Validate(entityObject, "someOtherPropertyName", value);
This "strange" assignment because SetProperty takes objects in a generic way and validates the specified property. Note, this is not real-world code, so don't be scared :) , but it may arise in similar ways throughout your code-base.
Another use case I was currently experiencing and which was the reason for writing this blog post is when announcing a problem about some property to the system user (i.e. in a log). In such a case you'd probably write
MyLogger.LogProblem("SomePropertyName", "Some message from a resource file");

So what's the problem with such code?
  • No compile-time-checking! Changing the property name of your object, won't give you any error during compile time but you may experience nice errors when the system is being used. Well ok, ReSharper does a nice job in also including such strings in refactorings, but still.
    These kind of bugs are heavy, since you may have difficulties in spotting them.
  • It is cumbersome to type and code because you have to remember the exact name of the property without any kind of Intellisense support.
These issues can be solved by using a nice Linq construct.
public static void LogProblem<T>(Expression<Func<T>> propertyExpression, string message)
{
    string propertyName = GetPropertyName(propertyExpression);
    if (propertyName == null)
        throw new NullReferenceException("The name of the property couldn't be retrieved!");

    LogEntry logEntry = new LogEntry()
    {
        Fieldname = propertyName,
        MessageDescription = String.Format(message, propertyName)
    };

    logEntries.Add(logEntry);
}

public static string GetPropertyName<T>(Expression<Func<T>> expression)
{
    MemberExpression body = (MemberExpression)expression.Body;
    return body.Member.Name;
}
This can then be used very nicely by rewriting the logging instruction I mentioned before like this
MyLogger.LogProblem(() => myObjInstance.SomePropertyName, "Some message from a resource file");
Voilá, you have a compile-time, fully intellisense supported logging method now. The only thing I don't really like is the somehow strange-looking declaration of the property name by having to use () => ...

“I am ready to write some unit tests. What code coverage should I aim for?”

Here's a nice "story" about code coverage from the Google Testing Blog.

Testivus on Test Coverage
Early one morning, a young programmer asked the great master:

“I am ready to write some unit tests. What code coverage should I aim for?”
The great master replied:
“Don’t worry about coverage, just write some good tests.”
The young programmer smiled, bowed, and left.

Read more on the official blog »
Code coverage is an interesting metric which I found particularly useful as an indicator of "trust in your tests". See my according post here.

HowTo: Install your Android app OTA on your device for testing

A fundamental thing when developing Android apps but also in general when developing with device emulators is to test your app on real devices. Android makes this easy. By activating "USB debugging" on the device and connecting it to your workstation with an USB cable. The app can then either be started from within Eclipse or by deploying it using the adb bridge.

However, most often I do not really want to debug the code on the real device, but rather just to test it by running it. ADB doesn't however allow you to install your app to an arbitrary IP (in the WLAN net for instance), but just by using the USB cable which, however, is really annoying when you just need to deploy your app. But don't give up, there are some alternatives which allow you to have some kind of OTA installation.

Practical example: Applying the Template Method design pattern

As I already mentioned in my previous post I'm currently doing domain objects to XSD generated object mapping. Monotonic, exactly, but I'm approaching the end of the work.
Still, when doing such annoying work, I'm continuously striving to reduce the amount of work by trying to find smarter, faster, more concise ways for doing this tedious work (in order to finish earlier ;) ). Usually after a couple of hours common patterns/repetitions emerge as I learn the structure of the underlying XSD. Refactorings then usually help to proceed faster.

A design pattern which I found to fit nicely when doing such object mapping work is the Template Method design pattern.

A template method defines the program skeleton of an algorithm. One or more of the algorithm steps are able to be overridden by subclasses to provide their own concrete implementation. This allows differing behaviors while ensuring that the overarching algorithm is still followed.
Source: Wikipedia
In fact, the most interesting part when doing this kind of mapping work is to define an appropriate program skeleton for outlining the basic structure and here is where I used the Template Method pattern.
The data flow is from the application's domain model to the XSD generated objects. Basically there is some input (one or potentially more domain objects) which produces the desired output (exactly one XSD generated object). These objects have then to be assembled properly before being serialized to the final XML output. Frankly, just basic serialization work.

Refactoring for the sake of compactness and reusability

Currently I'm doing a rather monotonic work, let's call it like this. We basically need to serialize our data to an XML file that has to match a given XSD which has been given to us by our customer. The problem, the XSD has not nearly the same structure of our own domain model which implies a lot of property 1-1 mapping between the C# objects generated from the XSD file and our domain model. Automatism?? Not really applicable. I tried already to figure out to which degree libs like AutoMapper could be useful but concluded that it wouldn't really bring much in the end.

A nice thing when coding such object mappings is that there emerge patterns which can then be refactored nicely, also because these mapping stores involve an overall structural/architectural design initially but then they are nearly a pure typing exercise (which often isn't that bad too). Take the example below:

List<SoggAggiudicatarioType> soggAggiudicatarioTypes = new List<SoggAggiudicatarioType>();
if (awardCompanies != null)
{
    foreach (ICompanyDetail companyDetail in awardCompanies)
    {
        soggAggiudicatarioTypes.Add(MapAwardCompanySoggAggiudicatarioType(companyDetail));
    }
}
convertedType.Aggiudicatari = soggAggiudicatarioTypes.ToArray<SoggAggiudicatarioType>();

This was one re-occurring pattern. A list of objects from our domain model had to be mapped accordingly to an array of a generated XSD type. Lot's of mostly similar constructs emerged so I refactored the whole stuff above to the following:

convertedType.Aggiudicatari = 
  MapArray<ICompanyDetail, SoggAggiudicatarioType>(awardCompanies,MapAwardCompanySoggAggiudicatarioType);

Transforms in a nice one-liner :) and saves you from cramps in your fingers ;) . But the code hasn't disappeared, it has just been refactored to the given, generic method:

protected TConvertTo[] MapArray<TConvertFrom, TConvertTo>(List<TConvertFrom> sourceData, Func<TConvertFrom, TConvertTo> convertFunction)
{
    List<TConvertTo> convertedResult = new List<TConvertTo>();
    if (sourceData != null)
    {
        foreach (TConvertFrom sourceItem in sourceData)
        {
            TConvertTo converted = convertFunction.Invoke(sourceItem);
            convertedResult.Add(converted);
        }
    }

    return convertedResult.ToArray<TConvertTo>();
}