java field qualifier best practice [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
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.

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 have these pesky coding standards is so that the code can be maintained ... by someone other than the guy who wrote it. A good IT manager will understand this. A good PM will understand this. A good programmer will understand this.

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.

Related

Builder pattern: When should the model members be final? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
The builder pattern is one of the most popular creation patterns, and it has numerous benefits. I specifically want to understand if immutability of the model object itself is one of the key benefits. All the while I thought it was, but I could not find any backing documentation on the same. Consider this scenario, you are creating an object from a network call (from json let's say). We create model objects and it has a Builder inline. This is what everybody does. The members of the model are also private. Since this is a network object, the members won't have setters. My doubts are
With builder securing object creation, do we need to make members private.
Can we instead keep them public final and eliminate need for getter()
In general (irrespective of the above two points), shouldn't all non-settable members be final? I don't see many people making members final, why is it so?
Is this a good approach or not?
I'm really having my pain with the example you chose. Parsing JSON into objects is really something you can delegate to JSON-B / Jackson / insert JSON library here nowadays. But I get it that we're on a theoretical level here.
Wikipedia just says: The intent of the Builder design pattern is to separate the construction of a complex object from its representation.
From the theory, the builder pattern neither forces immutability nor is it any aspect of it.
With builder securing object creation, do we need to make members
private.
You don't need to do anything. But there is one simple stylistic rule: You either access members by getters and setters or by making them public. But not both.
Can we instead keep them public final and eliminate need for getter()
Final would imply immutability - if that's what you want to achieve, you can do so.
In general (irrespective of the above two points), shouldn't all
non-settable members be final? I don't see many people making members
final, why is it so? Is this a good approach or not?
You only make members final if you want them to be immutable or if they are constants. Otherwise it makes no sense. With your example, I can only think of constant values? However, you cannot make members final without setting their value. You either need to set them in the constructor or initialise them to null. But having final null values most likely doesn't serve any purpose.
The better approach for such values would be really just not to define a getter or setter and making it private. But then you again have just some useless null values laying in your class.
To be frank, this whole discussion about getters/setters or public is opening Pandora's box. I have had too many discussions about this by now, and it just doesn't matter which way you do it. In the end both serve the same purpose: setting and retrieving values.
Regarding final values: I don't have to use immutability often to be frank, in my area of development I can't really think of any case I've used it so far. The only thing I use it for is to mark constant values which I don't want to be changed by anything.
In the end, this whole discussion about design patterns is tedious. A builder is just a helping structure. You have to find your way on how to use it for your use case and in your company. Just remind you of the fact that it's whole purpose is to make the creation of complex objects more accessible.

Java define a explicit package-private modifier [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Obviously Java has a Access level package-private which achieved by not adding any explicit modifier.
But isn't there a way to explicitly add this modifier? It's a bit confusing that we need to omit access level when we want to use member in package only.
If there's no way, why package private decided to be a default level?
For example if default level was public than we would more consciously define relevant access level.
This isn't duplicate of question of why use it, because I know why, I just don't know why it's define implicitly and can't be defined explicitly.
EDIT
You can define it explicitly by using Lombok's #PackagePrivate
Used to indicate the explicit intention for the annotated entity to have the package private access level. Currently used by FieldDefaults and Value to avoid having it make a field one of public, protected, or private.
#PackagePrivate String thanksLombok;
In my opinion,
It would be bad if the default was
public because you could miss specifying the modifier and the piece of code that was intended to be private or something would be accessible to the world. Also, this might be against one of the OOP's core concepts - encapsulation.
private because generally you would want to interact with other classes instead of writing everything in one class.
protected because I would expect (personal opinion) things that are in a folder (package) to be accessible inside the folder and not in a class (child class) residing in some completely different directory.
If I were to do it again, I would choose package-private as the default because if some things are together (in the same package), the intention might be that they should be able to talk to each other.
But isn't there a way to explicitly add this modifier?
No there isn't. (Short of modifying the Java language, which is highly unlikely for something like this.)
The rest of your question calls for opinion-based answers1 and is off topic.
1 - 1) We were not in the room ~25 years ago when the design decisions were made. 2) There is (AFAIK) no extant publicly available documentation for the original language design decisions. 3) The people who were in the room will have probably mostly forgotten, even if we could ask them. 4) Any attempt by your / me to "reverse engineer" the original thinking will be colored by ~25 years of hindsight.

