Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Skills Matter - Agile Development in C#

I'll be running Skills Matter's Agile Development in C# 3 day training course (starting March 3rd) in London. The course material is written by Kevlin Henney and is excellent. I'm really looking forward to it. Feel free to email me if you're thinking of attending.

C# 2.0 - Visitor return type

In this entry I'm revisting the Visitor Pattern, this time using C# 2.0 generics rather than Java generics. One addition to the previous design is to declare two interaces, one for a void return and one for a non-void return:
public interface IVisitable
{
    void Accept(IVisitor visitor);
    R    Accept(IVisitor1<R> visitor);
}
public interface IVisitor
{
    void Visit(A visited);
    void Visit(B visited);
    void Visit(C visited);
}
public interface IVisitor1<R>
{
    R Visit<R>(A visited);
    R Visit<R>(B visited);
    R Visit<R>(C visited);
}
Each concrete element then simply implements both Accept methods:
public class A : IVisitable
{
    ...
    public void Accept(Visitor visitor)
    {
       visitor.Visit(this);
    }
    public R Accept<R>(Visitor1<R> visitor)
    {
        return visitor.Visit(this);
    }
    ...
}
I could do this in Java too of course. However, the C# version edges out the Java version in two respects. First, C# allows two types to have the same name as long as they have a different number of generic arguments.
public interface IVisitor
{
    void Visit(A visited);
    void Visit(B visited);
    void Visit(C visited);
}
public interface IVisitor<R>
{
    R Visit<R>(A visited);
    R Visit<R>(B visited);
    R Visit<R>(C visited);
}
Secondly, generic IVisitor works with all types (including value types such as bool) without the need for wrapper classes:
public class ExampleVisitor : IVisitor<bool>
{
    public bool Visit(A visited) { ... }
    public bool Visit(B visited) { ... }
    public bool Visit(C visited) { ... }
}

Statement Refactoring

I've just noticed this somewhere:
public string MakeRequest(string hostname, string message)
{
    Socket socket = null;
    IPAddress serverAddress = null;
    IPEndPoint serverEndPoint = null;  
    byte[] sendBytes = null, bytesReceived = null;
    int bytesReceivedSize = -1, readSize = 4096;
    serverAddress = Dns.Resolve(hostname).AddressList[0];
    serverEndPoint = new IPEndPoint(serverAddress, 80);
    socket = new Socket(AddressFamily.InterNetwork,
    SocketType.Stream, ProtocolType.Tcp);
    bytesReceived = new byte[readSize];  
    sendBytes = Encoding.ASCII.GetBytes(message);
    socket.Connect(serverEndPoint); 
    socket.Send(sendBytes);
    bytesReceivedSize = socket.Receive(bytesReceived, readSize, 0);
    socket.Close();
    if(-1 != bytesReceivedSize)
    {
        return Encoding.ASCII.GetString(bytesReceived, 0, bytesReceivedSize);
    }
    return "";
}
Why do programmers still write code like this in C#? Do they like verbosity? Why not write this instead:
public string MakeRequest(string hostname, string message)
{
    IPAddress serverAddress = Dns.Resolve(hostname).AddressList[0];
    IPEndPoint serverEndPoint = new IPEndPoint(serverAddress, 80);
    Socket socket = new Socket(AddressFamily.InterNetwork,
                               SocketType.Stream, ProtocolType.Tcp);
    int readSize = 4096;
    byte[] bytesReceived = new byte[readSize];  
    byte[] sendBytes = Encoding.ASCII.GetBytes(message);
    ...
}
It seems to me there are loads of these statement level refactorings that would prove really useful. Do any tools support "small" refactoring like this? Do any books talk about them?

Here's another: Instead of writing:
if (expression)
    return true;
else
    return false;
why not just write:
return expression;

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
    {
        //...
    }
}

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).