Posts tagged with c - page 13

First look: Applying Domain-Driven Designs and Patterns

In an attempt to quench my thirst for all things C# and having already torn through the great .NET Framework Design Guidelines and less-great Effective C# I grabbed a copy of Applying Domain-Driven Design and Patterns (With Examples in C# and .NET) by Jimmy Nilsson.

The book is obviously based around domain models but also gives some coverage to test-driven development, NHibernate, design patterns, refactoring, code-smells etc.

This is only a first-look as I’m only up to page 130 of the 500+ the tome weighs in at but here are a few observations so far.

The Impedance Mismatch Between Domain Model and Relational Database

One annoyance with the book is that is identifies and discusses problems and then offers no discussion or ideas for a solution before moving onto another topic.

A good example is this section which touches on the mismatch between the primitive types of .NET and SQL without the consideration of how/where to check this, the fact that SQL types can be null with no regard to .NET 2’s INullable, bit flags or ‘magic values’.

How to Recognize If an Application Will Be Long Lasting

Another perfect example of the previous problem. The heading asks the question but the short anecdote about how a hacked together app became mission critical fails to answer it.

Use public fields

Jimmy proposes a number of techniques that fly in the face of .NET Framework Guidelines and other solid material. This is highlighted by the phrase;

As long as the fields are both readable and write-able and no interception is needed … public fields are at least as good as properties.

Perhaps Jimmy doesn’t know that converting a field to a property later will break binary compatibility with anything using your assembly.

Expose internals for testing

…expose sub-results so they are testable

flies in the face of hiding the implementation and Jimmy does at least refer to this balance but the whole idea of exposing unnecessary details for the sake of being able to test them gives me a shudder.

Throwing aside the whole question of whether you should write unit tests that test implementation rather than interface a better solution would be to add a

#if TESTING

block to classes that really need to expose their internals to your test tools and compile with that switch set in your testing environment.

Use static factory classes!

Jimmy extracts the factory methods into a new class and but then leaves them static. A static class throws away substitutability, extension and indeed everything that makes OO great for the sake of being able to access it like a global variable.

Expose IList as read-only

On page 102 Jimmy refactors a “public IList Children” field firstly making it a read-only property and then creates a AddChild method which is fine but then how will he stop people modifying his IList? With ArrayList.ReadOnly(children) of course bemoaning how clients still see .Add etc.

Hello Jimmy, let me introduce you to IEnumerable.

Use reflection to set internal properties from Factory & Repository!

Jimmy describes how some properties should be read-only but then the Factory and Repository need to set the values. He proposes reflection.

Maybe Jimmy missed the memento pattern and dislikes the internal keyword.

Coding standards

All the code samples use _ for internal members – something that Microsoft guidelines and their FxCop tools are keen to stamp out. Besides being ugly it also reeks of the obsolete Hungarian naming prefixes.

Storybook format

The whole book is written in “I still remember”, “I worked on an application”, “After that, I tried Domain Models”… It makes for slow reading at times.

Well that about wraps it up so far.

[)amien

Extend HttpApplication with session counts and uptime

It’s sometimes useful to know or display how many people are currently using your web application and how long it’s been up for.

As web applications normally inherit from System.Web.HttpApplication we can extend this class with a common re-usable class to add the required functionality.

public class WebApplication : System.Web.HttpApplication {
    private static readonlyDateTime pStartedAt = DateTime.Now;
    private static long pSessionCount = 0;

    public WebApplication() : base() { }

    public override void Init () {
        base.Init();
        HookEventHandlers();
    }

    public static long SessionCount {
        get { return pSessionCount; }
    }

    public static DateTime StartedAt {
        get { return pStartedAt; }
    }
    public static TimeSpan Uptime {
        get { return DateTime.Now.Subtract(pStartedAt); }
    }

    private void HookEventHandlers () {
        IHttpModule httpModule = Modules["Session"];
        if (httpModule is SessionStateModule) {
            SessionStateModule sessionStateModule = ((SessionStateModule) httpModule);
            sessionStateModule.Start += new System.EventHandler(SessionStart);
            sessionStateModule.End += new System.EventHandler(SessionEnd);
        }
    }

    private void SessionStart (object sender, EventArgs e) {
        Interlocked.Increment(ref pSessionCount);
    }

    private void SessionEnd (object sender, EventArgs e) {
        Interlocked.Decrement(ref pSessionCount);
    }
}

The next step is to ensure your web application’s class – as defined by global.asax – is of the new WebApplication type. A good approach is to have your own Global.asax.cs file inherit directly from the new WebApplication;

public class App : WebApplication { ... }

Now those sessions and uptime are being tracked how do you get at them?

lblCurrentSessions.Text = WebApplication.SessionCount.ToString();
lblUptime.Text = WebApplication.Uptime.ToString();

This approach is only suitable for sites operating on a single web server.

[)amien

IEnumerable as IEnumerable

A few weeks ago I touched on the substitutability of generic types and how Collection<BaseClass> is never substitutable for Collection<SubClass>. This is because while the read facilities would be substitutable the write ones would not be. A Collection can’t contain non-SubClass classes.

