C# Gotcha

I've just spent 10 minutes blankly staring at my screen trying to figure out why the heck an ultra simple piece of C# didn't work... Suppose you create the following and compile it into an assembly called JSL.HelloWorld.dll
namespace JSL.HelloWorld
{
    public class Example
    {
        //...
    }
}
And then you write a test for it...
namespace Tests.JSL.HelloWorld
{
    using JSL.HelloWorld;
    using NUnit.Framework;

    [TestFixture]
    public class ExampleTest
    {
        [Test]
        public void Eg()
        {
            Example puzzle = new Example();
            //...
        }
    }
}
Looks fine. Yet when you compile the test csc complains that "the type or namespace name 'Example' could not be found...". Ten minutes blank staring follows. The problem is there are two namespaces called JSL.HelloWorld. There's one that's global that contains the class called Example we're after. And there's another one inside the namespace called Tests (called Tests.JSL.HelloWorld). So the compiler tries to resolve Example in Tests.JSL.HelloWorld but not in JSL.HelloWorld. One solution is as follows:
namespace Tests.JSL.HelloWorld
{
    using global::JSL.HelloWorld;
    using NUnit.Framework;

    [TestFixture]
    public class ExampleTest
    {
        //...
    }
}

BCS SPA 5th Jan 2005

Immo H√ľneke has mercilessly bullied me into speaking at a BCS SPA meeting in central London. It'll be essentially the same talk I gave to the North East branch - a hotch potch of interesting quotes and various related topics loosely knitted together into something vaguely resembling a presentation.

The End of Certainty

is the title of an excellent book by Ilya Prigogine. It's subtitled Time, Chaos, and the New Laws of Nature and I reckon at least two of those three apply to software. Prigogine is a Nobel Prize winner (in Chemistry) and has worked on problems of non-equilibrium, complexity, self-organization, entropy, etc, for over four decades. Rather than writing an extensive review I'm going to open the book at a few random pages...
A nonequilibrium system may evolve spontaneously to a state of increased complexity.
Bifurcations are a source of symmetry breaking...Bifurcations are the manifestation of an intrinsic differentiation between parts of the system and its environment.
Once we have dissipative structures we can speak on self-organization.
...order can only be maintained by self-organization.
...constraints do not eliminate creativity, they provoke it.
...our position is that classical mechanics is incomplete because it does not include irreversible processes associated with an increase in entropy.
There is a necessary trade off between certainty at a given time for continuity through time.

I've won something!

I'm chuffed to learn one of my articles has won best Overload article for the year (the year in question being 2003). Writing unpaid articles isn't as altruistic as it appears. You learn a great deal by writing. If you're a developer your job is writing descriptions. Writing matters. Richard Gabriel's advice to developers is to learn poetry. And Dijkstra said that the best indicator of a developers skill was mastery of their native tongue. One of Michael Jackson's lexicon entries is called simply 'Descriptions'.

ACCU 2005 Conference

I'll be speaking at the ACCU conference held 20th to 23rd April 2005 (with an additional pre-conference tutorial day on the 19th). These are always great developer focused conferences. Confirmed speakers include Bjarne Stroustrup, Jim Coplien, and Kevlin Henney. More details.

Java Tiger - Visitor return type

I've been playing with generics in the latest JDK (among other features) to see how many of the features are useful in my eternal JavaSauce project. Quite a few as it happens. Annotations, varargs, new for loop iteration, static imports. And generics. In particular generics for the Visitor Pattern. Here's what I had before Tiger (some class names changed to save typing):
public interface Visitable
{
    void accept(Visitor visitor);
}

public interface Visitor
{
    void visit(A visited);
    void visit(B visited);
    void visit(C visited);
}
These interfaces allow me to visit the A, B, and C classes which all live in the same package and particpate in a Composite relationship (as is often the case). Given the recursive whole-part relationships there's a strong temptation to make the return type boolean instead of void. However, some concrete Visitors don't need or use a return type so for these classes the void return type is preferable. There's a definite tension. Generics can help. Here's what I've now got:
public interface Visitable
{
    <R> R accept(Visitor<R> visitor);
}

