What is the purpose of interface inside a Java class? - java

In the sample code below, I have an interface inside class so that I'm using the methods of interface. But i don't see any effect with/without interface methods. Can someone help me what is the purpose of adding including them?
public class Controller {
FlowerCallBackReceiver mListener;
#Override
public void success(String s, Response response) {
try {
mListener.onFetchProgress(flower);
} catch (JSONException e) {
mListener.onFetchFailed();
}
mListener.onFetchComplete();
}
#Override
public void failure(RetrofitError error) {
mListener.onFetchComplete();
}
public interface FlowerCallBackReceiver {
void onFetchProgress(Flower flower);
void onFetchComplete();
void onFetchFailed();
}
}

This nested interface declaration is just a simple organizational technique. It won't change the standard Java interface semantics at all.
For instance, developers use it to clean up the top level package namespace. It's a matter a style, one may say.
Some quick Java SE examples:
interface Thread.UncaughtExceptionHandler
interface Map.Entry<K,V>
interface Policy.Parameters
interface DirectoryStream.Filter<T>
interface ServiceRegistry.Filter
etc

There is no obvious reason to have that interface there, based on the code you have shown.
One might typically nest an interface inside a class if implementations of that class are to be used in the body of the rest of the class, for example if Controller had a method like:
void doSomething(FlowerCallBackReceiver callback) {
// ...
}
But this interface isn't used here, so it's not apparent why it would be here.

Related

Java Delegate Interface

