Expanding My Bookshelf

•January 31, 2010 • Leave a Comment

I have just updated my Bookshelf. It’s been Christmas season recently, which means I was able to add some substantial extensions to my library. First of all I got a copy of the Gang of Four (GoF) standard work “Design Patterns: Elements of reusable Object-Oriented Software”. As with Eric Evan’s book on Domain Driven Design, I am impressed by the precise style of writing they used to describe common patterns in Software. It’s been pretty handy in situations where I felt like “wait, I have seen this before, let’s do it right this time”.

My next book, “Best Kept Secrets of Peer Code Review” by Jason Cohen was provided for free by Smart Bear Software, the creators of CodeCollaborator a Software to help with code review. By coincidence, the book deals exactly with this matter and describes the necessary steps to introduce, execute and improve a peer code review process. A very interesting read. Thanks guys.

For Christmas I got Peter Seibel’s “Coders at Work”. Unfortunately, I don’t have much time for reading since I need to prepare for my (soon!!!) exams, so this is one of the books that will have to sit on my bookshelf unread for a while. However, I expect it to be a fun and more relaxed read than most other “tech books”.

My employer was kind enough to donate me an Amazon voucher, which I used to buy the Albahari Brother’s (the are also the creators of LINQ Pad) LINQ Pocket Reference and a book on Functional Programming with F#. Thank you very much Mrs. Leber. Even though I could just read small parts of them, they provided for an excellent bonus on understanding of the underlying principles on LINQ, which was especially handy during my work with the MoreLinq project.

I feel a little unsatisfied for having around 5 books sitting on my desk which I am half through. I’m on a very tight schedule at the moment and need to prioritize tasks relentlessly. Pretty much the same I had to do my whole last year, so I’m used to it :-) . Each of those books has been a valuable support to the work I’ve done lately, so I will continue to expand my library in this and that direction, if I see the above criteria met. This leaves me realizing, how important continuous learning and expanding one’s horizon is, which is fun because the horizon is so huge and there’s always something new to discover. Kind of opposite  to what I need to do for school at the moment (fixed horizons, fixed expectations and known solutions)…

Configuring Git and Mercurial to use DiffMerge

•January 28, 2010 • Leave a Comment

My preferred merge/diff tool at the moment is DiffMerge by SourceGear. Besides normal diff and also folder diffs, it supports three-way merging and has a pretty sweet, intuitive UI with a-well chosen colour scheme and excellent shortcuts. The reason it is my tool du jour is its perfect cross-platform implementation supporting Windows, MacOS X and Unix. The feature set (and the UI!) is same on all platforms. Remembering only the workings of one diff tool significantly reduces friction for me.

Integrating DiffMerge with the various VCS I use (mercurial, git and svn) is quite cumbersome, but is fortunately very well possible. I’ll post my sample configurations here. The configuration files are alway located in the user’s home directory. Configuration is the same for Windows/Mac OS X and Unix, however you’ll have to adapt the path to the DiffMerge executable accordingly.

Mercurial (~/Mercurial.ini):

[diff]
git = True

[extensions]
hgext.extdiff =

[ui]
merge = diffmerge

[extdiff]
cmd.diffmerge = c:\Programme\SourceGear\DiffMerge\DiffMerge.exe

[tortoisehg]
vdiff = diffmerge

[merge-tools]
diffmerge.executable = c:\Programme\SourceGear\DiffMerge\DiffMerge.exe
diffmerge.args = --result=$output -t1="Local Version" -t2=$output -t3="Other Version" --caption=$output  $local $base $other
diffmerge.binary = False
diffmerge.symlinks = False
diffmerge.gui = True
diffmerge.premerge = True

Mercurial will fire up DiffMerge during merges automatically from now on. Since the built-in diff command will always print directly to console (you can pipe this into a patch file too, very useful!) you need the extdiff extension to enable diffing with DiffMerge. That’s why TortoiseHg also needs to be configured explicitly to use DiffMerge as visual diff tool.

