Prasenjit Purohit February 2016

java field qualifier best practice

It is a good practice to use a proper qualifier between private, protected, private or default. But is there any other reason like performance or JVM optimization drawback default is used instead of private? As an example

public class Class1{
    Class2 class2;
}

And where variable class2 could have been private.

Also if the variable is autowired or injected by DI framework. Framework calls field.setAccessible(true). Does that make any difference as per the performance or optimization.

Answers


saroff February 2016

If it's not meant to be used by any other application - then just make it private. The point is OTHER developers can't read your mind. And if it's not private, then they will think, that it is meant to be used outside of class.


Stephen C February 2016

I think I now understand the motivation for this question.

The reasons for using the correct access modifiers on variables in normal Java are well understood. Basically, it is all about modularity, encapsulation, avoiding unwanted / harmful coupling and so on.

What about Spring?

Well it is true that Spring can circumvent normal access rules and allow you to inject private variables. However, from what I understand, you have to deliberately annotate your private fields with @autowire or similar for this to occur. What is actually going on here is that Spring is following an "instruction" that is explicitly declared in the source code by means of the annotation. Spring XML-based wiring won't let you inject a value into a private field or using a private setter.

In the light of this, the argument that Spring allows you break private encapsulation is ... while technically true ... ultimately self-serving. Sure, you can do it. But you have to do it explicitly, deliberately ... by design. And it ONLY happens when the objects are wired.

By contrast, if you are sloppy about the modifiers, and declare every instance variable as public or package private, then you are leaving open the possibility of all sorts of lazy, ill-considered, or even accidental breaking of encapsulation. And even if you (the original author) are disciplined, the next guy reading / maintaining your code can't be sure that you have been disciplined. He has to check ...

So how do you "force" someone to toe the line?

It is probably best to persuade rather than force, but the way to force people to write decent code is to get your project manager / quality manager to adopt a coding standard, and insist that it is followed. (But this can be easier said than done if your management doesn't understand the long-term costs of poor quality.)

The real reason we ha

Post Status

Asked in February 2016
Viewed 3,947 times
Voted 14
Answered 2 times

Search




Leave an answer