When writing code I strongly believe in making interfaces between objects (and data structures) as small as possible. This makes life easier for both you and the people consuming your code.
The distinction between data strutures and objects is something only a few think about. To be clear: A data structure only carries data. An object carries state and behavior. This little rant is about data structures.
In C# it is common to create a data structure in the following way:
public class Product {
public string Id {get;set;}
public string Name {get;set;}
public Money Price {get;set;}
}
You would typically use this data structure to represent a product in your inventory. What you are actually saying (by having public setters) is that any piece of code can change the Product Id, Name or Price at any time. If your are lucky nobody actually does this, but hey, why make it hard on yourself?
If you are creating a data structure that is meant to be immutable, then make it immutable.
public class Product {
public Product(string id, string name, Money price)
{
Id = id;
Name = name;
Price = price;
}
public string Id {get; private set;}
public string Name { get; private set; }
public Money Price { get; private set; }
}
It's not much, but it makes your code more explicit by narrowing the interface of the data structure to represent what you intended. It might even get you out of trouble once in a while.
Any thougths ? Please share.
(Note: “Data structure” might be a poor choice of word here, since the term is often used to represent something slightly different in computer science.)