0

Should we put behaviors (method) in constant class in Java? If not then why? Which clean code practice/principle I am breaking while doing that?

public class TagConstants {

  public static final String O_NAME = "oName";
  public static final String O_TYPE = "oType";
  public static final String S_TYPE = "sType";
  public static final String V_CATEGORY = "vCategory"; // 50 more final strings

  public static boolean abc(String type){
    if(O_TYPE.equals(type) || S_TYPE.equals(type)){
      return true;
    }
  }

2 Answers 2

3

No, you shouldn't.

If the "type" has a behavior, then you should make it a proper object. This will make it its own smaller, cohesive thing. It becomes slightly easier to maintain, because it is not mixed with other stuff, and also properly named. Also, by making it its own type, you (and others) will not accidentally mistake any string for a "type". It will make reading signatures easier. It is basically a win-win-win from all sides.

1
  • Agree, with the follow-up that an enum is probably the correct solution.
    – user949300
    Jun 20, 2021 at 4:45
0

It really depends on what the purpose of the method is. Because you can't define methods outside of a class in Java, the approach you show is standard practice for utility methods i.e. things that generic and address cross-cutting concerns. You can find classes like this throughout the JDK e.g. the Collections class.

However, if this is a 'behavior' specific to a (different) class, it's considered bad practice. Define the method in the class either as a member method or a class-level method (static).

Another option that might be relevant here is to use an enum and defined the isAbc method there. The naming convention in Java for boolean test methods is to prefix them with 'is'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.