Sarah Taraporewalla's Technical Ramblings

How to Mug Tiny Types

| Comments

I love tiny types. I love how they make me feel, how they make me laugh, how easy it is to understand what is going on when they are around. The one annoying aspect, however, is when they have to cross application boundaries. Whenever you need to persist them, or present them onto the screen, in order to get to the value, you usually expose the underlying wrapped primitive. This always feels so icky reaching into them and stealing their values. But, on my current project, we up with some neat ideas as to how to rob our tiny types for their precious.

Here is how it works:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public interface IVictim<T>
{
  void MuggedBy(IRobber<T> robber);
}

public interface IRobber<T>
{
  T StealFrom(IVictim<T> victim);
  void Steal(T valuables);
}

public class Percentage : IVictim<T>
{
  private readonly decimal percentage;
  public Percentage(decimal percentage)
  {
      this.percentage = percentage;
  }

  public void MuggedBy(IRobber<decimal> robber)
  {
      robber.Steal(percentage);
  }
}

public class ValuablesRobber<T> : IRobber<T>
{
  private T stolenGoods;

  public T StealFrom(IVictim<T> victim)
  {
      victim.MuggedBy(this);
      return stolenGoods;
  }

  public void Steal(T valuables)
  {
      stolenGoods = valuables;
  }
}

public class PercentageFormatter : IFormatter
{
  public string Format(object toFormat)
  {
      if (toFormat == null) return string.Empty;
      var percentage = (Percentage)toFormat;
      var value = new ValuablesRobber<decimal>().StealFrom(percentage);
      return value.ToString("0.00") + "%";
  }
}

Comments