public interface Visitor<R>
{
    R visit(A a);
    R visit(B b);
    R visit(C c);
}
One slight problem with this approach is that R can only be a reference type:
public final class SomeVisitor
    implements
        Visitor<boolean>  // compile time error
{    ...
}
A small Adapter can help to solve this:
public final class BooleanVisitorAdapter
    implements
        Visitor<Boolean>
{
    public BooleanVisitorAdapter(final BooleanVisitor adaptee)
    {
        this.adaptee = adaptee;
    }

    public Boolean visit(final A visited)
    {
        return Boolean.valueOf(adaptee.visit(visited));
    }

    public Boolean visit(final B visited)
    {
        return Boolean.valueOf(adaptee.visit(visited));
    }

    public Boolean visit(final C visited)
    {
        return Boolean.valueOf(adaptee.visit(visited));
    }

    private final BooleanVisitor adaptee;
}

public interface BooleanVisitor

{
    boolean visit(A visited);
    boolean visit(B visited);
    boolean visit(C visited);
}
Allowing:
someObject.accept(new BooleanVisitorAdapter(
    new BooleanVisitor()
    {
        public boolean visit(final A visited) { ... }
        public boolean visit(final B visited) { ... }
        public boolean visit(final C visited) { ... }
    }));
Note how the adapter creates a Boolean from a boolean. That could be handy; it could avoid the client writing
new Boolean(true)
which would cause needless pressure on the garbage collector (remember this is in a recursive context).

Talk in Newcastle Dec 9th

I've been invited to speak at a BCS SPA-NE meeting in Newcastle on December 9th. show details

Caller has Custody

I recently discussed the idea of custody with Kevlin Henney. The general rule in software is the caller has custody. This is perhaps one of those things that's obvious once you realize but that until you realize it you might miss it. To take a simple example - calling a method with an argument. If the argument is a value there is no custody to worry about. But what if the argument is a pointer (or reference - something that creates a level of indirection).
void method(type * p);
Caller Has Custody is concerned with deciding who has custody for the object p points to. Who is responsible for creating/destroying that object? And the answer, clearly, is the code calling the method. It's not the method itself. Less experienced programmers (to generalize horribly) seem to be overly worried by this and, particularly in C++, have a tendency to use smart pointers to express this rather than using a simple raw pointer.

Perhaps Caller Has Custody is not quite so obvious for constructors. It's natural for a constructor to remember the information passed in via its parameters.
class eg
{
public:

    eg(type * p)
        : p(p)
    {
    }
    ...
}
Perhaps the nagging doubt with a constructor is that since a constructor creates a new object any information saved as part of the state of the object can easily persist beyond the duration of the constructor call itself. Perhaps that's why (again to generalize horribly) less experienced programmers seem to want to copy/clone the argument - that way the callee can take custody of the clone, and the newly created object becomes completely self contained; free from any lifetime dependencies on anything outside itself.
class eg
{
public:

    eg(type * p)
        : p(p ? p->clone() : 0)
    {
    }
    ...
}

This has a supercial attraction but it's not a good road to take. The right road is to take a deep breath and, just like in real life, accept the interdependent nature of things. A big part of mastering object-oriented programming is mastering the nature of the connections. We all chant the mantra low-coupling high-cohesion but rarely do we really embrace it. By definition a highly cohesive class does one thing and one thing only. It has a single defining responsibility. That implies two things: first, cohesive classes tend to be small and second, systems are composed of lots of objects. But all the objects in a system have to be connected together (if they're not then you've got more than one system). Thus an important part of designing an object is designing it's connections to other objects. Objects are never totally self contained. They always live in a larger context, and it's the larger context that gives them meaning.

C# Explictness

At the ACCU 2004 conference I gave a talk on the evolution and design of C#. During the talk I emphasized the explicit nature of C# software. It's rare (at least in C# 1.0) for the compiler to add code to what you've written. To take a simple example: new int[4]{1,2,3}; is a compile time error in C#. The compiler does not append a default zero to the list. Another example is the virtual and override keywords:
class Wibble
{
    public virtual void Method() { ... }
}
class SpecializedWibble : Wibble
{
    public override void Method() { ... }
}
Another example is how the ref and out keywords have to be placed on both the argument and the parameter. Lack of fall-through in a switch statement is another. But there are some counter-examples. Default visibility is internal and default accessibility is private. But note that static constructors, destructors, and explicit interface implementations of properties indexers and operations are not private by default. In those cases you can't specify an accessibility and they're not private since they can't even be called from sibling functions. Here's another one. By default a class is not sealed. I find this surprising because inside the class the reverse is true - you have to explicitly use virtual/override keywords. Perhaps C# would benefit from an unsealed keyword (the checked/unchecked provide a precedent for paired keywords). Then all classes would have to be explicitly abstract, unsealed or sealed.
unsealed class wibble
{
    ...
}
sealed class SpecializedWibble : Wibble
{
    ...
}
It seems to me there is an important distinction to be made between these kind of defaults (where there is a choice) and defaults where there is no choice (for example interface members must be implicitly public).

C# Standard Interim Drop

TG2 has released an interim public drop of the revised C# standard. You can grab a PDF file from these sites: The usual boiler-plate wording applies... TG2 is providing these working documents to the public for informational purposes only. The contents are subject to change.

Comments and Style

Here's a small fragment I've just spotted in The Elements of Java Style.
if (this.invoiceTotal > 1000.0) {
    this.invoiceTotal = this.invoiceTotal * 0.95;
}
The authors say that the program appears to give a 5 percent discount. And again in the comment (the tip is on writing comments) they point out that:
// Apply a 5% discount to all invoices 
// over one thousand dollars
is a valueless comment because it provides little additional information. Maybe. But it does provide some additional information. I count three things the comment says that the code doesn't. One is the % symbol, two is the word discount, and three is the word dollars. The point is you can say these three things in the software itself. For example:
if (this.invoiceTotal > 1000.0) {
    final double discount = this.invoiceTotal * 0.05;
    this.invoiceTotal = this.invoiceTotal - discount;
}
To my eyes the repetitive this. is just noise, so I would simplify to:
if (invoiceTotal > 1000.0) {
    final double discount = invoiceTotal * 0.05;
    invoiceTotal = invoiceTotal - discount;
}
and then to:
if (invoiceTotal > 1000.0) {
    final double discount = invoiceTotal * 0.05;
    invoiceTotal -= discount;
}
Say it in software. Less code, more software.

I've received some feedback on my initial post - which is nice. Ric Parkin advised caution about drawing analogies from The Quantum Self - mostly because any analogy, when stretched too far, will snap. And I agree. Analogies can be useful but you musn't forget that software is a discipline in its own right.

So to expound a little, when I was thinking of the particle/wave analogy I wasn't thinking of the dynamic aspect, the interaction - I was likening the particle aspect to the inside of an entity and the wave aspect to its connections to the outside. The shape. The fractal shape if you like (since I'm also reading Chaos). Shape is important. Richard Gabriel talks about shape quite a lot in his excellent book Patterns of Software.

Kevlin Henny (who incidentally, coined the phrase "less code more software") also had some insightful comments on the word follows in "form follows forces". It suggests moving only in one direction, and we all know this is not the case. Developing software is not a linear process. Feedback is natural and healthy. If there was a word that conveyed follows-and-is-followed-by I'd use that. But I can't think of one.

Particles and Waves

I'm reading The Quantum Self by Danah Zohar (ISBN 0-00-654426-6). There are lots of passages that remind me of aspects software development. Or rather, aspects of software itself. In particular, during my consultancy travels I notice that a lot of software shops pay too much attention to the individual bits of software and not enough attention to the way the bits are connected together. The connections are everything. As Fred Brooks said (in The Mythical Man Month):


The essence of a software entity is a construct of interlocking concepts

Anyway, back to The Quantum Self and the snippet that grabbed me:


each sub-system maintains some identity through its particle aspect and merges with a new and larger identity through its wave aspect.

The particle aspect reminds me of the individual bits and the wave aspect reminds me of the interlocking. Neither is more important. A quality design needs both. Poor designs are typically wave-aspect-poor. Same for books. A lot of books on, for example, C++ focus on the particle aspect of C++. They give you lots of small code fragment and detail on syntax but almost nothing on the bigger picture; on how to design the stuff to fit together and how to use C++ idiomatically to reflect the design.


I'm also reading Chaos by James Gleick (ISBN 0-349-10525-1). There's a bit in it that reminded me of something Kevlin Henney said in one of his presentations. He (Kevlin) was discussing Patterns (in the Chrisopher Alexander-Richard Gabriel sense rather than the Gang of Four sense) and in particular the idea of forces. Gleick (quoting D'Arcy Thompson) asks:


whether all the patterns might be reduced to a single system of generating forces.

In my copy of Chaos I've scribbed "form follows forces". I mean this as a replacement to the idea of "form follows function" (which is a sound-byte I've never agreed with). Forces are important. In my mind they relate to the particle-wave duality I mention above. The forces come from the wave aspect. From how the parts interconnect. From the design. To quote Eliel Saarinen


Always design a thing by considering it in its next larger context.

This is one reason testing is so important. Testing forces you to use things. Using something forces you into the next larger context. This won't (despite what some say) magically make designs appears all by themselves but it does put you in a good place to think design thoughts.