简体   繁体   中英

Enums vs string constants c#

So I have recently read a book specifically on Dependency Injection. In this book, somewhere, it states that enums are a code smell....

I wanted to get a general consensus from SO'ers. I need to design a rather large application with some central core classes, and am seeking assistance in terms design principles that fellow SO'ers would use in this instance, before committing myself to one way or the other making it very difficult to change afterwards.

public enum Foo
{
  LovelyFoo,
  TerribleFoo
}

OR

Using a static class with Contants

public static class Foo
{
    public const string LovelyFoo = nameof(LovelyFoo); //or "Lovely Foo";
    public const string TerribleFoo = nameof(TerribleFoo); // or "Terrible Foo";
}

Then Of course using it when required

Foo MyFoo = Foo.LovelyFoo;

OR

string MyFoo = Foo.LovelyFoo;
  1. Just because something can be abused doesn't mean its bad to use.

  2. you gave no realistic use cases, and just foo examples its hard to tell if this smells or not.

  3. enums are good for tightly bound sets of things, days of the week for instance.

    • Were there is a legitimate use for switch statements
    • Where the set doesn't change and is ingrained.
    • Where (and this is circular i know) enums make sense

Let constants be constants, let enums be enums. But if you find your self wanting to use lots of enums and switches, then this is probably crying out for generics or polymorphic. Just because they look neat and typed and wonderful doesn't mean your code should be full of them.

Lastly, Run the Microsoft test over your use cases. That's to say, what would Microsoft do, where in the BCL have you seen this example, is it common, does Microsoft use them like this. Although this is no saving grace, if you find your self writing weird and wonderful structures that are unpredictable and no-one else has seen, then you are probably doing something wrong

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM