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 cla开发者_如何学Csses 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.
精彩评论