Monday, June 28, 2010

C# tip - 6/28/2010

Consider using immutable types when creating objects.

If your object is only considered to be a storage place where every set of data is linked to the rest of the object, consider not only using Struct, but also making the entire object immutable (and maybe even using static factory methods to populate the object itself).

An example would be a stock information.  The stock object would have NAME and SYMBOL as its attributes.  If you change NAME, you will have to also change the SYMBOL.  For example:

Stock stock = new Stock("MSFT", "Microsoft Corporation");
stock.setSymbol("GOOG");
- now, the stock object has the SYMBOL as GOOG and NAME as Microsoft Corporation, which is obviously wrong.

The best way to implement this is:

  • create the object as a struct
  • make all private attribute be readonly
  • implement only private setters and public getters
  • consider implementing static factory methods.
  • consider implementing the Builder pattern to create these objects if you have more than a couple attributes to set
Issues arising from using immutable types are the same that are listed in the Builder Pattern tip.

No comments:

Labels