Steven Berdak
Steven Berdak

Reputation: 89

Is it bad form to declare constants using methods?

I did a search and could not find any other threads that cover this specific topic.

    public static final Path DIR  = ROOT.resolve(NAME);

Is there any reason this would be considered bad practice?

Upvotes: 1

Views: 51

Answers (2)

mpasko256
mpasko256

Reputation: 841

What you did, is a declaration of a global variable. It is bad practice itself. What I would rather suggest is to declare this variable as private and initialize it in a constructor of class that will be granted only responsibility to operate on that directory (?). Consider a situation when the directory path calculation method would change. It would impact all other classes that use this variable. So it would be better to limit any negative impacts.

Upvotes: 1

Timothy Truckle
Timothy Truckle

Reputation: 15622

The main problem is the tight coupling between the class having this constant and what ever the type of ROOT is.

So if DIR is something that is not known at compile time it should be injected into the class (preferably as a constructor parameter) and held in a private final (but not static) member.

Upvotes: 3

Related Questions