Skip to content

Instantly share code, notes, and snippets.

@dtchepak
Created October 28, 2013 23:42
Show Gist options
  • Save dtchepak/7206785 to your computer and use it in GitHub Desktop.
Save dtchepak/7206785 to your computer and use it in GitHub Desktop.
public abstract class Thingoe {
public Thingoe(string id, int quantity) { ... }
public string Id { get; private set; }
public int Quantity { get; private set; }
}
public class WidgetThingoe : Thingoe {
public WidgetThingoe(string id, int quantity) : base(id,quantity) {}
}
public class OtherThingoe : Thingoe {
public OtherThingoe(string id, int quantity) : base(id,quantity) {}
}
@mausch
Copy link

mausch commented Oct 29, 2013

class Thingoe {
  public readonly string Id;
  public readonly int Quantity;
  public Thingoe(string id, int quantity) {...}
}

class WidgetThingoe {
  public readonly Thingoe Thingy;
  public WidgetThingoe(Thingoe thingy) {...}
}

class OtherThingoe {
  public readonly Thingoe Thingy;
  public OtherThingoe(Thingoe thingy) {...}
}

i.e. record types in F# .
In Haskell, you could represent WidgetThingoe and OtherThingoe as newtypes (or not).
Or maybe you were trying to model a sum type? If so, ask yourself if you need an open type (like the original Thingoe you posted) or a closed type (i.e. a discriminated union).
The best rule of thumb: make illegal states unrepresentable.

@dtchepak
Copy link
Author

@mausch,
Closed type is fine. We'd like to be able to work with ids and quantities across all thingoes, but also restrict certain operations to specific types of thingoes.

e.g. (in haskellish)

getIds :: Thingoe -> String
widgets :: [WidgetThingoe]

widgetIds :: [WidgetThingoe] -> [String]
widgetIds = map getIds

I think I'm after structural typing?

The motivation for this is porting some existing code that uses sub-typing, and I'm trying to think of alternative representations that have the same power.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment