Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should static variables be replaced with enums?

So I was looking at some code that was checked in and I got all puzzled over:

// Amount of days before cancellation can't be done
enum Cancellation { Limit = 2 };

Asking the guy who checked it in he argued that it's much better to use enums instead of static variables, bettern than this:

private static int CANCELLATION_LIMIT = 2;

So we started arguing. My argument was that he was using enum as a way to store values (it'll break if there were two enum symbols with the same value). He argued it was an antipattern to have static variables in a class.

My question is what best practice should be used for either?

like image 789
Spoike Avatar asked Jan 29 '09 10:01

Spoike


People also ask

Is it better to use enum or constant?

Enums are lists of constants. When you need a predefined list of values which do represent some kind of numeric or textual data, you should use an enum. You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values.

Does enum need to be static?

All Enums are implicitly static, its just you don't need to write the static keyword.

Are enum variables static?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden).

Should enums be constants?

Enums are known as named constants. Enums are strongly-typed constants that make the code more readable and less prone to errors. Enums are known as named constants. If we have some constants related to each other then we can use an enum to group all the constants.


2 Answers

return "Is it logically a set of values" ? "Enum is appropriate" : "Static const is fine"

(I'm a big fan of the logically consistent)

like image 121
annakata Avatar answered Oct 21 '22 13:10

annakata


Enums are typed.

That is, if you have a method where you have to pass a certain 'state' to a method for instance, you can only pass 'valid' arguments. For instance:

enum OrderState 
{
  pending = 1,
  shipped = 2
}

public IList<Order> GetOrdersInState( OrderState )
{
}

This is a good example -imho- of using enums. When OrderState is an int for which you create 2 const ints, you have no restriction and are able to pass invalid values. The compiler won't complain.

However, the case that you're bringing up, I think using enums is not a valid solution. It's a misuse of using an int, and a const int should be used.

Enums are good, but they should be used where they must be used. They're not the preferred tool in every situation. Having a const or static var is in this case not an antipattern.

like image 41
Frederik Gheysels Avatar answered Oct 21 '22 12:10

Frederik Gheysels