Understanding the Flyweight pattern - c#

Intent:
The intent of this pattern is to use sharing to support a large number
of objects that have part of their internal state in common where the
other part of state can vary.
Objects can share state via static fields.
What is the difference between sharing internal state of a large number of objects using the flyweight pattern and using static fields?
Is the pool of objects that the flyweight provides via its Factory what the flyweight is really all about?

Using static fields, there can only ever be one instance of the object in use at any one point in time. Using the flyweight pattern, you can have any number of different instances in use simultaneously, (each one of which is used multiple times). The canonical example of the flyweight pattern is for a text editor, where you need an object instantiated for each and every character in the document. Instead of having one object in memory for each character in a 10,000 word document, you then only need 26 objects, (assuming document only uses lower case letters), one for the letter 'a', one for the letter 'b', etc., and they are reused, transiently, over and over again throughout the document, each time you need to perform some function or action requiring an 'a' object.
EDIT: to answer question from first comment below:
So, since you need 26 different objects, making a Letter class that was a static, or a singleton, wouldn't work. If it was a static, you can't make any instances, and so whatever the static values would have to be appropriate for every place in the code where you made use of it.
If it was a singleton, then of course you only have one object. Every property would have to be adjustable (and adjusted) every time you used it.
To use this pattern for the letters in the alphabet, you have to have 26 different classes, one for each letter...
Also, the "part of the class that can vary" really means that some fields represent state that is different for every instance of the class. Whereas the part that is in common means that the values of those common fields are in common for all uses of the object matching those state values (all the 'a's for example), not for every instance of the class.
Again, using the text editor as an example.
Every place in your code that you need to deal with a character that is an 'a', you would first, go to the data structure that stores your 26 instances of character objects, and fetch the 'a' instance,
You would first modify/change the varying properties (the properties not tied to it's nature as an 'a', but perhaps to it's font size, position, color, etc.) to match the needs for this specific character 'a' in the document.
Then you would utilize the object to do whatever it is you need to do with it, and then return it to the storage structure for reuse the next time your code needs an 'a'.

The Flyweight pattern is used to avoid the overhead of large numbers of very similar classes. There are cases in programming where it seems that you need to generate a very large number of small class instances to represent data. Sometimes you can greatly reduce the number of different classes that you need to instantiate if you can recognize that the instances are fundamentally the same except for a few parameters. If you can move those variables outside the class instance and pass them in as part of a method call, the number of separate instances can be greatly reduced by sharing them.
In this context, it's important to bear in mind that the Flyweight was invented in an era where C# was nothing more than a rough sketch on some power point charts. And the maturation of the language was informed by some of these patterns implicitly. C# includes class members...
It is more typical to declare a non-static class with some static
members, than to declare an entire class as static. Two common uses of
static fields are to keep a count of the number of objects that have
been instantiated, or to store a value that must be shared among all
instances.
Source C# statics on MSDN
Taking things further, WPF technology popularized shared resources, and the result is often declarative code only.
So if your language of choice is C#, you may be advised to consider the Flyweight pattern against inherent properties that already exist in the language.

While patterns and their implementations are a bit subjective, using statics is a valid - albeit simplest possible - way to achieve Flyweight.
If you can use statics, that's great. Otherwise you can do something like you've touched on ... your factory that constructs flyweight objects can assign/reference the proper shared object.

Here is some example, it print all of the soldiers and their medals.
Because not all of the soldiers are decorated we are using the flyweight design pattern.
public class Soldiers
{
private string[] _soldiers;
private Dictionary<int, Medal> _medals = new Dictionary<int, Medal>();
public Soldiers(string[] soldier)
{
this._soldiers = soldier;
}
public Medal this[int index]
{
get
{
Medal medal = new Medal();
this._medals.Add(index, medal);
return this._medals[index];
}
}
public override string ToString()
{
var soldierList = new List<string>();
for (var i = 0; i < this._soldiers.Length; i++)
{
string soldier = this._soldiers[i];
if (this._medals.ContainsKey(i))
soldier = soldier + ", Medal: " + this._medals.ElementAt(i).ToString();
soldierList.Add(soldier);
}
return string.Join("; ", soldierList);
}
public class Medal
{
public bool Bronze;
public bool Silver;
public bool Gold;
public override string ToString()
{
return (this.Bronze ? "Bronze," : "") + (this.Silver ? "Silver," : "") + (this.Gold ? "Gold" : "")
}
}
}
Usage:
Soldiers soldiers = new Soldiers(new string[] { "SoldierA" , "SoldierB" , "SoldierC" });
soldiers[0].Gold = true;
soldiers[0].Silver = true;
soldiers[2].Bronze = true;
Console.Write(soldiers.ToString()) // "SoldierA, Medal: Silver,Gold; SoldierB; SoldierC, Medal: Bronze";

Related

Should a constructor parse input?