Git (~/.gitignore):

[mergetool "diffmerge"]
        cmd = diffmerge --merge --result=$MERGED $LOCAL $BASE $REMOTE
        trustExitCode = true
[diff]
        tool = diffmerge
[difftool "diffmerge"]
        cmd = diffmerge \"$LOCAL\" \"$REMOTE\"

Git does not merge automatically but will rather leave merge markes in the file. You have to use

git mergetool -t diffmerge

to bring up DiffMerge. On the web one can find recommendations to set

trustExitCode = false

when using DiffMerge. Since v 3.1. this is no longer needed because DiffMerge now returns correct status codes indicating whether a merge was successful or failed.

TDD as a Means to Explore New Platforms

•January 15, 2010 • Leave a Comment

On of my motivations behind the iRow project was to try a 100% TDD approach on a real world project. Being familiar with  features of .net testing frameworks (my favorite is MbUnit), my baseline expectations on the way such a framework should work and integrate into my development environment where set. Unfortunately, I was soon disappointed by the frameworks available. I have written about my research on iPhone unit testing frameworks before, so I won’t list their shortcomings here. In retrospective, working with a testing framework gave me unique opportunities to gain insight into the new platform.

The concrete advantages I experienced were:

  • learn about platform specific build systems and deployment details
  • forced to develop components in a loosely coupled fashion from the ground up
  • explore unique mechanisms of the language, that might require new or make known patterns redundant
  • fast compile-test cycle, less time spent in front of the debugger
  • combined with source control: painless experiments
  • combined with isolation framework: implementation shows how runtime manipulations can be made
  • testing framework implementation shows how code meta-data can be leveraged (or not leveraged)

I can imagine taking this approach to learning new platforms in the future. Plus, I think knowing how to verify the own code is an essential skill on every platform.

I’m At StackOverflow Careers Now

•January 13, 2010 • Leave a Comment

Since I am currently looking for an internship at a software company between my exams and studies, I thought it would be a good idea to file my CV at StackOverflow Careers. You can find it here.  The timeframe I am available is 06/2010 – 10/2010.

Modelshredder: Tracking down InvalidProgramException

•January 1, 2010 • Leave a Comment

I received my first bug report for modelshredder the other day. When trying to convert a sequence of objects into a DataTable, the following exception occurred:

I did some immediate research on possible causes for such an exception to be thrown. Microsofts KnowledgeBase indicated there might be a problem with the amount of local variables being allocated inside the injected method, however this was not the case since modelshredder uses only three local variables, regardless of the type of object. After some back and forth with the bug reporter, we were able to conduct a sample to reproduce the bug. Some trial and error with ShredderOptions including different subsets of members revealed, that the exception only occurred when the injected code tried to access an Indexer Property. The cause for this is pretty clear when taking a look at the MSIL generated for a property access.


ilgen.Emit(OpCodes.Ldloc_0);     // Load array on evaluation stack
ilgen.Emit(OpCodes.Ldc_I4_S, i); // Load array position on eval stack
ilgen.Emit(OpCodes.Ldarg_0);     // Load ourselves on the eval stack
ilgen.Emit(OpCodes.Call, pi.GetGetMethod());
// Check if we need to box a value type
if (pi.PropertyType.IsValueType)
{
    ilgen.Emit(OpCodes.Box, pi.PropertyType);
}

// Store value in array, this pops all fields from eval stack that were added this for loop
ilgen.Emit(OpCodes.Stelem_Ref);

As you can see, the code expects the getter to be callable without any parameter, which is not the case if (PropertyInfo) pi.GetGetMethod() returns an indexer method. Since I can’t imagine there’s any use in representing the contents of an indexer property in tabular form, I decided to simply ban indexer properties from the ShredderOptions. To do so, I have added a validation inside the ShredderOptions constructor to check all PropertyInfos for Index parameters.


PropertyInfo pi = member as PropertyInfo; 

if (pi != null)

