Best practice for global constants involving magic numbers

前端 未结 5 1555
北海茫月
北海茫月 2020-12-17 21:11

To avoid magic numbers, I always use constants in my code. Back in the old days we used to define constant sets in a methodless interface which has now become an antipatter

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-17 21:47

    Yes it is. Enum is the best choice.

    You are getting for free:

    • constants
    • immutable objects
    • singletons

    All in one.

    But wait, there's some more. Every enum value can have its own fields and methods. It's a rich constant object with behavior that allows transformation into different forms. Not only toString, but toInt, toWhateverDestination you need.

提交回复
热议问题