Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import static vs. static final

In the past I often used "import static" construct in Java classes. Recently I realized that instead of

import static my.pack.A.MY_CONSTANT;

you can use

import my.pack.A;

public class B {
    private static final MY_CONSTANT = A.MY_CONSTANT;
}

The most obvious advantages of this approach are:

  1. You can use refactoring in Eclipse to easily strip out all long constant expressions like A.B.C.CONSTANT.ANOTHER_ONE.TOO_LONG from your code without messing with static imports (which are not so quick to master in Eclipse)
  2. You can give any name to any expression, which may be more meaningful in the current context.

For example:

private static final PAYMENT_TYPE = PaymentType.CASH;
...
calculateSomething(amount, PAYMENT_TYPE);

instead of

import static my.pack.PaymentType.CASH
...
calculateSomething(amount, CASH);

and also this is more easy to refactor, if the default PaymentType value changes to CREDIT_CARD.

My question is: are there any downsides of this approach compared to static imports or can it be used everywhere instead?

My only concern for now is the resulting compiled .class file, which is probably different for the two described approaches. So performance and memory usage may theoretically suffer.

like image 907
afrish Avatar asked Feb 17 '23 17:02

afrish


1 Answers

I think the only downside is you have more code where you assign one constant to another constant. Other than that there should be no difference. Performance and memory shouldn't matter, you'll likely have more references back to the same constant pool entries. Even if it created separate constant pool entries it would take a lot of them to make a difference.

Being able to give good names to constants might be a very good thing, in cases where it isn't feasible to rename the original entries.

like image 113
Nathan Hughes Avatar answered Feb 20 '23 07:02

Nathan Hughes