A value object is a design pattern in which an object is made to represent something simple, like currencies or dates. A value object should be equal to another value object if both objects have the same value despite being two different objects. In this article, I will dive into why I find value objects useful and discuss various trade-offs in designing value objects. I will be doing examples in C#, but the examples should apply to many of the other major languages out there.

Shopping for value — a shopping cart example:

Imagine that you’re in charge of developing or maintaining the code base of a simple webshop. Every item in the store has a unique ID, name, and price associated with it. In this case, an item may look like this in code:

public class Item {
  public Guid Id {get; set; }
  public string Name { get; set; }
  public decimal Price { get; set; }
}

Suddenly a new requirement emerges: shop items may have their prices quoted in multiple currencies.

Considering the time to market, and the fact that you can feel your boss breathing down your neck, you may be tempted to introduce a dictionary. This way you can look up the price for each currency. Without much hesitation and under pressure to deliver, you opt to go for a simple dictionary from string to decimal:

public class Item {
  public Guid Id {get; set; }
  public string Name { get; set; }
  public IDictionary<string, decimal> Prices {get; set; }
}

#programming #c-sharp-programming #dotnet #software-development #coding #c++

Value objects and How to Appreciate Them
1.15 GEEK