Does private methods are considered in the God Class code smell? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
The PMD started warn me about having the God Class after adding a small private method to an existing class.
I didn't find any clarification what types of methods are considered to be the reason of the code smell. It only says that it uses metrics to make a decision and such a class does too many things.
From my point of view we can have as many private methods as we want as long as we follow the Single Responsibility rule.
So I wanted to know whether my assumption is right or should I obey the PMD warning and make a refactoring. Thanks!
I think you named the crucial concept: the single responsibility principle. And as long as you keep this concept in mind (and you follow the other SOLID rules) you should be fine.
I rather find a high number of private methods could be a good thing - as you are hopefully upholding the single layer of abstraction principle!
Of course: when there are really too many private methods it might be worth looking if there are certain "sub aspects" worth moving into distinct classes of their own.
To complete the very good GhostCat answer, I would add that
the God object pattern doesn't apply only for methods or even public methods.
It's an anti-pattern where the object (or class as the issue comes from static members) knows too much (fields) and or does too much (methods).
So fields and methods (public as private) accumulation in a same class may contribute to make a class or an object a undesirable god.
From my point of view we can have as many private methods as we want
as long as we follow the Single Responsibility rule.
Single Responsibility principle for API is a really good thing.
But it doesn't mean that private processing/fields should violate this one.
Indeed as a class becomes really "big", the cohesion between its members may become low and so an undesirable coupling between some members may appear.
So separating distinct processings in other classes makes sense to improve code readability and maintainability .
The point is that when you see that your class has too many private methods, often times this functionality can be extracted to another class and by doing so you can:
reduce duplication in your code base
improve its testability
So this rule is legitimate, because even if you think that your design is SOLID enough, many times your object composition could be in fact more crystalic.

Why did Java make package access default? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm asking this question because I believe they did it for a very good reason and that most people do not use it properly, well from my experience in industry so far anyway. But if my theory is true then I'm not sure why they included the private access modifier...?
I believe that if default access is properly used it provides enhanced testability whilst maintaining encapsulation. And it also renders the private access modifier redundant.
The default access modifier can be used to provide the same affect by using a unique package for methods that need to be hidden from the rest of the world, and it does this without compromising testability, as packages in a test folder, with the same are able to access all the default methods declared in a source folder.
I believe this is why Java uses package access as 'default'. But I'm not sure why they also included private access, I'm sure there is a valid use case...
I agree about using the default (package private) modifier for stuff that is to be accessed by tests, but I don't agree about private being unnecessary. Even for tests there is a lot of stuff that is not needed to be visible.
For a good test, implementation details are unnecessary and should not be visible outside the class. The more "whitebox" a test is, the more fragile it is. I usually limit the default modifier to fields I expect to be set via dependency injection and set manually in a test. (I could also use constructor injection and get rid of this, but this is more convenient.)
I propose little thought-experiment. Consider this code:
public void promoteUser(User user)
{
int newRank = computeNew(user);
user.setRank(newRank);
}
private int computeNewRank(User user)
{
return user.getRank() + 1;
}
One might feel computeNewRank should be tested (real implementation might do lot more stuff). But let's forget that for a moment and through the magic of inlining do this:
public void promoteUser(User user)
{
int newRank = user.getRank() + 1;
user.setRank(newRank);
}
The beauty of this experiment is that it applies to private methods of any size. You can always imagine yourself inlining private member and asking yourself "What do I really want to test here?". Is it the private method itself or perhaps new class/component with brand new functionality that's disguised as private method? The point is, you should rarely (if ever!) need to test private (or even package/internal) members. To outside world, to your contract consumers those are all irrelevant details.
Now, of course we could replace everything with system tests. But then how your regular work flow would look like? What if in order to test the rank promotion code you'd have to log user, register for session, wait 3 minutes, enter promotional code, receive sms, confirm... You see my point.
It's good to remember that unit tests are for you, not the other way around. You can bend them, adjust them, make them fit so that you can deliver software of better quality. Thier purpose is not to help you achieve some magical goal of 100% coverage, but rather to give you immediate feedback on what you're doing so that you can react more quickly to bugs and failures you will encounter. Or in other words, to improve your productivity.

Good practice when accessing a field in a class [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
When you have to access a "member variable"/field in a class, is it good practice to access it directly or call the getter and setter? and why?
I see almost only benefits in making your fields private and only provide access through a getter and possibly a setter
controlled access. If you only want to provide read access, or only write access you can only achieve this by using getters/setters
if you want to fire PropertyChangeEvents for bean properties, you can include this code in your setter. Otherwise all calls which modify this field directly should trigger a change event as well
I personally find it easier to discover in my IDE who modifies the field. The only direct access to the field is in the class (since it is a private field), and all external changes go through the setter. This allows for faster debugging than having to use a field watchpoint
subclasses who want to do something extra when the field change can override the setter, call super.set and do something extra
The only possible drawback I can think of is that it requires a bit more code to write (for the getters and setters), and a bit more code for accessing the field from outside the class. But with the current IDEs is this a pretty lame excuse
Some extra literature:
link1, link2
Call the setter/getter rather than accessing directly. That way any extra required code in the setter/getter will be run.
Getter/ Setter allows for lazy instantiation, which is often a way to go. Additionally, this way you have a controlled access to your variables (both for yourself and as part of any API you may want to expose); ability to hide implementation of initialization etc are also very important.
The biggest benefits of S/G in my opinion is reduced risk of someone modifying it without your control. A small example .. consider that a getter may give you .. a copy of the original instead of an original.
Benefits are multiple, when given a choice, choose setter/ getter for the benefits of data encapsulation and more control.
If it is a member of the calling class, access it directly. Otherwise use the getter/setter methods.
Why? You should not be creating getter/setter methods just so that the calling class can access its own members. Otherwise you should use the getter/setter methods for the reasons elaborated by others.

Categories