Question

From a OO perspective, are enums supposed to be within a separate class? I have seen a few examples of this. I am wondering if this is the correct way to do it? (just trying to learn the 'proper' way of doing things.

Était-ce utile?

La solution

There is no universally "proper" way of defining enums - it goes the same way as other entities that can be nested or could exist on their own, such as classes and interfaces.

  • When your enum is intended for use only with a particular class, for example, to enumerate options of one of its methods, defining enum inside the class is reasonable
  • When your enum is intended to be shared among multiple classes, define it at the top level.

Autres conseils

If the enum constants are used by multiple classes, then it can be in separate class. Otherwise, if it's used only within a class, it can be private inner enum class.

If only one class is using those enums, you better have them in that class and mark them private. But if their scope is more than one class, you obviously need to have those enums at a place where they could be accessed by all the classes that need them.

As suggested in above answer it all depend on requirements. I think it is worthwhile to make it public/separate for reusability and decoupling point of view.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top