1

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?

Steven Berdak
  • 89
  • 1
  • 5
  • Nothing specific, as that's a field value and field values are initialized first there shouldn't be issue with that code. But maybe you should consider using static initialization block for that. – whatamidoingwithmylife Dec 03 '17 at 21:13
  • Example: https://stackoverflow.com/a/2420405/544779 – Mörre Dec 03 '17 at 21:16
  • I see. Thank you for your answer. Maybe this will help anyone else who is wondering whether static final variables assigned through a method are good practice or not. – Steven Berdak Dec 03 '17 at 23:37

2 Answers2

3

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.

Timothy Truckle
  • 15,071
  • 2
  • 27
  • 51
  • The purpose is just to ensure that the path is uniformly used throughout the class as well as other classes having access to this path. I originally had a getter method but then I started asking myself why and then I came up with this. It compiles fine sure but it doesn't feel right as it feels wrong to instantiate a class with something that has the potential to return null (possibility, though unlikely). You are probably right though. The constructor is private anyways so initializing in a constructor or a static initialization block as other have said probably makes more sense. Thank you :P – Steven Berdak Dec 03 '17 at 23:34
1

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.

mpasko256
  • 811
  • 14
  • 30
  • Yes, the files this class is responsible for only exist in a single directory. Root is where the program was ran. Not system root such as C:\ – Steven Berdak Dec 03 '17 at 23:24