:::: MENU ::::
Posts tagged with: dtos

DTOs: To Flatten Or Not To Flatten?

that is the question…

I’m busy working on a JSON based API with client libraries in Flex, C# and Javascript (and eventually iPhone, JavaFX etc).

One of the things the API deals with is the concept of a Market. Markets have a number of properties that “belong” to them, simplistically things like MarketId and Name.

public class Market
{
    public int MarketId {get; set;}
    public string Name {get; set;}
}

However, I can see that in using a list of markets, its going to be useful to know related data about the market for things like sorting. For example, when showing a list of markets I’d like to know the volume traded in the last day so I can colour them differently. Or the price change in the last hour etc.

DTO wise, there seem to be several options.

  1. Flattening with “nulls”

    public class Market
    {
        public int MarketId {get; set;}
        public string Name {get; set;}
        public decimal? VolumeInLastDay {get; set;}
        public decimal? PriceDeltaLastHour {get; set;}
    }
    

    It seems that over time this approach will lead to very “messy” DTOs where you’re forced to do a lot of “isNull” style checking before attempting to display things.

  2. Multiple specific MarketWithXYZ DTOS

    public class MarketWithVolume: Market
    {
        public decimal VolumeInLastDay {get; set;}
    }
    
    public class MarketWithPriceDelta: Market
    {
        public decimal PriceDeltaLastHour {get; set;}
    }
    
    public class MarketWithVolumeAndPriceDelta: MarketWithVolume
    {
        public decimal? PriceDeltaLastHour {get; set;}
    }
    

    An explosion of DTOs, but at least you know exactly what data you’ve got at any instance

  3. Property Bags

    public class Market
    {
        public int MarketId {get; set;}
        public string Name {get; set;}
        public Hashtable RelatedData {get; set;}
    }
    
    decimal delta = Market.RelatedData["PriceDeltaLastHour "];
    
    

    In a way this feels even worse than having multiple null attributes; especially for someone new to the API because you won’t know until run time which data is available.

How have you approached this problem in the past? What works, and what doesn’t? Comments much appreciated.

Update

  • Reduced duplication in Multiple specific option using inheritance