Does private methods are considered in the God Class code smell? [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 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.

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.

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.

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.

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.

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