One approach for dealing with collections in general recommended in .NET Framework Design Guidelines is to expose IEnumerator or IEnumerable interfaces rather than the collection itself – especially if you intend on it being read-only.

But even IEnumerator<T> and IEnumerable<T> can’t help you if you need to return not but a base-class or interface that should be substitutable for. Unless the base-class you want _is object_ in which case seeing `IEnumerable` inherits from the non-generic `IEnumerable` solves your problem.

C#’s generics aren’t clever enough to realize that an instantiated generic class might be substitutable for another generic class although. Wilco points out that the .NET CLR supports “generic contravariance” but C# doesn’t yet expose it.

In the mean time trying to passing back IEnumerator<T> to something expecting IEnumerator<BaseClassOfT> will result in a compiler error. Try cast ing it and a run-time error awaits.

One option would be to create a whole new Collection<BaseClass> and copy each SubClass element into it but this is hardly efficient or elegant.

What would be really cool is if you could somehow wrap it like;

public IEnumerable<BaseClass> BaseClasses {
    return new BaseEnumerable<BaseClass, SubClass>(subClassCollection);
}

Of course you’d need BaseEnumerator and BaseEnumerable generic classes to do this and preferably they’d be able to enforce that SubClass is of BaseClass at compile time.

So here are two classes to do just that for your enumerable pleasure.

using System;
using System.Collections;
using System.Collections.Generic;

public class BaseEnumerable<TBase, TSub> : IEnumerable<TBase> where TSub : TBase {
    private IEnumerable<TSub> subEnumerable;

    public BaseEnumerable(IEnumerable<TSub> subEnumerable) {
        this.subEnumerable = subEnumerable;
    }

    public IEnumerator<TBase> GetEnumerator() {
        return new BaseEnumerator<TBase, TSub>(subEnumerable);
    }

    IEnumerator IEnumerable.GetEnumerator() {
        return subEnumerable.GetEnumerator();
    }
}

public class BaseEnumerator<TBase, TSub> : IEnumerable<TBase> where TSub : TBase {
    private IEnumerator<TSub> subEnumerator;

    public BaseEnumerator(IEnumerable<TSub> subEnumerable) {
        subEnumerator = subEnumerable.GetEnumerator();
    }

    public BaseEnumerator(IEnumerable<TSub> subEnumerator) {
        this.subEnumerator = subEnumerator;
    }

    public TBase Current {
        get { return subEnumerator.Current; }
    }

    public bool MoveNext() {
        return subEnumerator.MoveNext();
    }

    public void Reset() {
        subEnumerator.Reset();
    }
}

They work clean and fast for me but I’m no expert on the responsibilities of implementing the Dispose pattern. Warranty is not included and your mileage may vary.

[)amien

Substitutability of generic types in .NET

The “is” operator

Anyone using object orientated programming soon finds themselves wanting to perform some action only if an object is of some type or implements some interface.

The easiest way is to do this is to use the “is” operator. Typically it will appear something like;

object objA = FunctionToGetAnObject();
if (obj is SomeClassOrInterface)
    ((SomeClassOrInterface) obj).SomeMethod();

Here if obj_A is of a type that implements SomeClassOrInterface anywhere in its inheritence tree then SomeMethod of SomeClassOrInterface will be called.

Test substitution with generic types

Now lets say we have our own generic type – here’s one to illustrate a point;

public class DamoClass<T> {
    public T GetProperty { get { ... } }
    public T SetProperty { set { ... } }
    public bool IsValid { return true; }
}

If we want to check obj_A supports DamoClass<T> but we don’t care what type T is you might expect to be able to perform;

if (objA is DamoClass)

But that results in a compilation error – you can’t reference a generic class without specifying the type parameters regardless of whether you care about them or not. You might then try;

if (objA is DamoClass<object>)

After all every class inherits from object. This compiles fine but at runtime if objA is of any type other than object, e.g. DamoClass<string> it will return false.

Why?

The following might be what you had in mind;

if (objA is DamoClass<object>) {
    ((DamoClass<object>) objA).IsValid();
    object test = ((DamoClass<object>) objA).GetProperty;
}

Which looks fine but if .NET allowed that then how would it prevent;

if (objA is DamoClass<object>)
    ((DamoClass<object>) objA).SetProperty = 11;

When objA.AssociatedObject might well be something other than an integer? It can’t – so it doesn’t.

Solution

The solution is to split your generic class into two classes.

The first contains your non-generic methods and properties and the second inherits from the first adding all the generic specialisation. The good news is that they can even have the same name.

public class DamoClass {
    public object GetProperty { get { ... } }
    public bool IsValid { return true; }
}

public class DamoClass<T> : DamoClass {
    public T SetProperty { set { ... } }
}

Then you are free to do;

if (objA is DamoClass) {
    ((DamoClass) objA).IsValid();
    object test = ((DamoClass) objA).GetProperty;
}

Indeed .NET itself uses this technique for IEnumerable and IEnumerable

One drawback with this technique is that you can’t redefine the type of a member in the subclass – maybe that’ll make C# 3.0.

[)amien