Is there a simple Interface in Java like the following code?
public interface Delegate {
void action();
}
Java Delegates? describes the functionality well.
It's not a Supplier, not a Consumer, not a Function, not a Runnable(no async stuff needed), I just want to pass a lambda to a method to be executed in between common parts.
Now I'm wondering why I have to define this interface myself. Am I just unable to find the standard Java interface for this or am I missing some vital drawback here?
Usage in my code (simplified):
public void transferX(Xrequest request){
transfer(request, () -> this.typedWrite(request));
}
public void transferY(Yrequest request){
transfer(request, () -> this.typedWrite(request));
}
void transfer(BaseRequest request, final Delegate writeFunction){
...
try{
writeFunction.action();
...
catch(...){...}
}
void typedWrite(Xrequest request){...}
void typedWrite(Yrequest request){...}
OK, as Sweeper pointed out, that is just the Runnable interface. I just don't like the naming, since I immediately associate it with multithreading.
For comparison:
#FunctionalInterface
public interface Runnable {
public abstract void run();
}

Template pattern but with one of the classes not implementing the method

I am trying to implement Template method pattern, but I need a slight variation that I don't think is best practice.
I have the following structure of classes
abstract class AbsClass {
public void algorithm(){
step1();
step2();
}
private void step1() {
//implementation
}
protected abstract void step2();
}
class A extends AbsClass {
protected void step2() {
// With implementation
}
}
class B extends AbsClass {
protected void step2() {
// No implementation needed
}
}
In the real case I have like 4 classes, and one of them doesn't need to have implementation for the second step. I don't think to leave the method empty would be good practice. I was thinking to put a comment(saying there is no need for implementation) in it, but I don't this would be the right solution.
Is there another approach I am not seeing?
We should not Force a design pattern. Here if we prefer Composition over inheritance then its better.
The code present in the question we have a method defined in a class but actually method has no behavior. Forcing a method in a class where it should not belomg to is not a good idea.
Below is one such possible implementation where you would not force a method to a class if it does not belong to it. Below is based on Strategy patter, but still I would say follow design principles and let the pattern itself suit your problem and do not force pattern to fit your solution.
public class AlgorithmClass {
private Strategy strategy;
public void setStrategy(Strategy strategy){
this.strategy = strategy;
}
public void algorithm(){
step1();
step2();
}
private void step1() {
//implementation
}
private void step2(){
if(this.strategy != null){
this.strategy.execute();
}
}
}
public interface Strategy{
public void execute();
}
public class Strategy1 implements Strategy{
public void execute(){
//implement your one of the stategies for step 2
}
}
public class Strategy2 implements Strategy{
public void execute(){
//implement your another stategy for step 2
}
}
I agree with #Vinay Avasthi's answer but I want to reinforce it.
Hook Method
Hook methods are defined in the base class and are a default implementation. And these can be overridden - they don't have to.
From Template-Method-Pattern Wikipedia page:
Template method's abstract class may also define hook methods that may be overridden by subclasses. These have a no-op implementation in the abstract class, but provide a "hook" on which to "hang" implementations.
Improvement
What you should do is leave a comment in the method body like // empty method body so that someone reading your code (and maybe your self) knows that this method has not been forgotten
Java's Default Methods
There is a second way to implement the Template-Method-Pattern in Java. Since Java 8 it is possible to have default method implementations in an interface.
If your methods do not depend on state it could look like:
interface AbsClass {
default void algorithm(){
step1();
step2();
}
default void step1() {
// implementation or empty
}
default void step2() {
// empty body in default case
}
}
class B implements AbsClass { }
I think it is absolutely fine. If the default behavior of step2 is to do nothing, then you can have an empty method in base class and override in child classes.

Java: Is child overriding parent discouraged?

I was wondering if it's frowned upon that when designing an framework to be used by others, a class has some function as default behavior and expects its customers to override it if necessary. An example would be something like the following:
public class RecordProcessor<T extends Record> {
// ...
public void process() {
// process record logic
}
}
Consumers of this library creates their concrete classes to process their own records of type T.
Now I want to add a function called preProcess() to offer the ability for the consumers to preprocess their records. It would then look something like this:
public class RecordProcessor<T extends Record> {
// ...
public void process() {
preprocess();
// process record logic
}
public void preProcess() {
// By default no preprocessing
}
}
I know I can make preProcess an abstract function, but I dont want to due to a couple reasons:
Not all customers need to preprocess their records
We have a pipeline structure that autodeploys pushed code, so making RecordProcessor an abstract class would immediately break our customers' applications.
Is making preProcess do nothing in the parent class and let child classes override it considered bad practice? If not, what should the best way be to let customers know that they now have the power to preprocess the records? Through java docs?
One approach is to mark the public method as final (but this might also break existing apps) and allow protected hook methods to be overridden. For example:
public class RecordProcessor<T extends Record> {
// ...
public final void process() {
doPreProcess();
doProcess();
doPostProcess();
}
protected void doPreProcess() {
// By default no preprocessing
return;
}
protected void doProcess() {
// some default implementation
}
protected void doPostProcess() {
// By default no postprocessing
return;
}
}
Having some documentation should make it natural for other developers to recognize the optional extension methods.
I don't see anything wrong with having a hook method which does nothing. However, it should contain a return statement so static analysis tools won't complain.
UPDATE: in order to avoid breaking existing apps, if possible mark the existing method as deprecated and introduce a new method. For example:
public class RecordProcessor<T extends Record> {
// ...
public final void execute() {
doPreProcess();
doProcess();
doPostProcess();
}
#Deprecated - use execute() method instead.
public void process() {
doProcess();
}
protected void doPreProcess() {
// By default no preprocessing
return;
}
protected void doProcess() {
// some default implementation
}
protected void doPostProcess() {
// By default no postprocessing
return;
}
}
Prefer composition over inheritance. If you want your clients to add custom pre processing then do it by delegating to a separate objects.
public interface RecordPreProcessor<T extends Record>{
public void process(T record);
}
public class RecordProcessor<T extends Record> {
private RecordPreProcessor<T> recordPreProcessor = null;
public void setRecordPreProcessor(RecordPreProcessor<T> recordPreProcessor) {
this.recordPreProcessor = recordPreProcessor;
}
public void process() {
if (recordPreProcessor != null) recordPreProcessor.process(record);
// process record logic
}
}
No, overriding is not discouraged in Java.
The language allows overriding.
The language makes all methods overridable by default.
The Java class library includes examples of the same pattern.
Your approach is one reasonable way to allow subclasses to extend the behavior of their parent class. There are alternatives, such as passing a behavior as an object. However, there is no one true way.
One way you could improve your code is to mark preProcess() as protected. It's an implementation detail of the class. You don't want just anyone holding a RecordProcessor to decide they can call preProcess() by itself, right?
public class RecordProcessor<T extends Record> {
...
protected void preProcess() {
^^^^^^^^^
// By default no preprocessing
}
}
Another way to improve this is to consider whether you intend anyone to create an instance of the superclass RecordProcessor. If you don't, make the class abstract, to prevent that. The class name can express that, if you like, or your coding guidelines call for it.
public abstract class AbstractRecordProcessor<T extends Record> {
^^^^^^^^ ^^^^^^^^
...
protected void preProcess() {
// By default no preprocessing
}
}
One common way to document such methods is with the phrase "The default implementation does nothing. Subclasses may override this method ...". For example, below is the documentation for java.util.concurrent.FutureTask.done(). You can find more examples by searching for the first sentence of that phrase online.
public class FutureTask<V> implements RunnableFuture<V> {
...
/**
* Protected method invoked when this task transitions to state
* {#code isDone} (whether normally or via cancellation). The
* default implementation does nothing. Subclasses may override
* this method to invoke completion callbacks or perform
* bookkeeping. Note that you can query status inside the
* implementation of this method to determine whether this task
* has been cancelled.
*/
protected void done() { }
}
What I ended up doing- which I also thought was pretty good, inspired by #tsolakp, was simply creating a child class to RecordProcessor, called something like PreprocessRecordProcessor. This has no way of interfering existing code because nothing existing was touched. The class would something like this:
public class PreprocessRecordProcessor<T extends Record> extends RecordProcessor<T> {
// ...
public void process() {
preProcess();
super.process();
}
protected abstract void preProcess();
}
And if customers of this library would like to add their own logic they can simply extend this class and they'd be forced to provide pre-processing logic (as supposed to having the option to provide, which may result in unexpected results if they forgot to.)

Implementing Generic Interface in Java

I have a Java generics question I was hoping someone could answer. Consider the following code:
public interface Event{}
public class AddressChanged implements Event{}
public class AddressDiscarded implements Event{}
public interface Handles<T extends Event>{
public void handle(T event);
}
I want to implement this Handles interface like this:
public class AddressHandler implements Handles<AddressChanged>, Handles<AddressDiscarded>{
public void handle(AddressChanged e){}
public void handle(AddressDiscarded e){}
}
But java doesn't allow implementing Handles twice using the Generic. I was able to accomplish this with C#, but cannot figure a workaround in java without using Reflection or instanceof and casting.
Is there a way in java to implement the Handles interface using both generic interfaces? Or perhaps another way to write the Handles interface so the end result can be accomplished?
Going after #Amir Raminfar, you can use visitor pattern
interface Event{
void accept(Visitor v);
}
interface Visitor {
void visitAddressChanged(AddressChanged a);
void visitAddressDiscarded(AddressDiscarded a);
}
class AddressChanged implements Event{
#Override
public void accept(Visitor v) {
v.visitAddressChanged(this);
}
}
class AddressDiscarded implements Event{
#Override
public void accept(Visitor v) {
v.visitAddressDiscarded(this);
}
}
class AddressHandler implements Visitor {
void handle(Event e){
e.accept(this);
}
public void visitAddressChanged(AddressChanged e){}
public void visitAddressDiscarded(AddressDiscarded e){}
}
You can't do that in Java. You can only implement one concrete realization of the same generic interface. I would do this instead:
public class AddressHandler implements Handles<Event>{
public void handle(Event e){
if(e instanceof AddressDiscarded){
handleDiscarded(e);
} else if(e instanceof AddressChanged){
handleChanged(e);
}
}
public void handleDiscarded(AddressDiscarded e){}
public void handleChanged(AddressChanged e){}
}
No, because different "concrete" generic types in Java compile to the same type. The actual interface your object will implement is:
public interface Handles {
public void handle(Event event);
}
And, obviously, you can't have two different methods with an identical signature...
AFAIK you cannot do that, because when compiling the source code in Java these will both boil down to handle(Event), making the method ambiguous.
The generic information is not available during runtime in Java, in contrast to C#. That is why there it works as you describe.
You will have to change the method names to make them unique, like handleAddressChanged and handleAddressDiscarded.
This is indeed one of the weak points of Java generics.
Unfortunately not. The usual solution (fat, ugly, fast) is to create one Handles interface (i.e. HandlesAddressChange, HandlesAddressDiscarded) and give each of them a different method (handleAddressChange(...), handleAddressDiscarded()).
That way, the Java runtime can tell them apart.
Or you can use anonymous classes.
It isn't allowed because Java erases generic signatures during compilation. The interface method will actually have the signature
public void handle(Object event);
So you have two choices. Either implement separate Handlers for different events:
public class AddressChangedHandler implements Handles<AddressChanged>{ /* ... */ }
public class AddressDiscardedHandler implements Handles<AddressDiscarded>{ /* ... */ }
or implement one handler for all but check the type of the incoming event:
public void handle(Event e){
if (e instanceof AddressChanged) {
handleAdressChanged(e);
}
else if (e instanceof AddressDiscareded) {
handleAdressDiscarded(e);
}
}
An implementation like this won't work due to the constraints of the java specification.
But if you're not afraid to use AOP or some sort of an IOC-Container you could use annotations for that. Than your Aspects or the container could manage the messaging infrastructure and call the methods you annotate.
First you have to create the annotations.
#Target(ElementType.TYPE)
#Retention(RetentionPolicy.RUNTIME)
public #interface EventConsumer {}
#Target(ElementType.METHOD)
#Retention(RetentionPolicy.RUNTIME)
public #interface Handles{}
The you may annotate your class like that:
#EventConsumer
public class AddressHandler{
#Handles
public void handle(AddressChanged e){}
#Handles
public void handle(AddressDiscarded e){}
}
If you don't mind using a (small) library, here's one I wrote that solves your problem:
https://github.com/bertilmuth/requirementsascode
You'd build a model like this
Model.builder()
.on(AddressChanged.class).system(this::handleAddressChanged)
.on(AddressDiscarded.class).system(this::handleAddressDiscarded)
.build()
and run it.
How to do that exactly is described on the website.

Java Polymorphism - Selecting correct method based on subtype

Given the following Class and Service layer signatures:
public class PersonActionRequest {
PersonVO person
// ... other fields
}
public class MyServiceLayerClass {
public void requestAction(PersonActionRequest request)
{
PersonVO abstractPerson = request.getPerson();
// call appropriate executeAction method based on subclass of PersonVO
}
private void executeAction(PersonVO person) {}
private void executeAction(EmployeeVO employee) {}
private void executeAction(ManagerVO manager) {}
private void executeAction(UnicornWranglerVO unicornWrangler) {}
}
As discussed here, java will select the best method based on type info at compile time. (Ie., it will always select executeAction(PersonVO person) ).
What's the most appropriate way to select the correct method?
The internet tells me that using instanceof gets me slapped. However, I don't see the appropraite way to select the method without explictly casting abstractPerson to one of the other concrete types.
EDIT: To Clarify - The VO passed in is a simple ValueObject exposed for web clients to instantiate and pass in. By convention it doesn't have methods on it, it's simply a data structure with fields.
For this reason, calling personVO.executeAction() is not an option.
Thanks
Marty
If executeAction was a method in a base class or interface that was common to PersonVO, EmployeeVO, ManagerVO and UnicornWranglerVO, you could just call abstractPerson.executeAction() instead of having multiple overridden methods.
Your principle obstacle to polymorphism here seems to be a 'dumb-struct' data object + 'manager class' service non-pattern. The "more polymorphic' approach would be for execute() to be a method that the various person implementations override.
Assuming that can't change, the way you do multiple dispatch in Java is with visitor-looking callbacks.
public interface PersonVisitor {
void executeAction(EmployeeVO employee);
void executeAction(ManagerVO manager);
void executeAction(UnicornWranglerVO unicornWrangler);
}
public abstract class PersonVO {
public abstract void accept(PersonVisitor visitor);
}
public class EmployeeVO extends PersonVO {
#Override
public void accept(PersonVisitor visitor) {
visitor.executeAction(this);
}
}
public class MyServiceLayerClass implements PersonVisitor {
public void requestAction(PersonActionRequest request)
{
PersonVO abstractPerson = request.getPerson();
abstractPerson.accept(this);
}
public void executeAction(EmployeeVO employee) {}
public void executeAction(ManagerVO manager) {}
public void executeAction(UnicornWranglerVO unicornWrangler) {}
}
You could change the way you are approaching the design and use a Visitor, passing the executor into the Person and have the person type determine which to call.
The Visitor pattern is often used to overcome Java lacking double-dispatch.
I would explicitly cast the abstractPerson. Not only does it ensure the JVM gets the right method, it makes it a hell of a lot easier to read and ensure you know what's going on.

Categories