Interfaces and static methods in java [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 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.

Related

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 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.

Is it good to Sharing constant strings in Java across many classes? [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
I'd like to have Java constant strings at one place and use them across whole project?I am confusing Is it a good practice for better readability or not?
Simple: when multiple classes need the same information, then that information should have a single "root".
So yes: it is absolutely good practice to avoid re-declaring the same value in different places. Having a "global" constant simply helps with avoiding code duplication - thus preventing errors later on, when you might have to change such values.
One single class with (unrelated) constants has problems. It is a bottleneck:
if in a team a constant is added at the bottom, someone else adding a constant will receive a VCS conflict. Enforce the declarations to be sorted alphabetically. It also ties this package together in other forms. Still many unneeded recompilations would be needed (see also the remark at the end).
In java 9 with modules, you would in every using module need to require the constants classes module, probably causing an unnecessary module graph.
Then there are constants which need not be named and still are not "magic".
In annotations as arguments. An annotation scanning can gather those values if you need uniqueness or such.
And finally there are shared constants. Near the used constructs is still my favourite.
Also the constants class pattern tends to be used often with String constants. That reeks of code smell, as it is a kind of burocracy where one
should use automatic mechanisms, OO, fixed conventions, declarative data.
For database tables and columns there exist better mechanisms.
Classes with constants (still) have the technical compilation problem that in java the constant is incorporated in the .class file itself, and the import disappears. Hence changing the original constant will not notify the compiler to recompile the "using" class. One needs a full clean build after recompiling a constants class.
If you think that your Strings are going to be referenced in many flows, then it is good to use. Moreover, it is a widely accepted practice as well.
It is good to create Interface & declare your all constant in it.
E.G
public interface ICommonConstants {
public static final String ENCODING_TYPE_UTF8="UTF-8";
}
Implement this interface in your all class where you like to use constants.You can use by calling
ICommonConstants.ENCODING_TYPE_UTF8
Code duplication is a code smell and if you wouldn't use readily available constants you need to re-declare the String over and over again for each class using it, which is bad.
This leads to less maintainable code, because when the duplicated String needs to change and you forget to update it in one of the classes, the code breaks.
It's common practice to set up a class holding reusable constants:
public final class MyDefs {
public static final String A = "a";
public static final String B = "b";
private MyDefs() {
// Utility class, don't initialize.
}
}
I would recommend an Enum, or you could just have sort of like a utility class with just static final strings. All depends on what you want do i guess, i don't see anything bad. if the class is going to be shared by many classes, that's fine.

What if inheritance was deprecated as a functionality? [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
I had a question on an interview like this...
What if, lets say JAVA, decided to remove inheritance from the programming language, and you have over 1000 classes that use inheritance (superclass). How would you fix that if you want to change something in the superclass (for example a method or more methods). The fastest and most efficient way?
What do you think? :)
EDIT: Hey, guys, I know its not logical and Java would not do that and its the basic concept of OOP... but that a mind bender question... how would you solve the problem where you "shared" the code all around the app and now you dont have this functionality any more. How would you solve it?
I believe what the question is driving at is the concept of favoring composition over inheritance.
Say we have this hierarchy:
class Parent{
public String getName(){
return "xyz";
}
}
class Child extends Parent{}
We could achieve a similar relationship through composition:
class Parent{
public String getName(){
return "xyz";
}
}
class Child{
private Parent myParent;
public String getName(){
return myParent.getName();
}
}
This is an oversimplified example, but the basics are there. For more info, see the answers to this question.
Since this is a "What-If" question I think is valid trying to answer it
Since removing inheritance will mean to remove using extends and implements using a interface or extending an abstract class will no be posible
My approach: Substitute the superclass with a class that has public static properties and public (static when posible) methods making it a common access point for all the other classes to call and replace the super calls to those methods.
In this way most of the logic an properties will still be into a single class.
Under your assumption the fastest and most efficient thing is to stay with current Java version and/or wait till some team of enthusiasts will fork the OpenJDK to evolve it in more sensible way than removing the inheritance.
First of all there would be no OOP concept without inheritance, so Java team will never do that because every class in java extends java.lang.Object.
IMHO, they want to see whether you understand the inheritance. Because if inheritance is removed, then there is no concept of Super class at all. So there is no point in thinking about 'fastest and efficient way'.
Let's assume, there is no inheritance, and you modified the code to remove the errors by using the class associations. Any popular IDE will do that very easily.
For example, in Eclipse, Select the method -> Press Alt + Shift + R (to modify all references). So another aim of that question might be to test your knowledge on IDE usage.
There are alternative patterns to inheritance even if inheritance is supported by the language, and certainly when inheriting from a class causes the 2 classes to be tightly coupled it can be worthwhile considering if inheritance is the always the right approach.
As an example I recently read a wonderful article/chapter on the type pattern (available here - http://gameprogrammingpatterns.com/type-object.html). There are a number of potentially applicable patterns within the book that could be of use in this manner definitely worth a read.
Of course applying this pattern (or any number of alternative patterns) to all 1,000 classes might be a bit of a long exercise.
Another option would be to implement a simple form of inheritance yourself to replace the one removed. This isn't all that uncommon for example there are a number of libraries for JavaScript and Lua (I'm sure there are many others) that add support for class like behaviour including inheritance. How difficult this is to achieve will depend on the properties of the language.
There are a very large number of caveats here including performance and supporting every feature of inheritance the 1,000 classes rely on - but in a world where Java drops inheritance as a feature anything is possible.

Categories