Java define a explicit package-private modifier [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 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.

Related

Interfaces and static methods in java [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 months ago.
The community reviewed whether to reopen this question 9 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
It occurred to me that interfaces cannot be instantiated and hence I could create an interface containing only a bunch of static utilities methods that I need as opposed to a regular class with a private constructor and public static methods. Any comments on that? Should I do it or does it not really matter?
A program is not just a set of instructions for a computer to obey. It's also a message to future developers. You should use the statements in your program to indicate to other developers (or even yourself a few months into the future), what you intend for the computer to do.
That's why we give variables, methods and classes clear names. It's why we lay out our programs in certain expected ways. It's why we use indentation consistently, and why we have naming conventions.
One of those conventions is that if you have a bunch of static methods that need to be organised together, they should be organised into a class, not an interface. Whether or not it's technically possible to put all your methods into an interface is not the question you should be asking. What matters is how to communicate most efficiently what you're actually intending to do.
To that end, please don't set up your program in strange, innovative ways. You're just going to confuse and annoy people.
Although this is possible interfaces should be used
when it is important for disparate groups of programmers to agree to a "contract" that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group's code is written. Generally speaking, interfaces are such contracts.
https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html
Interfaces should be defined as an abstract type used to specify the behavior of a class; therefore they're meant to be later implemented.
What you're trying to do is not completely wrong (interfaces can offer static methods), but it's definitely not what they were designed for. If you want to offer a set of static utilities from a common "place", you could declare a final class with a private constructor, in order to prevent its extension (with possible methods overriding), and avoid its instantiation. The Math class is a perfect example of this.
Alternatively, if you want to declare instances of said class, you could declare your class normally, then declare its methods as final (to prevent their overriding) and offer a public constructor or a factory method.

Does encapsulation of class methods/fields matter if they are only accessed by the class itself? [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
Short context: I made a tetris clone in java (all the game data and methods are a Class) and I am concerned about whether encapsulation matters in this case.
Almost all of the fields and methods are marked as "default", without any getters and setters because the user is not supposed to access them.
Methods manipulate variables directly without any arguments passed, of course only when the thing it is manipulating is unique (there can not be two current pieces, two next block lists, two held pieces and so on)
Do I really need getters and setters if the user is never supposed to get raw members of the class? Methods just directly get and set the values. If I have a simple int that I want to get or set, I am just doing it directly.
No return value, if one exact thing is supposed to happen every time. For example: if a collision happens during spawning, gameOver() is triggered immediately instead of returning false, then doing it outside of function. I chose to not have a return value because it is much simpler to do it inside function instead of surrounding each function call with an if statement doing the same thing.
Do I need to fix some of these things, and how should I, preserving stability in both readability and performance?
It does not.
Why? The understanding is that a class’s fields and methods are working in conjunction towards a common goal. So they are not enemies or careless actors that you have to protect yourself against.
It is only to prevent external actors from mucking up class invariants that you hide your fields and methods as much as possible and expose only that which is necessary.
If you have to use setters and getters to enforce discipline in the code within a class, then you have much bigger problems to handle than maintaining proper encapsulation (and other OO principles.)
No, you do not need getters and setters if you do not intend on anything accessing the member variables from outside of the class.
In your case because the member variables are only accessed from within the class itself then the access modifier(s) should be changed to private.
The use of the default keyword means that you do not want to provide an access modifier and that variable should be available to any other class in the same package.
More info can be found Here

Any reason to make private methods in a Spring singleton bean static? [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
I did some research but didn't find an answer that I am looking for. In Spring, DAO and service classes are declared as interface. Classes implementing interfaces are usually singleton Java beans. Question: do you see any reason that I should make private methods that don’t rely on instance variables static? Why?
For example, I have several private methods in a DAO class converting database data to domain object and these private methods don’t use instance variables. I understand some people might suggest that I should extract them to a utility.
The word singleton is used in multiple ways, which can cause a bit of confusion. A "hard" (physical, class-based, JVM) singleton is a class that ensures that only one instance can exist in the entire JVM, usually through an enum or a constant. This pattern should be avoided if the object has any state or configuration at all, since that can cause unexpected coupling between parts of an application. (It's usually fine if the object represents either a pure function, such as CASE_INSENSITIVE_ORDER, or a value.)
In contrast, a singleton-scoped bean (logical, container-based) simply means that the container that is managing it will keep a single shared instance and supply it to all consumers that want one (instead of, for example, creating a separate private copy for each consumer). In most Spring applications, it's actually preferred for these to implement a Java interface that serves as the contract between the two sides, so the methods can't be static.
As to performance questions, static carries a meaning--specifically, that the method or field doesn't have a relationship to a specific instance of that class. Use it when the meaning is appropriate (such as most of the methods in Math), and don't change the meaning of your code in this way for any theoretical performance reason.

java field qualifier best practice [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 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.

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.

Categories