What if inheritance was deprecated as a functionality? [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
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.

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

Is there a possibility that C++ multiple inheritance might be replaced with the Java interfaces? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have been studying a bit of Java and C++ more or less at the same time and I noticed that Java has a more friendly and intuitive way of interpreting the OOP than the C++ way.
Yes, Java is completely OO and, on the other hand, C++ supports many paradigms, but this doesn't mean that C++ couldn't improve its way of implementing the OO paradigm.
C++ supports multiple inheritance and Java translated it with multiple implementation (interfaces), which I find really intuitive and simple (I don't think that this is just an opinion).
My first question is in the title. I think that C++ would be more friendly, without losing practically a bit of its power. It's a question of improving a extraordinary programming language, which however is not perfect.
My second question is: what are the advantages of multiple inheritance compared to the interfaces of Java programming language (if any)?
Multiple inheritance can be dangerous, but it's sometimes the most appropriate solution to a problem, and there's lots of software already written that uses it. Removing multiple inheritance from C++ would break all that software, in a way that's not simple to fix. Being compatible with existing code is more important than being "friendly".
If you want the effect of a Java interface in C++, just write a class that contains nothing but pure-virtual member functions, and derive from it using virtual inheritance to "implement" it in another class.
Java was designed as a higher-level and simpler language than C++, and the tradeoffs between them are the same as between any high-level and lower-level language. Java provides a bit less flexibility (e.g. single inheritance, little control over memory allocation) in exchange for being a bit easier to work with; C++ provides more power and flexibility at the cost of having to "know what you're doing" a bit more. These differences are OK; there's no need to turn one language into the other.
C++ is becoming more and more user-friendly with the updates, becoming bit by bit more like java, but it needs not to change too much not to wreck legacy code. The Boost library is more or less the pioneer of the c++ language, being the (probably) most used library of all times and taking an easier and more intuitive OO approach to c++. Features from the Boost libraries often get to the STD eventually.
Let's take this easy example : class man and class parent have respective functions work and cry. class dad inherits from both man and parent. Now you don't have to write cry twice when you write class mom which inherits from class woman as well as from parent.
1.Having multiple inheritance in a explicit way is seems to be more user friendly but actually it is not. There are lot of problem will be coming in the future if you do that i mean in your project for an instance knowingly unknowingly you will be adding the same code again and again to your final Class which makes your project more complicated and confuses the interpreter which method should be executed at the appropriate time.
Just consider in C++ you have
Class A
{
void display_a(){}
}
Class B A
{
void display_b(){}//this class contains 'display_a()' too
}
Class C A,B //multiple inheritance.
{
display_c(){} //this class contains two times 'display_a()' and one time 'display_b()'
}
so class a contains two times 'display_a()' this is the problem we have in multiple inheritance in C++ so that we go for Interface in Java,which solve that problem.

Are there any Java method ordering conventions? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I've got a large-ish class (40 or so methods) that is part of a package I will be submitting as course-work. Currently, the methods are pretty jumbled up in terms of utility public/private etc. and I want to order them in a sensible way. Is there a standard way of doing this? E.g. normally fields are listed before methods, the constructor(s) are listed before other methods, and getters/setters last; what about the remaining methods?
Class (static) variables: First the public class variables, then the
protected, and then the private.
Instance variables: First public, then protected, and then private.
Constructors
Methods: These methods should be grouped by functionality rather
than by scope or accessibility. For example, a private class method
can be in between two public instance methods. The goal is to make
reading and understanding the code easier.
Source: https://www.oracle.com/java/technologies/javase/codeconventions-fileorganization.html
Some conventions list all the public methods first, and then all the private ones - that means it's easy to separate the API from the implementation, even when there's no interface involved, if you see what I mean.
Another idea is to group related methods together - this makes it easier to spot seams where you could split your existing large class into several smaller, more targeted ones.
The more precise link to «Code Conventions»: «Class and Interface Declarations»
Not sure if there is universally accepted standard but my own preferences are;
constructors first
static methods next, if there is a main method, always before other static methods
non static methods next, usually in order of the significance of the method followed by any methods that it calls. This means that public methods that call other class methods appear towards the top and private methods that call no other methods usually end up towards the bottom
standard methods like toString, equals and hashcode next
getters and setters have a special place reserved right at the bottom of the class
40 methods in a single class is a bit much.
Would it make sense to move some of the functionality into other - suitably named - classes? Then it is much easier to make sense of.
When you have fewer, it is much easier to list them in a natural reading order. A frequent paradigm is to list things either before or after you need them , in the order you need them.
This usually means that main() goes on top or on bottom.
My "convention": static before instance, public before private, constructor before methods, but main method at the bottom (if present).
Also, eclipse offers the possibility to sort class members for you, if you for some reason mixed them up:
Open your class file, the go to "Source" in the main menu and select "Sort Members".
taken from here: Sorting methods in Eclipse
Are you using Eclipse? If so I would stick with the default member sort order, because that is likely to be most familiar to whoever reads your code (although it is not my favourite sort order.)

Categories