Does IntelliJ IDEA have a Create Wrapper code generator - java

If I have an interface with a few methods. Sometimes I need to create a new implementation of the interface which wraps another instance of the interface and delegates most of the methods to the wrapped instance. Then I would change a couple of the implementations, maybe not delegating them.
A classic example would be the Collections.unmodifiableXXX() methods in the JDK which block access to the modification methods.
Does IntelliJ have any code assistance that will generate a delegate implementation of the interface and then I can just tweak a couple of methods?

You can do it in two stages. First implement the interface and then introduce delegation

Code|Delegate Methods

Related

Interface defining a concrete method - Under what circumstances is this allowed?

While going through spring security modules I came across this piece of code inside the Principal Interface class. My understanding is that Interfaces do not implement anything concrete.
What is the reason for the below piece of code inside an Interface ?
public interface Principal {
//other method definitions
public default boolean implies(Subject subject) {
if (subject == null)
return false;
return subject.getPrincipals().contains(this);
}
}
Those are called default methods; and were introduced with Java8.
Quoting the Oracle tutorial:
Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.
Meaning: starting with java8, we actually can add behavior into interfaces. The idea is to make it easier to enhance existing interfaces - not to provide a "generic" mixin/trait concept to Java.
In other words: according to the people behind Java, the main reason for default was the need to enhance a lot of existing collection interfaces to support the new stream paradigm.
It is also worth pointing out that Java8 interfaces also allow for static methods:
In addition to default methods, you can define static methods in interfaces. (A static method is a method that is associated with the class in which it is defined rather than with any object. Every instance of the class shares its static methods.)
This is a default method for an interface, available since Java 8.
It's a feature that allows developers to add new methods to an interface without breaking the existing implementations of these. It provides flexibility to allow interface define implementation which will use as default in the situation where a concrete class fails to provide an implementation for that method.
Refactoring an existing interface from a framework or even from the
JDK is complicated. Modify one interface breaks all classes that
extends the interface which means that adding any new method could
break millions of lines of code. Therefore, default methods have
introduced as a mechanism to extending interfaces in a backward
compatible way.
Another potential usage would be to just call other methods from the interface like in a forEach option where you get a list parameter and call another method that accepts just one element.
My personal opinion is that default methods should be used as less as possible and to not contain any business logic. It's mainly made for keeping old interfaces (10+ years old) retro-compatible.
More details: https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html
https://dzone.com/articles/interface-default-methods-java

Adding methods or not adding methods to interface?