Often, I find that I must instantiate a bunch of objects, but I find it easier to supply the parameters for this instantiation as a human-readable text file, which I manually compose and feed into the program as input.
For instance, if the object is a Car then the file might be a bunch of rows, each containing the name, speed and color (the three mandatory constructor parameters) delimited with tabs:
My car 65 Red
Arthur's car 132 Pink
Old junk car 23 Rust brown
This is easy for me to inspect visually, modify or generate by another program. The program can then load the file, take each row, parse out the relevant parameters, feed them into a Car(string name, int speed, uint color) constructor and create the object.
Notice how there is some work that must be done on the input before it is compatible with the constructor: The speed must be converted from string to int with a call to int.Parse. The color must be matched to a RGB value by looking up the English color name (perhaps the program would access Wikipedia to figure out each color's value, or consults a predefined map of name -> RGB somewhere).
My question is, from an OOP standpoint, who should do this parsing? The constructor, or the method calling the constructor?
With the first option, the advantage is simplicity. The calling function must only do:
foreach(var row in input_file)
list_of_objects_that_i_am_populating.Add(new Car(row));
And all the ugly parsing can be nicely contained in the constructor, which doesn't have much other code anyhow, so the parsing code can be easily read and modified without being distracted by non-parsing code.
The disadvantage is that code reuse goes out the window because now my object is joined at the hip to an input format (worse, because the input format is ad-hoc and manually composed, it is ephemeral and potentially not guaranteed to stay the same). If I reuse this object in another program, where I decide that it is convenient to slightly change the formatting of the input file, the two versions of the object definition are now divergent. I often find myself defining input formats in the comment section of the constructor, which seems a bit code-smelly.
Another disadvantage is that I have lost the ability to do batch operations. Recall the earlier example problem of mapping color names to values: What if I was using a web service that takes 1 minute to process every individual request, regardless of whether that request is asking to convert one color name or a million. With a very large input file, I would drastically slow down my application by accessing the service once for each row, instead of submitting one big request for all rows, and then instantiating the objects according to the reply.
What is the "correct" way to handle a situation like this? Should I parse input the constructor and treat the problems above as exceptional issues that must be dealt with on a case-by-case basis? Should I let my calling method do the parsing (even though it may already be bloated with much convoluted program logic)?
My question is, from an OOP standpoint, who should do this parsing? The constructor, or the method calling the constructor?
In general, you should avoid doing this within the constructor. That would be a violation of the Single Responsibility Principle. Each type should only be responsible for the operations required within that type, and nothing else.
Ideally, a separate class would be responsible for parsing the data into its proper form (and nothing else). The method creating your instance would take that (parsed) data and create your types.
I would create and use factory methods to load via a settings file, or csv. I would NOT put such code in the constructor itself.
Factory version 1:
public class Car
{
... your existing methods and data ...
public static Car CreateFromCsv(string csv ) { .... }
public static Car CreateFromFile(string fileName) { ...}
}
Or use a dedicated Factory:
public static class CarFactory
{
public static Car CreateFromCsv(string csv ) { .... }
public static Car CreateFromFile(string fileName) { ...}
}
Or a dedicated business logic class:
namespace BusinessLogic;
public class LoadCars
{
public Car ExecuteForCsv(string csv) { ...}
public Car ExecuteForFile(string fileName) { ... }
}
I think it's generally better practice to make your FileParser separate from your Car class. I would personally parse the file and return a List<string[]> or something to that effect then make an overload of the Car constructor, like this:
Car(string[] values)
{
// do error handling here like
if (values.Length != 2)
// error
if (int.TryParse(values[1], out tempVar))
// set int param, if not then throw error
}
So I would have one class that parses the file into its tokens (as strings) and does basic error handling (like checking the file exists and that the record count is what you'd expect etc.). Then do more specific input validation in the car constructor since that will apply to other input sources as well (say the user enters their input at the cmd line, you could still use that constructor effectively).
In general, avoid putting code in constructors which may throw an exception or simply fail to construct a properly formed object. And as you note in your question, your current implementation has tightly coupled your objects to a file format which is usually better delegated to a class or factory method.

Efficient way to pass large number of argments into a constructor

I am working on a project and I have an object, upon instantiation of which, will have a large number of values (20+) passed into it. I know I could make a constructor that would take in all of the values, but I am looking for a cleaner / more efficient way to do this.
Just to put this in perspective, the object is a character in a game, new instances of which are frequently created. The values assigned are attributes which are randomly generated.
Is a constructor with a large number of arguments the best way to go? Or is there a better way to do this that I don't know about? Any advice would be greatly appreciated.
EDIT: When a new game starts, a List<Character> is created and a for loop creates 10 instances of character and adds them to the list.
You can create a call that defines your game character. have users populate that class and pass it as the argument to your class.
something like this,
public class CharecterInfo
{
public string Name {get;set;}
public int Power {get;set;}
public int Health{get;set;}
}
public class Charecter
{
public Charecter(CharecterInfo charecterInfo)
{
//import values
}
}
I would avoid using public properties, since your class could be used while it's not properly initialized (in a bad state) which is the job of the constructor. you should use a constructor and validate the input before allowing the user to continue.
If the properties have public setters, you can use the object initialization syntax, e.g.:
Character c = new FooCharacter() {
Name = "Ugly Monster",
HP = 10000,
....,
};
Edit: as pointed out in the comments, this assumes that your constructor (empty or with minimal parameters) will initialize all required properties with valid data. The initialization syntax is just syntactic sugar that sets any specified properties after the constructor has initialized the object.
This completely depends on what those arguments are... But generally, it's not a great idea to have huge parameter lists. This is because of the confusion it creates over which parameter is what. An exception to this would be where you have a variable-length argument list that takes key/value pairs, allowing you to pass your data in an undefined order.
One alternative is to make another class that represents all your arguments. You could just create an instance of this, set the relevant fields and pass that in. To extend the idea, you might break that class up into a few classes and then provide a handful of constructors that take different combinations of those.
The useful thing with this approach is that you can have a default value for any of the arguments. Normally, if you want to specify a value for something further down the argument list but use defaults for the rest, you have to fill in all the default values in between. With this approach you can use all defaults except for the values you want to specify.
You have several options:
If all of the values are required:
Stick with the large list of parameters
Create a new class which has all of these items as properties
If not all of the values are required and you can use the Builder-pattern:
This link describes the pattern in detail: http://cdmckay.org/blog/2009/07/03/joshua-blochs-builder-pattern-in-csharp/
You can make a method that returns a class instance. Perhaps even in that class itself.
Something like:
public class Character
{
public string Name;
public int Level;
static Random random = new Random();
public static Character CreateNew()
{
Character newOne = new Character();
newOne.Level = random.Next(1, 5);
newOne.Name = (random.Next(1, 2) == 1) ? "Me" : "You";
return newOne;
}
}
One possibility lies in OOAD itself. Character attributes sound like a big enough concern to be the responsibility of a distinct class with which your character class collaborates.
A quick CRC analysis of your domain may help identify one or more newly distinguished responsibilities & corresponding types that are missing presently.

How best design a scalable class?

what I mean by that is:
I basically have a class that has too many properties and functions now. To remain performant and understandable, it needs to shrink somehow. But I still need all those properties and methods somewhere.
It's like this right now:
class Apple
float seedCount;
...
...about 25 variables and properties here.
void Update() <-- a huge method that checks for each property and updates if so
In most cases the class needs almost none of those properties. In some cases in needs to be able to grow very selectively and gain a feature or lose a feature.
The only solution I have come up with, is that I create a bunch of classes and place some properties in there. I only initialize this classes object when one of those properties is needed, otherwise it remains null.
class Apple
Seed seed;
Many problems because of that:
I constantly have to check for every single object and feature each frame. If the seed is not initialized I don't have to calculate anything for it. If it is, I have to.
If I decided to put more than 1 property/feature into the Seed class, I need to check every single one of those aswell.
It just gets more and more complicated. The problem I have is therefore, that I need granular control over all the features and can't split them intelligently into larger subclasses. Any form of subclass would just contain a bunch of properties that need to be checked and updated if wanted.
I can't exactly create subclasses of Apple, because of the need for such high granular control. It would be madness to create as many classes as there are combinations of properties.
My main goal: I want short code.
It would be madness to create as many classes as there are combinations of properties.
Sounds like you might be looking for the Decorator Pattern. It's purpose is to make it easier to manage objects that can have many different combinations of properties without an exponentially growing heirarchy. You just have one small subclass for each property or behavior (not necessarily one C# property, just something you can group together) and then you can compose them together at runtime.
In your case, each Apple decorator class will override your Update method, and make the calculations necessary for its parts, and then call base.Update to pass it to the next in line.
Your final answer will heavily depend on exactly what your "Apple" really is.
After reviewing your comments and samples in my other answer, I've thought about the Decorator pattern and how it was being used vs how you want things to work. I've come to the conclusion that Decorator is not right for this purpose. I'm thinking Strategy instead. I have modified the previous sample code for you to take a look at.
I've gotten rid of the decorators altogether. The Broodfather abstract class remains. It has two additional properties an IBroodfatherMagicAbility and an IBroodfatherBloodthirstAbility. This two properties will allow you to access the different attributes that pertain to those abilities, however the key to this all is that the strategy for implementing the abilities can change at runtime (see Strategy pattern).
There are two classes each that implement a "strategy" for both bloodthrist and magic.
IBroodfatherBloodthirstAbility.cs - this is the interface that all "bloodthirst strategies" must implement.
BroodfatherNonBloodThristy.cs - class that implements the attributes for non-bloodthirsty.
BroodfatherBloodThristy.cs - class that implements the attributes for bloodthirsty.
IBroodfatherMagicAbility.cs - this is the interface that all "magical strategies" must implement.
BroodfatherNonMagical.cs - class that implements a strategy for non-magical.
BroodfatherMagical.cs - class that implements a strategy for magical.
BasicBroodfather.cs - this is similar to the previous example, except that now when an instance is created the magic and bloodthrist properties get set to new instances of the non-magical and non-bloodthristy strategy objects.
Program.cs is the driver that shows the classes and how the different strategies can get swapped in and out at runtime.
I think you'll find that more suited to how you wanted things to work.
you may use a nested class in Apple class
http://msdn.microsoft.com/en-us/library/ms173120(VS.80).aspx
I think the key thing here is that you are trying to hold everything in one class. Because of that, the class must be constantly checking what it has and what it doesn't. The solution is to create subclasses or decorators that already know whether or not they have a particular thing. Then they don't have to be checking it each time.
Because you have so many properties which may be combined in different ways, it sounds like the decorator solution is more up your alley.
I think you're in the right path: composition. You compose your class with the other classes that are needed. But you also need to delegate responsibility accordingly. In your example, it's the Seed class that should be responsible for checking it's internal state, and Apple just delegates to it.
As for the optional features problem, maybe you can use null objects instead of null references. This way, you don't need to check for null everytime, and the code is more consistent.
I've been pondering this question for a bit and I've come up with an alternate solution. This may be a bit unorthodox and anti-object oriented, but if you're not faint of heart read on...
Building upon the Apple example: the Apple class can contain many properties, these properties which could be categorized into related groups. For the example I rolled with an Apple class with some properties related to the apple's seeds and others related to the apple's skin.
Apple
a. Seed
a1. GetSeedCount
a2. ...
b. Skin
b1. GetSkinColor
b2. ...
I'm using a dictionary object to store all the apples properties.
I wrote extension methods to define accessors to the properties, using different classes to keep them separate and organized.
By using a dictionary for the properties, you can iterate through all properties stored thusfar at any point (if you have to check all of them, as it sounded like you needed in your update method). Unfortunately you lose strong typing of the data (at least in my sample I did because I'm using a Dictionary< string, string>. You could have separate dictionaries for every type needed, but that would require more plumbing code to route the property access to the correct dictionary.
Using extension methods to define accessors to the properties allows you to separate the code for each logical categories of properties. This keeps things organized into separate chunks of related logic.
Here is a sample I came up with to test how this would work, given with the standard warning that if you were to continue down this path robustification would be in order (validation, error handling, etc.).
Apple.cs
namespace ConsoleApplication1
{
using System.Collections.Generic;
using System.Text;
public class Apple
{
// Define the set of valid properties for all apple objects.
private static HashSet<string> AllowedProperties = new HashSet<string>(
new string [] {
"Color",
"SeedCount"
});
// The main store for all properties
private Dictionary<string, string> Properties = new Dictionary<string, string>();
// Indexer for accessing properties
// Access via the indexer should be restricted to the extension methods!
// Unfortunately can't enforce this by making it private because then extension methods wouldn't be able to use it as they are now.
public string this[string prop]
{
get
{
if (!AllowedProperties.Contains(prop))
{
// throw exception
}
if (Properties.ContainsKey(prop))
{
return this.Properties[prop];
}
else
{
// TODO throw 'property unitialized' exeception || lookup & return default value for this property || etc.
// this return is here just to make the sample runable
return "0";
}
}
set
{
if (!AllowedProperties.Contains(prop))
{
// TODO throw 'invalid property' exception
// these assignments are here just to make the sample runable
prop = "INVALID";
value = "0";
}
this.Properties[prop] = value.ToString();
}
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
foreach (var kv in this.Properties)
{
sb.AppendFormat("{0}={1}\n", kv.Key, kv.Value);
}
return sb.ToString();
}
}
}
AppleExtensions.cs
namespace AppleExtensionMethods
{
using System;
using ConsoleApplication1;
// Accessors for Seed Properties
public static class Seed
{
public static float GetSeedCount(this Apple apple)
{
return Convert.ToSingle(apple["SeedCount"]);
}
public static void SetSeedCount(this Apple apple, string count)
{
apple["SeedCount"] = count;
}
}
// Accessors for Skin Properties
public static class Skin
{
public static string GetSkinColor(this Apple apple)
{
return apple["Color"];
}
public static void SetSkinColor(this Apple apple, string color)
{
apple["Color"] = ValidSkinColorOrDefault(apple, color);
}
private static string ValidSkinColorOrDefault(this Apple apple, string color)
{
switch (color.ToLower())
{
case "red":
return color;
case "green":
return color;
default:
return "rotten brown";
}
}
}
}
Here is a test drive:
Program.cs
namespace ConsoleApplication1
{
using System;
using AppleExtensionMethods;
class Program
{
static void Main(string[] args)
{
Apple apple = new Apple();
apple.SetSkinColor("Red");
apple.SetSeedCount("8");
Console.WriteLine("My apple is {0} and has {1} seed(s)\r\n", apple.GetSkinColor(), apple.GetSeedCount());
apple.SetSkinColor("green");
apple.SetSeedCount("4");
Console.WriteLine("Now my apple is {0} and has {1} seed(s)\r\n", apple.GetSkinColor(), apple.GetSeedCount());
apple.SetSkinColor("blue");
apple.SetSeedCount("0");
Console.WriteLine("Now my apple is {0} and has {1} seed(s)\r\n", apple.GetSkinColor(), apple.GetSeedCount());
apple.SetSkinColor("yellow");
apple.SetSeedCount("15");
Console.WriteLine(apple.ToString());
// Unfortunatly there is nothing stopping users of the class from doing something like that shown below.
// This would be bad because it bypasses any behavior that you have defined in the get/set functions defined
// as extension methods.
// One thing in your favor here is it is inconvenient for user of the class to find the valid property names as
// they'd have to go look at the apple class. It's much easier (from a lazy programmer standpoint) to use the
// extension methods as they show up in intellisense :) However, relying on lazy programming does not a contract make.
// There would have to be an agreed upon contract at the user of the class level that states,
// "I will never use the indexer and always use the extension methods!"
apple["Color"] = "don't panic";
apple["SeedCount"] = "on second thought...";
Console.WriteLine(apple.ToString());
}
}
}
Addressing your comment from 7/11 (the date, not the store) :)
In the sample code you provided, there is a comment that states:
"As you can see, I can't call
BasicBroodmother methods on "monster"
You realize you could do something like this at that point:
BasicBroodmother bm = monster as BasicBroodmother;
if (bm != null)
{
bm.Eat();
}
There isn't much meat to your code, (I understand it was just an example), but when I look at it I get the feeling that you should be able to improve the design. My immediate thought was having an abstract class for broodmother which would contain default implementations of any attributes/actions that are common to all broodmothers. Then specialized broodmothers, like the magical broodmother, would contain any specialized attributes/actions specific to the magical broodmother, but also inherit from the abstract class and if necessary override the nessecary base attributes/actions.
I would take a look at the Strategy pattern for the design of the actions so that the actions (i.e. behaviours like eat, spawn, attack) can be swappable based the type of monster.
[edit 7/13]
Don't have time to go into details right now (need sleep), but I put together some sample code showing a different approach.
The code consists of:
Broodfather.cs - abstract class filled with all things common to different Broodfathers "types."
BasicBroodFather.cs - concrete class that inherits from Broodfather.
BroodfatherDecorator.cs - abstract class to be inherited by all Broodfather decorators.
MagicalBroodfather.cs - this class decorates/wraps a Broodfather with "magic"
BloodthirstyBroodfather.cs - this class decorates/wraps a Broodfather with "bloodthirst"
program.cs - demonstrates two examples: The first starts with a basic broodfather that gets wrapped by magic then by bloodthirst. The second starts with a basic broodfather and wraps it in the other order bloodthirst, then magic.
Maybe your methods are not were they are supposed to be?
If you separated the Seed class from the Apple class, why don't you move the methods that use the Seed information to the Seed class too?
If those methods need information on other Apple properties, you can pass it as a parameter.
By doing this, I guess you can eliminate the initialization checks...
This is a great book about how to solve this kind of problem:
Refactoring
My main goal: I want short code.
Options:
Rewrite all functions as static and create a class for each one.
Rewrite your codebase in Perl.
Remove all comments.

C#: Abstract Strategy base class serving as Abstract Factory for Strategy objects

I am trying to create a web-based tool for my company that, in essence, uses geographic input to produce tabular results. Currently, three different business areas use my tool and receive three different kinds of output. Luckily, all of the outputs are based on the same idea of Master Table - Child Table, and they even share a common Master Table.
Unfortunately, in each case the related rows of the Child Table contain vastly different data. Because this is the only point of contention I extracted a FetchChildData method into a separate class called DetailFinder. As a result, my code looks like this:
DetailFinder DetailHandler;
if (ReportType == "Planning")
DetailHandler = new PlanningFinder();
else if (ReportType == "Operations")
DetailHandler = new OperationsFinder();
else if (ReportType == "Maintenance")
DetailHandler = new MaintenanceFinder();
DataTable ChildTable = DetailHandler.FetchChildData(Master);
Where PlanningFinder, OperationsFinder, and MaintenanceFinder are all subclasses of DetailFinder.
I have just been asked to add support for another business area and would hate to continue this if block trend. What I would prefer is to have a parse method that would look like this:
DetailFinder DetailHandler = DetailFinder.Parse(ReportType);
However, I am at a loss as to how to have DetailFinder know what subclass handles each string, or even what subclasses exist without just shifting the if block to the Parse method. Is there a way for subclasses to register themselves with the abstract DetailFinder?
You could use an IoC container, many of them allows you to register multiple services with different names or policies.
For instance, with a hypothetical IoC container you could do this:
IoC.Register<DetailHandler, PlanningFinder>("Planning");
IoC.Register<DetailHandler, OperationsFinder>("Operations");
...
and then:
DetailHandler handler = IoC.Resolve<DetailHandler>("Planning");
some variations on this theme.
You can look at the following IoC implementations:
AutoFac
Unity
Castle Windsor
You might want to use a map of types to creational methods:
public class DetailFinder
{
private static Dictionary<string,Func<DetailFinder>> Creators;
static DetailFinder()
{
Creators = new Dictionary<string,Func<DetailFinder>>();
Creators.Add( "Planning", CreatePlanningFinder );
Creators.Add( "Operations", CreateOperationsFinder );
...
}
public static DetailFinder Create( string type )
{
return Creators[type].Invoke();
}
private static DetailFinder CreatePlanningFinder()
{
return new PlanningFinder();
}
private static DetailFinder CreateOperationsFinder()
{
return new OperationsFinder();
}
...
}
Used as:
DetailFinder detailHandler = DetailFinder.Create( ReportType );
I'm not sure this is much better than your if statement, but it does make it trivially easy to both read and extend. Simply add a creational method and an entry in the Creators map.
Another alternative would be to store a map of report types and finder types, then use Activator.CreateInstance on the type if you are always simply going to invoke the constructor. The factory method detail above would probably be more appropriate if there were more complexity in the creation of the object.
public class DetailFinder
{
private static Dictionary<string,Type> Creators;
static DetailFinder()
{
Creators = new Dictionary<string,Type>();
Creators.Add( "Planning", typeof(PlanningFinder) );
...
}
public static DetailFinder Create( string type )
{
Type t = Creators[type];
return Activator.CreateInstance(t) as DetailFinder;
}
}
As long as the big if block or switch statement or whatever it is appears in only one place, it isn't bad for maintainability, so don't worry about it for that reason.
However, when it comes to extensibility, things are different. If you truly want new DetailFinders to be able to register themselves, you may want to take a look at the Managed Extensibility Framework which essentially allows you to drop new assemblies into an 'add-ins' folder or similar, and the core application will then automatically pick up the new DetailFinders.
However, I'm not sure that this is the amount of extensibility you really need.
To avoid an ever growing if..else block you could switch it round so the individal finders register which type they handle with the factory class.
The factory class on initialisation will need to discover all the possible finders and store them in a hashmap (dictionary). This could be done by reflection and/or using the managed extensibility framework as Mark Seemann suggests.
However - be wary of making this overly complex. Prefer to do the simplest thing that could possibly work now with a view to refectoring when you need it. Don't go and build a complex self-configuring framework if you'll only ever need one more finder type ;)
You can use the reflection.
There is a sample code for Parse method of DetailFinder (remember to add error checking to that code):
public DetailFinder Parse(ReportType reportType)
{
string detailFinderClassName = GetDetailFinderClassNameByReportType(reportType);
return Activator.CreateInstance(Type.GetType(detailFinderClassName)) as DetailFinder;
}
Method GetDetailFinderClassNameByReportType can get a class name from a database, from a configuration file etc.
I think information about "Plugin" pattern will be useful in your case: P of EAA: Plugin
Like Mark said, a big if/switch block isn't bad since it will all be in one place (all of computer science is basically about getting similarity in some kind of space).
That said, I would probably just use polymorphism (thus making the type system work for me). Have each report implement a FindDetails method (I'd have them inherit from a Report abstract class) since you're going to end with several kinds of detail finders anyway. This also simulates pattern matching and algebraic datatypes from functional languages.

Immutable object pattern in C# - what do you think? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have over the course of a few projects developed a pattern for creating immutable (readonly) objects and immutable object graphs. Immutable objects carry the benefit of being 100% thread safe and can therefore be reused across threads. In my work I very often use this pattern in Web applications for configuration settings and other objects that I load and cache in memory. Cached objects should always be immutable as you want to guarantee they are not unexpectedly changed.
Now, you can of course easily design immutable objects as in the following example:
public class SampleElement
{
private Guid id;
private string name;
public SampleElement(Guid id, string name)
{
this.id = id;
this.name = name;
}
public Guid Id
{
get { return id; }
}
public string Name
{
get { return name; }
}
}
This is fine for simple classes - but for more complex classes I do not fancy the concept of passing all values through a constructor. Having setters on the properties is more desirable and your code constructing a new object gets easier to read.
So how do you create immutable objects with setters?
Well, in my pattern objects start out as being fully mutable until you freeze them with a single method call. Once an object is frozen it will stay immutable forever - it cannot be turned into a mutable object again. If you need a mutable version of the object, you simply clone it.
Ok, now on to some code. I have in the following code snippets tried to boil the pattern down to its simplest form. The IElement is the base interface that all immutable objects must ultimately implement.
public interface IElement : ICloneable
{
bool IsReadOnly { get; }
void MakeReadOnly();
}
The Element class is the default implementation of the IElement interface:
public abstract class Element : IElement
{
private bool immutable;
public bool IsReadOnly
{
get { return immutable; }
}
public virtual void MakeReadOnly()
{
immutable = true;
}
protected virtual void FailIfImmutable()
{
if (immutable) throw new ImmutableElementException(this);
}
...
}
Let's refactor the SampleElement class above to implement the immutable object pattern:
public class SampleElement : Element
{
private Guid id;
private string name;
public SampleElement() {}
public Guid Id
{
get
{
return id;
}
set
{
FailIfImmutable();
id = value;
}
}
public string Name
{
get
{
return name;
}
set
{
FailIfImmutable();
name = value;
}
}
}
You can now change the Id property and the Name property as long as the object has not been marked as immutable by calling the MakeReadOnly() method. Once it is immutable, calling a setter will yield an ImmutableElementException.
Final note:
The full pattern is more complex than the code snippets shown here. It also contains support for collections of immutable objects and complete object graphs of immutable object graphs. The full pattern enables you to turn an entire object graph immutable by calling the MakeReadOnly() method on the outermost object. Once you start creating larger object models using this pattern the risk of leaky objects increases. A leaky object is an object that fails to call the FailIfImmutable() method before making a change to the object. To test for leaks I have also developed a generic leak detector class for use in unit tests. It uses reflection to test if all properties and methods throw the ImmutableElementException in the immutable state.
In other words TDD is used here.
I have grown to like this pattern a lot and find great benefits in it. So what I would like to know is if any of you are using similar patterns? If yes, do you know of any good resources that document it? I am essentially looking for potential improvements and for any standards that might already exist on this topic.
For info, the second approach is called "popsicle immutability".
Eric Lippert has a series of blog entries on immutability starting here. I'm still getting to grips with the CTP (C# 4.0), but it looks interesting what optional / named parameters (to the .ctor) might do here (when mapped to readonly fields)...
[update: I've blogged on this here]
For info, I probably wouldn't make those methods virtual - we probably don't want subclasses being able to make it non-freezable. If you want them to be able to add extra code, I'd suggest something like:
[public|protected] void Freeze()
{
if(!frozen)
{
frozen = true;
OnFrozen();
}
}
protected virtual void OnFrozen() {} // subclass can add code here.
Also - AOP (such as PostSharp) might be a viable option for adding all those ThrowIfFrozen() checks.
(apologies if I have changed terminology / method names - SO doesn't keep the original post visible when composing replies)
Another option would be to create some kind of Builder class.
For an example, in Java (and C# and many other languages) String is immutable. If you want to do multiple operations to create a String you use a StringBuilder. This is mutable, and then once you're done you have it return to you the final String object. From then on it's immutable.
You could do something similar for your other classes. You have your immutable Element, and then an ElementBuilder. All the builder would do is store the options you set, then when you finalize it it constructs and returns the immutable Element.
It's a little more code, but I think it's cleaner than having setters on a class that's supposed to be immutable.
After my initial discomfort about the fact that I had to create a new System.Drawing.Point on each modification, I've wholly embraced the concept some years ago. In fact, I now create every field as readonly by default and only change it to be mutable if there's a compelling reason – which there is surprisingly rarely.
I don't care very much about cross-threading issues, though (I rarely use code where this is relevant). I just find it much, much better because of the semantic expressiveness. Immutability is the very epitome of an interface which is hard to use incorrectly.
You are still dealing with state, and thus can still be bitten if your objects are parallelized before being made immutable.
A more functional way might be to return a new instance of the object with each setter. Or create a mutable object and pass that in to the constructor.
The (relatively) new Software Design paradigm called Domain Driven design, makes the distinction between entity objects and value objects.
Entity Objects are defined as anything that has to map to a key-driven object in a persistent data store, like an employee, or a client, or an invoice, etc... where changing the properties of the object implies that you need to save the change to a data store somewhere, and the existence of multiple instances of a class with the same "key" imnplies a need to synchronize them, or coordinate their persistence to the data store so that one instance' changes do not overwrite the others. Changing the properties of an entity object implies you are changing something about the object - not changing WHICH object you are referencing...
Value objects otoh, are objects that can be considered immutable, whose utility is defined strictly by their property values, and for which multiple instances, do not need to be coordinated in any way... like addresses, or telephone numbers, or the wheels on a car, or the letters in a document... these things are totally defined by their properties... an uppercase 'A' object in an text editor can be interchanged transparently with any other uppercase 'A' object throughout the document, you don't need a key to distinguish it from all the other 'A's In this sense it is immutable, because if you change it to a 'B' (just like changing the phone number string in a phone number object, you are not changing the data associated with some mutable entity, you are switching from one value to another... just as when you change the value of a string...
Expanding on the point by #Cory Foy and #Charles Bretana where there is a difference between entities and values. Whereas value-objects should always be immutable, I really don't think that an object should be able to freeze themselves, or allow themselves to be frozen arbitrarily in the codebase. It has a really bad smell to it, and I worry that it could get hard to track down where exactly an object was frozen, and why it was frozen, and the fact that between calls to an object it could change state from thawed to frozen.
That isn't to say that sometimes you want to give a (mutable) entity to something and ensure it isn't going to be changed.
So, instead of freezing the object itself, another possibility is to copy the semantics of ReadOnlyCollection< T >
List<int> list = new List<int> { 1, 2, 3};
ReadOnlyCollection<int> readOnlyList = list.AsReadOnly();
Your object can take a part as mutable when it needs it, and then be immutable when you desire it to be.
Note that ReadOnlyCollection< T > also implements ICollection< T > which has an Add( T item) method in the interface. However there is also bool IsReadOnly { get; } defined in the interface so that consumers can check before calling a method that will throw an exception.
The difference is that you can't just set IsReadOnly to false. A collection either is or isn't read only, and that never changes for the lifetime of the collection.
It would be nice at time to have the const-correctness that C++ gives you at compile time, but that starts to have it's own set of problems and I'm glad C# doesn't go there.
ICloneable - I thought I'd just refer back to the following:
Do not implement ICloneable
Do not use ICloneable in public APIs
Brad Abrams - Design Guidelines, Managed code and the .NET Framework
System.String is a good example of a immutable class with setters and mutating methods, only that each mutating method returns a new instance.
This is an important problem, and I've love to see more direct framework/language support to solve it. The solution you have requires a lot of boilerplate. It might be simple to automate some of the boilerplate by using code generation.
You'd generate a partial class that contains all the freezable properties. It would be fairly simple to make a reusable T4 template for this.
The template would take this for input:
namespace
class name
list of property name/type tuples
And would output a C# file, containing:
namespace declaration
partial class
each of the properties, with the corresponding types, a backing field, a getter, and a setter which invokes the FailIfFrozen method
AOP tags on freezable properties could also work, but it would require more dependencies, whereas T4 is built into newer versions of Visual Studio.
Another scenario which is very much like this is the INotifyPropertyChanged interface. Solutions for that problem are likely to be applicable to this problem.
My problem with this pattern is that you're not imposing any compile-time restraints upon immutability. The coder is responsible for making sure an object is set to immutable before for example adding it to a cache or another non-thread-safe structure.
That's why I would extend this coding pattern with a compile-time restraint in the form of a generic class, like this:
public class Immutable<T> where T : IElement
{
private T value;
public Immutable(T mutable)
{
this.value = (T) mutable.Clone();
this.value.MakeReadOnly();
}
public T Value
{
get
{
return this.value;
}
}
public static implicit operator Immutable<T>(T mutable)
{
return new Immutable<T>(mutable);
}
public static implicit operator T(Immutable<T> immutable)
{
return immutable.value;
}
}
Here's a sample how you would use this:
// All elements of this list are guaranteed to be immutable
List<Immutable<SampleElement>> elements =
new List<Immutable<SampleElement>>();
for (int i = 1; i < 10; i++)
{
SampleElement newElement = new SampleElement();
newElement.Id = Guid.NewGuid();
newElement.Name = "Sample" + i.ToString();
// The compiler will automatically convert to Immutable<SampleElement> for you
// because of the implicit conversion operator
elements.Add(newElement);
}
foreach (SampleElement element in elements)
Console.Out.WriteLine(element.Name);
elements[3].Value.Id = Guid.NewGuid(); // This will throw an ImmutableElementException
Just a tip to simplify the element properties: Use automatic properties with private set and avoid explicitly declaring the data field. e.g.
public class SampleElement {
public SampleElement(Guid id, string name) {
Id = id;
Name = name;
}
public Guid Id {
get; private set;
}
public string Name {
get; private set;
}
}
Here is a new video on Channel 9 where Anders Hejlsberg from 36:30 in the interview starts talking about immutability in C#. He gives a very good use case for popsicle immutability and explains how this is something you are currently required to implement yourself. It was music to my ears hearing him say it is worth thinking about better support for creating immutable object graphs in future versions of C#
Expert to Expert: Anders Hejlsberg - The Future of C#
Two other options for your particular problem that haven't been discussed:
Build your own deserializer, one that can call a private property setter. While the effort in building the deserializer at the beginning will be much more, it makes things cleaner. The compiler will keep you from even attempting to call the setters and the code in your classes will be easier to read.
Put a constructor in each class that takes an XElement (or some other flavor of XML object model) and populates itself from it. Obviously as the number of classes increases, this quickly becomes less desirable as a solution.
How about having an abstract class ThingBase, with subclasses MutableThing and ImmutableThing? ThingBase would contain all the data in a protected structure, providing public read-only properties for the fields and protected read-only property for its structure. It would also provide an overridable AsImmutable method which would return an ImmutableThing.
MutableThing would shadow the properties with read/write properties, and provide both a default constructor and a constructor that accepts a ThingBase.
Immutable thing would be a sealed class that overrides AsImmutable to simply return itself. It would also provide a constructor that accepts a ThingBase.
I dont like the idea of being able to change an object from a mutable to an immutable state, that kind of seems to defeat the point of design to me. When are you needing to do that? Only objects which represent VALUES should be immutable
You can use optional named arguments together with nullables to make an immutable setter with very little boilerplate. If you really do want to set a property to null then you may have some more troubles.
class Foo{
...
public Foo
Set
( double? majorBar=null
, double? minorBar=null
, int? cats=null
, double? dogs=null)
{
return new Foo
( majorBar ?? MajorBar
, minorBar ?? MinorBar
, cats ?? Cats
, dogs ?? Dogs);
}
public Foo
( double R
, double r
, int l
, double e
)
{
....
}
}
You would use it like so
var f = new Foo(10,20,30,40);
var g = f.Set(cat:99);

Categories