{ 

if (pi.GetIndexParameters().Length > 0 ) 

throw new ArgumentException("May not contain indexer properties.", "members");

}

Even though the fix was pretty easy once the cause was identified, bugs in MSIL injection are very hard to track down. The exception could point to any other part of the injected code being incorrect. I haven’t seen any effective way (or tool for that matter) to debug or review runtime injected code yet. It appears, one is pretty much left with nothing but trial and error in such cases.

Announcing Modelshredder/MoreLinq project merge

•December 30, 2009 • Leave a Comment

I have been able to conduct some effort into the modelshredder project, and after a little consultation with John Skeet I am considering merging it with the morelinq project. morelinq provides some very useful IEnumerable extensions such as ForEach to execute an Action on each element of a sequence. Since morelinq is licensed under the Apache License it will be necessary to re-license the modelshredder code (which is LGPL currently).

I think there are a lot of reasons in favor for such a project merge:

  • morelinq has excellent code documentation and test coverage
  • both projects have equal scope (IEnumerable extensions)
  • simplified deployment for adopters of both libraries (one dll)
  • broader base of maintainers/contributors
  • Silverlight support for modelshredder

I have requested a code review on the morelinq mailing list and have incorporated the suggestions made. Until my code will be ready to be merged into the morelinq code base, I will have to write some unit tests and I want to further improve code documentation. The most notable change introduced is  that modelshredder is dropping support for non-generic IEnumerables. Restricting scope to the generic IEnumerable interface makes the code a lot less complex and easier to read.

I do still have a lot of ideas for the modelshredder project and will extend it as soon as I see fit. Other than all those “future plans” for modelshredder, I have been able to fix some nasty bugs regarding invalid MSIL being generated. But I will leave that for another post.

Breaking the Silence

•December 29, 2009 • Leave a Comment

It’s been pretty silent on my blog for a while. I have been busy finishing the iRow project and writing the corresponding paper, preparing and writing tests in school and holding various presentations there too. Since  21st of December I am officially on holiday and took some time to decompress and celebrate christmas with the family. I have had time to cross a lot of small things from my to-do list that accumulated since autumn, read some interesting books and make some software experiments.

iPhone resetting experience

•December 3, 2009 • Leave a Comment

My iPhone has started to behave somewhat “laggy” recently, taking too long waking up from standby when pressing a button, repeated hangs when using the virtual keyboard to write  emails etc.

My device also had accumulated a lot of “history” in terms of apps I don’t use any longer but was too lazy to delete and has been jailbreaked once.So I decided it would be the easiest to just reset the firmware, went into iTunes and hit the restore button.

iTunes proceeded taking a full backup of my decvice and restored the firmware afterwards, which took an hour approximately. After I reactivated the iPhone, iTunes asked me if I wanted to restore my personal settings and sync my apps, leaving me to choose what apps should go on the device again and let me even sort them on the springboard from within iTunes (makes it so much easier!). After that I synced my music and pictures and I was pretty impressed with the result:

  1. No hacking required, everything easily click-through
  2. All my apps data was conserved (notes, gps trails etc.)
  3. All my email settings was still there
  4. My music was all there
  5. My photos were all there

The complete procedure took me probably half an hour, rest of the time waiting for iTunes to finish :-)

Singleton Considerations

•November 22, 2009 • Leave a Comment

I started out writing this post as a series of comments on StackOverflow but I decided there just wasn’t enough room to discuss this.

The original question is titled “What is so bad about Singletons?” and can be found at StackOverflow here. The answer receiving the most upvotes was:

Paraphrased from Brian Button:

  1. They are generally used as a global instance, why is that so bad? Because you hide the dependencies of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is a code smell.
  2. They violate the Single Responsibility Principle: by virtue of the fact that they control their own creation and life-cycle.
  3. They inherently cause code to be tightly coupled. This makes faking them out under test rather difficult in many cases.
  4. They carry state around for the lifetime of the app. Another hit to testing since you can end up with a situation where tests need to be ordered which is a big no no for unit tests. Why? Because each unit test should be independent from the other.