In Java 8, we can have default implementations for methods in interfaces, in addition to declarations which need to be implemented in the concrete classes.
Is it a good design or best practice to have default methods in an interface, or did Java 8 come-up with that only to provide more support on older APIs? Should we start with using default methods in new Java 8 projects?
Please help me to understand what is good design here, in detail.
Prior java8, you were looking towards versioned capabilities when talking about "reasonable" ways of extending interfaces:
You have something like:
interface Capability ...
interface AppleDealer {
List<Apples> getApples();
}
and in order to retrieve an AppleDealer, there is some central service like
public <T> T getCapability (Class<T> type);
So your client code would be doing:
AppleDealer dealer = service.getCapability(AppleDealer.class);
When the need for another method comes up, you go:
interface AppleDealerV2 extends AppleDealer { ...
And clients that want V2, just do a getCapability(AppleDealerV2.class) call. Those that don't care don't have to modify their code!
Please note: of course, this only works for extending interfaces. You can't use this approach neither to change signatures nor to remove methods in existing interfaces.
Thus: just adding a new method to an interface; and having default to implement that method right there; without breaking any existing client code is a huge step forward!
Meaning: why wouldn't you use default methods on existing interfaces? Existing code will not care. It doesn't know about the new defaulted methods.
Default method in Interface has some limitations. You can not have data variables in Interface. In general the reason default methods were added for the following reason. Say in your previous version you wrote a class that implements an interface "A".In your next version you decided that it would be good idea to add a method to your interface "A". But you can not do so since any class that implements "A" now will not have that extra method and thus will not compile. This would be a MAJOR backwards compatibility breakdown. So in Java 8 you can add a default method implementation into interface so all classes that implemented old version of "A" will not be broken but will fall back on default implementation. So use this feature sparingly, only if indeed you need to expand your existing interface.
In earlier java versions it wasnt possible beacuase you had abstract classes to use concrete and declared methods only but.
Java 8 introduces “Default Method” or (Defender methods) new feature, which allows developer to add new methods to the interfaces without breaking the existing implementation of these interface. It provides flexibility to allow interface define implementation which will use as default in the situation where a concrete class fails to provide an implementation for that method.
Let consider small example to understand how it works:
public interface oldInterface {
public void existingMethod();
default public void newDefaultMethod() {
System.out.println("New default method"
" is added in interface");
}
}
The following class will compile successfully in Java JDK 8
public class oldInterfaceImpl implements oldInterface {
public void existingMethod() {
// existing implementation is here…
}
}
Why Defaut Method?
Reengineering an existing JDK framework is always very complex. Modify one interface in JDK framework breaks all classes that extends the interface which means that adding any new method could break millions of lines of code. Therefore, default methods have introduced as a mechanism to extending interfaces in a backward compatible way.
NOTE:
However we can achive this backward compatability.but its always recommended to use interfaces with delarations only that is what they are best used for.
For simple example if You have an interface Human_behaviour you can utilize all the actions of this interface like to_Walk();
to_Eat() ,to_Love(),to_Fight() say for example in every implementing class in a unique way for every human object.Like
One Human can Fight using Swords and another Object using guns and so forth.
Thus Interface is a blessing but may always be used as per the need.

Override an interface?

I am creating a mod for the game Minecraft, which has an interface to implement in-game commands. I need the mod to implement that interface, but override one of its methods with a non-compatible method (different return type). But I need to prevent a situation where other classes that implement that interface will not work or not be recognized by the game.
I think this would require overriding the interface with a new interface that is the same as the original, but with an overloaded version of that method to support the mod's needs. Is this possible (or is there another way I can accomplish this?)
One way to think about interfaces is as a contract.
Implementing classes must strictly adhere to this contract.
This means that the method signatures (including return values and parameter) must match exactly.
The entire point of interfaces is to define the interaction without strictly knowing the implementation.
If the interaction you are looking to implement is different then it's possible that you are trying to use something in a way it wasn't intended for.
Even if it is possible to subclass an interface, it's going to quickly get messy.
It's probably in you best interest to create a new interface (with all the other methods the same).
Since it's not going to be comparable with classes that use interface A, you are saving yourself trouble by separating it entirely.
The interfaces supplied by Mojang/forge team are intended for use within the mojang/forge code. They expect the result types to be returned that the interfaces return. If they don't get that as defined by the contract/interface the code will crash/not compile.
It seems as if you are trying to use an interface for a particular purpose for an own project/api.
Consider writing a new interface specifically for the purpose you intend to use it for. Don't modify core interfaces.
A class can inherit multiple interfaces, so that's not an issue. You can implement AND the forge/mojang interface AND your own.
You can implement the mod class. Then override the method. Also write another method which will overload the method in your implemented class. That way you won't have to change the interface.

Preventing API users from using some methods

Hi I'm implementing a given design in java. Basically I have an abstract class which is called base and I have a number of concrete classes which are extending Base and implementing an interface from a different package. Each concrete class will be implementing a different interface. Now these interfaces contain both event-based and non event-based method signatures in them. My question here is; I'm only expected to implement non-event based methods in my concrete classes, however because of the implements keyword java forces me to insert an auto generated method body, which is basically return null. They might be implementing those event based methods later on but not at the moment. What would be an appropriate way to let the API user know that these methods do not contain an implementation. Here are my thoughts;
Use deprecated keyword
Create an exception class and throw that exception inside of the method and let the API user handle it.
I do not have the option of making changes to the existing architecture. Any idea really appreciated. Thank you.
According to Oracle, the reasons to deprecate an API include
It is insecure, buggy, or highly inefficient
It is going away in a future release
It encourages bad coding practices
neither of which actually fits your case.
Personally, I would favor throwing an UnsupportedOperationException which is already provided by the Standard Library in order to
indicate that the requested operation is not supported.
To me, this sounds more like what you actually want.
You can create your own interface which lists all the method you want users of your component to be able to access. Make this the only interface they use and additional public methods will not be visible.
Option (2) is good, but as you are following interfaces you'll want unchecked exceptions. And document the methods as unimplemented.
Deprecated implies a history, i.e., it works but should no longer be used. Since you are explicitly stating that the methods do not work, marking as deprecated will not prevent use nor indicate that the methods are unimplemented.
I would suggest use some mix bag of design patterns. That will help you solve this problem efficiently and make the code maintainable as well.
Based on my knowledge, you can use the Abstract Factory pattern here. See the design sketch below in the figure.
Method1 and method2 in subclass1 and subclass2 are the ones which are supposed to be exposed while method3 and method4 in subclass1 and subclass2 are the ones which we don't want to expose.
Create a Genericsubclass interface and create some methods in this interface depending upon the nature of methods you have in subclasses. For ex: i have create one method in this interface called nonEventbasedmethod1
Create a factory corresponding to every sub class and each factory will implement the GenericSubclass interface. Then implementation of nonEventbasedmethod1 method in subclass1Factory would be some thing like
nonEventbasedmethod1(){
subclass1.method1();
}
and implementation of nonEventbasedmethod1 method in subclass2Factory would be some thing like
nonEventbasedmethod1(){
subclass2.method3();
}
Then create a SubclassAbstract Factory which will return one of the subclass factories and then without worrying about which factory has been returned (that decision has already been taken in SubclassAbstractFactory before returning the appropriate factory) simply call the desired method from GenericSubclass interface and underneath one of the methods from the subclass1 or subclass2 will be invoked.
Hope this helps.
If you plain to throw an exception for "NotSupported" or "NotImplemented" Exception - consider the exception of NotImplementedException (at org.apache.commons).
However, I would reconsider to revisit your design and see if you can avoid having this - maybe you need to define another interface, which will hold the methods that are always implemented, and extend it in another interface (or provide an interface with no extension to the previous one) for the methods you not always implement.

100% Abstract class vs Interface

Is there a reason to use a 100% abstract class and not an interface ?
Can you give me a good example when to use both so I can grasp the concept a little?
Update:
100% Abstract class -> abstract class with only abstract methods.
I'm curios if there are differences between php and java regarding this aspect.
Update2:
Even if I understand most of the reasons I'm more interested in the conceptual more than technical reasons.
If by "100% abstract class" you mean "abstract class with no concrete methods", then I can think of a reason: visibility.
You can define an abstract method to be protected, and hence not part of the public API of the class. However, that seems like an odd design.
Another thing that came to my mind is when you expect to add common functionality to the base class - i.e. if it is likely to have some utility methods shared by all implementors, but these methods are not implemented.
Another thing - instance variables. You can have inheritable instance variables in the abstract class.
The one case where an "100% abstract class" may be advantageous over an interface is in places where API stability is a key concern.
If you write an API where other people are expected to implement your interface you have to stick to the interface. You can't add any methods to the interface later on because that would break all clients (you would have to work around this by implement a second interface and let your code check againt the usage with instanceof checks and provide an fallback).
If you realize the same with an class you can add (non abstract) methods later on without breaking the client.
Next to visibility, another reason could be to be able to specify a certain Constructor you want all implementations to implement, or define a certain property. But in general, I agree with Alexander that a 100% abstract class isn't a good idea. I would prefer an interface in most cases unless there's a very good reason not to use an interface.
I personally think the difference as conceptual more than technical. For instance it would be bad idea to have an interface called "Human" and implement them on Male and Female. It would make more sense to make the Human as class.
You can implement multiple interfaces and you should see interfaces as add-ons.
I'm not quite sure how to answer this conceptually anymore, but in practice I use interfaces for the following reasons:
To indicate different classes have a shared interface: that you can manipulate them / use them in the same way
You can implement multiple interfaces, but only extend one class
Reasons for using abstract classes:
To share functionality between similar objects. For example Porshe911 could extend Car, overwrite a few methods and keep the rest.
To write frameworks that people can adapt. For example by leaving a few crucial methods unimplemented and writing the rest of the class to be internally consistent provided you implement those few methods. An example would be a menu class with a single abstract method getMenuItems()
Your example of the 100% abstract class seems senseless to me. As far as I can see that would just make it an interface, with the added restriction that you can have only one.
100% Abstract class isn't good idea. For common structure of child classes uses Interface. For similiar classes with same some methods and not same others more better to use Abstract Class.

Categories