Thursday, September 24, 2009

Four Bits of Advice: Another Bit

This is the third post in a short series of post about developper adivce ([1], [2], [4]). The first one listed 16 pieces of advices in the form of headlines. The second post briefly explained the first 4, and this post is about the next 4:


0100: Consider infrastructure orientation
Where should infrastructure code go? Well, what is infrastructure code? It's code enabling domain objects to be used by the infrastructure parts of an application, like data persistence parts, the serialization parts, or the remoting parts. Often such code is added to domain objects in a vertical manner via inheritance, resulting in something along the lines of:















This works fine in a lot of cases, but there is the alternative of having the domain objects contain references to infrastructure objects, and letting them delegate to the infrastructure code when needed. That alternative results in a horizontal arrangement of domain and infrastructure code, which looks something like this:


The point is not that orienting infrastructure code horizontally is better than vertically. The point is that it is worth evaluating both option when designing a piece of software.

0101: Use role based interfaces
Interfaces, as in C# or Java interfaces, should define a single role an object can play. An object, on the other hand, can play several roles, and therefore it is perfectly all right for a class to implement several interfaces. This opposes a style of programming often seen in both C# and Java: Given a class called Foo, there is an interface called IFoo. The only class that implements IFoo is Foo, and all the public methods of Foo are implemtations of IFoo methods. An interface like IFoo does not add much value: It does not express or define anything that the public interface of Foo does not already express and define. The only thing IFoo adds is a test seam. Granted test seams are important and valuable, the same seam and more seams are available if Foo implements a number interfaces each defining a role. These roles make sense in terms of the application and its domain. Therefore they make the software easier to read, and with any luck more flexible.
For more on this I recommend Martin Fowlers post about role interfaces.

0110: Be economic
Do waste resources unnecessarily. Specifically: Do not make interfaces larger than they need to be. Do not add extra features to interfaces "just in case", or "because I can". The same goes for larger designs. Adding that extra stuff is wasteful, because you have to spend time writing it, because other programmers have to spend time reading and understanding it, and because it needs to be tested. Furthermore the shorter more concise implementation is usually the more elegant.
For more on this read through Kevlin Henneys slides on economy and elegance.

0111: Prefer code over comments
Comments can and do lie. Comments become obsolete and out of date. Comments are overlooked by programmers. By contrast, code is actually read by programmers, code is and stays current, and code with good naming can often express what would otherwise have been written in comments.
Thats it for now.

Sunday, September 20, 2009

97 Things Every Programmer Should Know

I have contributed a piece to the 97 Things Every Programmer Should Know wiki, which is a wiki containing a long list of good advice for programmers. The plan is that the wiki will turn into a book, by the same name as the wiki. There are well over 100 pieces on the wiki by now, and it's well worth the read; there are a lot really good tidbits.
The piece I contributed is about preferring declarative code over imperative code. It's at http://programmer.97things.oreilly.com/wiki/index.php/Declarative_over_imperative, if you go read it I would appreciate your feedback.

Sunday, September 13, 2009

Build automation with psake