1:

I agree with him on that. In cases, where such a dependency is not obvious by the classes name, the dependency should be injected. Injecting Singleton Instances into classes proves a wrong usage of the pattern.

2:

All Objects need to control their life-cycle in a way. All objects need to have a constructor/destructor. This is even more true in non-managed languages such as C++/Objective-C where you are responsible of releasing your collaborators (Java and .NET programmers tend to forget that).  A Singleton’s life-cycle is assumed to be the same as the application’s, so I don’t see the need to “control” that here. Most Singleton implementations are using a lazy-load mechanism to instantiate themselves. This is trivial and their life-cycle is unlikely to change, or else you shouldn’t use Singleton.

3:

The GoF Singleton Pattern description includes the following: (p.128, Consequences 3.)

Permits refinement of operations and representation. The Singleton class may be subclassed, and it’s easy to configure an application with an instance of this extended class. You can configure the application with an instance of the class you need at run-time“.

Contrary to static classes, Singleton Instances are normal classes and can therefore inherit from base classes and/or implement interfaces. In order to make a Singleton Instance swappable, you can either choose to inject (“initialize”) a “to-be-Singleton Instance” into the Singleton or lazy-load it based on some configuration info. Throwing exceptions on requests made before the Singleton Instance was initialized (and optionally, when an attempt is made to reinitialize it) ensures the same semantic behaviour as that of a simple Singleton Class. Eventually, this is no different from how an IoC Container would deal with Objects whose lifetime shall be that of a Singleton.

4:

If your Singleton carries a significant global state, don’t use Singleton. This includes persistent storage such as Databases, Files etc. Note that log files are an exception to that. In most cases their state isn’t significant for the behaviour of the Application. Good examples for the usage of Singletons are PrintSpoolers (fire and forget).

.NET Information Day Darmstadt

•November 6, 2009 • Leave a Comment

The .NET User Group Frankfurt and Microsoft Student Partners invited to the .Net Information Day conference at TU Darmstadt University on 4th November 2009.

It was the first .NET conference I attended and also my first encounter with the .NET User Group Frankfurt. Since I had to stay at school till 5pm and arrived at Darmstadt 6.30pm I missed out on the Clean-Code-Developer Initiative opening session and would have nearly missed the complete session about “MultiTouch with .NET 4.0″.

The first complete session I attended was “Distributed Applications with .NET 3.5 & Co.” by Christian Weyer and Dominick Baier from thinktecture. Their “YouTube” demo application was really awesome and Christian was a really great speaker and fun to listen, Dominick played the “Code Monkey” part. Although they just covered WCF basics that I was already familiar with, their talk was really interesting. They showed a fully working sample application featuring a simple HTTP service on the server side.  On the client side they did not just have an ASP.NET application but also an Apple Push Notification iPhone client. All live and all working, most impressive the iPhone client live over internet.

Closing session was  Effective, loosely coupled C# with Daniel Fisher and without Michael Willers, who was ill unfortunately. Besides covering the well known SOLID principles and having his short take on Joel Spolky’s Duct Tape Programmsers blog post. Very interesting. What followed was the best explanation of why one should prefer composition over inheritance I have ever heard of. Daniel claimed that in the contrived “Person->Employee” scenario composition should be used because it resembles reality more closely than inheritance. Of course an Employee is a Person. But what makes a Person an Employee? An employment Contract. What happens if a Person is employed at multiple companies? Right, the contract model provides advantages. This made me realize that there is indeed very litte necessity in multiple inheritance (that’s why it’s left out in C# I guess). Cases where it might prove useful are often better implemented using composition.

I really enjoyed attending the conference, it was excellently organized with interesting sessions and someone also sponsored soft-drinks. I also won a Microsoft T-Shirt, probably for being the youngest attendee :-) . The german .NET community is really cool with a rich diversity  and very competent speakers. I’ll try to attend one of the next User Group meetings and get to know them better.