views:

3

answers:

0

I have a set of classes, where each class represents a diferent type of a database field. For example, a very basic subset of it would be:

public abstract class DbObject { internal DbObject() { } }

public class DbInteger : DbObject
{
    public int Data { get; set; }
    public DbInteger(int data) { this.Data = data; }
}

public class DbFloat : DbObject
{
    public float Data { get; set; }
    public DbFloat(float data) { this.Data = data; }
}

// Etc.

I support different input / output formats, so I have XxxDbReader and XxxDbWriter classes for each format. The problem appears when I want to read, write, print, etc. an object of "any" type. The method looks like:

private void Write(DbObject obj)
{
    if (obj is DbInteger)
        WriteInteger(((DbInteger)obj).Data);
    else if (obj is DbFloat)
        WriteFloat(((DbFloat)obj).Data);
    // Etc.
}

A method like the above is usually considered "evil", and this problem is supposed to be solved by adding an abstract method to the base class and implementing it on the subtypes. However, this doesn't seem like a good idea to me, since I would have to add a method for each format to the classes (no module separation) and there are a lot of version, endianness, etc. details that doesn't make sense to be anywhere but the Reader and Writer classes.

Is there any way to make this code nicer and better designed? Or is this one of the few cases where I should use that kind of code?