Type Code vs Enum for refactoring?
Type code (i.e., 1,2,3 (open,close,unused)) is being used in my project and I would like to refactor that part of code. Should I follow Replace type code with class as mentioned in Refactoring Improve the design of existing code or just using enum is sufficient? C# is my progr开发者_JAVA技巧amming language.
From what you're describing, the type code represents a discrete set of choices which have no other associated information. I would therefore suggest using an enum
type to replace the integral representation.
It looks like open, closed and unused are states. If yes, then I suggest you to use state design pattern. It may look like creating more classes, but code will be maintainable. You can get rid of switches and if/else as well.
http://www.blackwasp.co.uk/State.aspx
Yes using an enum is "sufficient" if you only want to do the minimum amount of work, but replacing it with a class is better.
Re the State pattern suggested by Splendor. I dislike the State pattern as defined by the GOF as it doesn't incorporate anything to do with actions on state transition, nor does it define what state transitions are valid. IMO there are better approaches to managing state than that pattern (however it's definitely worth reading about patterns if you haven't).
To answer your question, I'd just use Enums. It's worth considering namespaces at this point.
You can put enums into your classes.
public class Box
{
public enum BoxState { Open, Closed, Unused }
}
or directly into a namespace:
namespace MyOrg.Enums
{
public enum BoxState { Open, Closed, Unused }
}
It really depends on the context of the enum; something very specific is more likely to belong inside a class, something more general (and used frequently through your code) is better inside a namespace.
精彩评论