I finally got a chance to take a proper look at psake, a build tool using PowerShell for the build scripts. Below is a psake script I did for a propject. It can compile the code by using MSBuild, clean up binaries, run NUnit tests, measure test coverage, and show the coverage results in the NCover gui. To do so a few paths are setup in the propoerties section, and it is assumed that tests reside in projects with names that end with Test:
properties {
 $base_dir = Resolve-Path .
 $testAssemblies = (Get-ChildItem "$base_dir" -Recurse -Include *Test.dll -Name | Select-String "bin")
 $buildartifacts_dir = (Get-ChildItem "$base_dir\src\" -Recurse -Include bin)
 $src_dir = "$base_dir\src"
 $tools_dir = "$base_dir\tools"
 $nunit_dir = "$tools_dir\NUnit-2.5.2.9222\bin\net-2.0"
 $ncover_dir = "$tools_dir\ncover"
 $db_script_dir = "$src_dir\Database"
 
 $env:Path += ";$ncover_dir;$nunit_dir"
 
 $test_result_file_postfix=".test-result.xml"
}

task default -depends Compile

task Compile {
 exec msbuild "$src_dir\DummyNameToProtectTheInnocent.sln"
}

task Test -depends Compile {
 foreach($test_asm_name in $testAssemblies) {
  $file_name =  [System.IO.Path]::GetFileName($test_asm_name.ToString())
  exec nunit-console.exe $test_asm_name /nodots
 }
}

task Coverage -depends Compile {
 $old_dir = pwd

 foreach($test_asm_name in $testAssemblies) {
  $file_name =  [System.IO.Path]::GetFileName($test_asm_name.ToString())
  $working_dir = [System.IO.Path]::GetDirectoryName($test_asm_name.ToString())
  $out_file_name = "$base_dir\$file_name".ToString().Replace(".dll", "") + ".coverage.xml"
  
  cd $working_dir
  NCover.Console.exe nunit-console.exe $file_name /nodots //x $out_file_name
  cd $old_dir
 } 
}

task Coverage_Gui -depends Coverage {
 foreach($xml in (Get-ChildItem . -Name -Include *.coverage.xml)) {
  tools\ncoverexplorer\NCoverExplorer.exe $xml
 }
}


task SetupDB {
 ."$base_dir\execute-sqlfile.ps1"

 Execute-SqlFile "$db_script_dir\RestoreBaseLineDB.sql" ".\SQLExpress" "master"
 Execute-SqlFile "$db_script_dir\SQL_CreateLoginAndPermissions.sql" ".\SQLExpress" "ConnectPortal"
 Execute-SqlFile "$db_script_dir\AddCompanyIDsToModul.sql" ".\SQLExpress" "ConnectPortal"
 Execute-SqlFile "$db_script_dir\UpdateOrder.sql" ".\SQLExpress" "ConnectPortal"
}

task Clean { 
 remove-item -force -recurse $buildartifacts_dir -ErrorAction SilentlyContinue 
}

I like the idea of using PowerShell for automation in projects targeting Windows for two reasons: One, its a real programming language (as opposed to xml), two, more and more things on Windows boxes can be set up and controlled through PowerShell. I want a real language for my build automation becuase it tends to become complicated over time, so sooner or later it I need the power of a programming language. And if the project only targets Windows, then PowerShell is good choice because its simply the Windows command line, and things like IIS, Exchange, SQL Server and so on provide PowerShell interfacfes.

Wednesday, September 2, 2009

Four Bits Worth of Dev Advice: The First Two Bits

This is the second post in a short series of post about developper advice ([1], [3], [4]). The first one listed 16 pieces of advices in the form of headlines. This post briefly explains the first 4:


0000: No bool to bool conversion
I dont know how many times I've seen code that basically converts from one boolean value to another. Like the following (real life, in-production, but obfuscated to protect the innocent) Java script code:


function IsEditorReady()
{
if (editorReady)
{
return true;
}
else
{
return false;
}
}
Why, oh why?
A variation of this is to have some boolean expression as the if-clause. A further variation is to have a series of nested ifs. Or to assign the boolean value to a variable instead of returning it. But still it's just converting something thats already a boolean to ... a boolean. And it's harder to read.


0001: Trust the implementation
When running on top of a big standard library take advantage of that. Don't re-implement the standard library functionality. Don't, for instance, write your very own sting tokenizer because you "want to be sure it works". Firstly you can be pretty sure your version doesn't work in all the corner cases. Secondly its a waste of time. Thirdly it's harder to read, than code using the standard library implementations. So c'mon; take advantage of those huge standard libraries we most often have today.

0010: Declarative over imperative
Writing code is error-prone. Period. But writing imperative code is much more error-prone than writing declarative code. Why? Because imperative code tries to tell the machine what to do step by step (and there are lots and lots of steps), while declarative code tells the machine what the intent is, and leaves the step by step details to the underlying implementation (which we trust, remember?).
Just as importantly declarative code is easier to read, for the exact same reason: It expresses intent, rather the method of reaching the intended goal. Consider this piece C++ of code:

void XYZClient::pushAlarm(const alarm_log &alarm)
{
alarmMutex.lock();
alarmList.push_back(alarm);
alarmMutex.unlock();
}


And then the alternative:


void XYZClient::pushAlarm(const alarm_log &alarm)
{
boost::mutex::scoped_lock lock(alarmMutex);
alarmList.push_back(alarm);
}


The second simply declares that the alarmMutex should be held until the end of the current scope. The first one tries to say when the mutex should be taken, and when it should be released ... and fails at doing so correctly. Granted it's just a matter of adding a try catch ... or is it...what about cases where the call to unlock fails?...oh, the headache.

0011: Beware of vampires
If you open up your doors, vampires will enter and drink your life blood...or in terms of OO software: If a class does not protect it private parts properly some other code will grip them, squeeze them and feast on their last bit of blood...well maybe that wasn't really in terms of software either, but consider this code:


public class Test : AbstractTestElementComposite
{
private readonly IDictionary headerProperties =
new Dictionary<string, string>();

// snip


public IDictionary HeaderProperties
{
get { return headerProperties; }
}


// snip
}


The problem is that the internal headerProperties dictionary is fully exposed by the getter. Oh, there's no setter, but that's just false protection, since vampirish code like this is allowed:


class Vampire
{
void SuckBlood(Test t)
{
t.HeaderProperties.Clear();
t.HeaderProperties.Add(“Alive?”, “Don’t know”);
}
}


This shows that the headerProperties dictionary isn't really kept private in this example. For a thourough write-up on the vampire issue I recommend Kevlin Henneys Encapsulation and Vampires article at StickyMinds.


That it for now, more advice follows.

Four Bits Worth of Dev Advice

Inspired mainly by 2 talks I saw at the JAOO 2008 conference (Kevlin Henney: Programmers Dozen, and Kevlin Henney and Frank Buschmann: 5 Design Considerations) I've put together list of advice for programmers. Such a list could obviously go on and on and on, but the exercise here is to choose the advice that I find most important, and that I see violated time and time again. So I decided to only allow as many pieces of advice as can be enumerated in 4 bits. And here's the raw, unexplained list:

0000: No bool to bool conversion
0001: Trust the implementation
0010: Declarative over imperative
0011: Beware of vampires
0100: Consider infrastructure orientation
0101: Use role based interfaces
0110: Be economic
0111: Prefer code over comments
1000: Use symmetric interfaces
1001: Use one abstraction level per method
1010: Grow guts
1011: Prefer use over reuse
1100: Write change friendly code
1101: Dry
1110: Don’t stay stuck
1111: Be curious

Most, but not all of these appeared in the two talks mentioned above.
I will be posting about all of the pieces of advice in the near future ([2], [3], [4]).