Best Practices for Storing Constants in a Program

0
7
Asked By CodeCrafter92 On

I'm currently working on a program that involves parsing a custom protocol with certain keywords like GET and LIST. Right now, I'm using magic strings for comparisons against the input, but I know it's better to store these as constants. Should I create a separate class specifically for protocol elements to keep track of these keywords, or would it be better to stick with using magic strings? Any advice would be much appreciated!

5 Answers

Answered By CodeRevolutionist On

Try not to create classes or interfaces just for storing constants—it often leads to an anti-pattern. Instead, you can use enums but also consider defining behaviors in addition to constants. For example, create an abstract class for your protocol commands that ties behaviors with the constants.

Answered By DevGuru77 On

Definitely go for enums. They provide a clearer structure and type safety as compared to just using strings.

Answered By ParserPro22 On

If you're looking for a comprehensive solution, tools like ANTLR could really help you build a more robust parser.

Answered By SyntaxWizard45 On

I usually recommend using enums for commands like these. For example, you can define an enum called Command with values GET and LIST. Then, you can convert string values into enums using Command.valueOf(str), which helps you avoid messy equality checks later on.

Answered By PatternFan88 On

One method I find effective is to create an interface containing all the constants, and then have the classes that require those constants implement that interface.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.