Overloaded method calls redesign - java

I have an interface IAction that has one generic method:
public interface IAction {
void doAction(ISignal sig, IState state);
}
Another class IActionAbstract then implements the IAction interface and calls overloaded methods with instanceof clauses:
public abstract class IActionAbstract implements IAction
{
#Override
public void doAction(ISignal sig, IState state)
{
if(sig instanceof ISignal1 && state instanceof IState1)
{
doOther((ISignal1)sig, (IState1)state);
}
else if(sig instanceof ISignal2 && state instanceof IState1)
{
doOther((ISignal2)sig, (IState1)state);
}
else if(sig instanceof ISignal1 && state instanceof IState2)
{
doOther((ISignal1)sig, (IState2)state);
}
}
abstract void doOther(ISignal1 sig, IState1 state);
abstract void doOther(ISignal2 sig, IState1 state);
abstract void doOther(ISignal1 sig, IState2 state);
}
I would like to remove the instanceof checks and replace with generics or redesign, but without adding more methods to IAction. I see how to do this with reflection, but would like to avoid if possible.
Edit: Removed generics since they are not required. I will try and explain more to give a better idea of this approach. The IActionAbstract file might be generated with the developer making an impl to implement the methods. ISignal and IState together make the method unique and can be thought of as a state machine state and signal.
Usage of the classes would look like in pseudo-code:
List<IAction> actions;
actions.get(i).doAction(ISignal1, IState1);
actions.get(i).doAction(ISignal2, IState2);
and so on...

Looks to me like you want separate implementations of IAction, i.e.
// generic interface declaration
public interface IAction<T extends ISignal, S extends IState> {
void doAction(T sig, S state);
}
// typed implementations of the generic interface
public class Action1 implements IAction<Signal1, State1> {
doAction(Signal1 sig, State1 state) {
// impl
}
}
// another typed implementations of the generic interface
public class Action2 implements IAction<Signal2, State2> {
doAction(Signal2 sig, State2 state) {
// impl
}
}
...and so on. Otherwise you're not even using generics.

I'm not quite sure what you're looking for. I agree with #claesv that your approach probably isn't necessary. Here is my approach:
public class GenericsQuestion {
public static void main(String[] args) {
ISignal sig = new Signal1();
IState state = new State1();
Strategy.getStrategyForSignalAndState(sig.getClass(), state.getClass()).doOther(sig, state);
}
}
class SignalAndState {
private Class<? extends IState> state;
private Class<? extends ISignal> signal;
/**
*
*/
public SignalAndState(Class<? extends ISignal> signal, Class<? extends IState> state2) {
// save state and signal
}
// equals & hashcode
}
enum Strategy {
ONE {
#Override
public void doOther(ISignal sig, IState state) {
}
},
TWO {
#Override
public void doOther(ISignal sig, IState state) {
}
},
THREE {
#Override
public void doOther(ISignal sig, IState state) {
}
};
private static final Map<SignalAndState, Strategy> STRATEGIES = new HashMap<SignalAndState, Strategy>();
static {
STRATEGIES.put(new SignalAndState(Signal1.class, State1.class), ONE);
STRATEGIES.put(new SignalAndState(Signal1.class, State2.class), TWO);
STRATEGIES.put(new SignalAndState(Signal2.class, State1.class), THREE);
}
public static Strategy getStrategyForSignalAndState(Class<? extends ISignal> sig, Class<? extends IState> state) {
return STRATEGIES.get(new SignalAndState(sig, state));
}
public abstract void doOther(ISignal sig, IState state);
}
I my eyes, this would be more elegant and flexible than using instanceof.
You could probably improve this by using EnumMap, but I don't use that much and am unsure about the benefits and/or usage. Just a hint if you'd like to investigate further.

Related

How to implement pattern matching in java and avoid instanceof?

At the moment I don't know how to avoid code smells in my piece of code.
I've tried several patterns (Strategy, Visitor) and they didn't provide a clean and maintainable solution. Here is an example of my code for strategy pattern:
public interface Strategy {
<T> T foo(FirstParam firstParam, SecondParam secondParam);
}
public class StrategyOne implements Strategy {
FirstReturnType foo(FirstParam firstParam, SecondParam secondParam);
}
public class StrategyTwo implements Strategy {
SecondReturnType foo(FirstParam firstParam, SecondParam secondParam);
}
#Setter
public class Context {
private Strategy strategy;
public void execute(FirstParam firstParam, SecondParam secondParam) {
if (strategy != null) {
strategy.fo(firstParam, secondParam);
}
}
}
And there is a example of objects.
public abstract class Action {
abstract void bar();
}
public class ActionOne extends Action {
void bar() {}
}
public class ActionTwo extends Action {
void bar() {}
}
And I want to make this piece of code cleaner
public class ActionExecutor {
private Context context;
private FirstParam firstParam;
private SecondParam secondParam;
public ActionExecutor(FirstParam firstParam, SecondParam secondParam) {
this.context = new Context();
this.firstParam = firstParam;
this.secondParam = secondParam;
}
public void doSmth(Item item) {
Action action = item.getAction();
if(action instanceof ActionOne) {
context.setStrategy(new StrategyOne());
}
if(action instanceof ActionTwo) {
context.setStrategy(new StrategyTwo());
}
context.execute(firstParam, secondParam);
}
}
The idea is to perform a specific action for a specific object type. But I don't know how to avoid the usage of instanceof in this situation.
Two ways top of my head.
public abstract class Action {
public Strategy strategy;
abstract void bar();
}
public class ActionOne extends Action {
void bar() {}
// set strategy here, possibly
}
public class ActionTwo extends Action {
void bar() {}
}
public void doSmth(Item item) {
Action action = item.getAction();
action.strategy.execute(firstParam, secondParam);
}
Second way, have an enum in all your actions and force it by declaring it as a parameter in your abstract class constructor. Then just use switch in instead of instanceof
Could be something like this:
public void doSmth(Item item) {
Action action = item.getAction();
Map<String,Strategy> strategies = new HashMap<>();
strategies.put(ActionOne.getClass().getSimpleName(),new StrategyOne());
strategies.put(ActionTwo.getClass().getSimpleName(),new StrategyTwo());
..
strategies.put(ActionHundred.getClass().getSimpleName(),new StrategyHundred());
if(strategies.containsKey(action.getClass().getSimpleName())) {
context.setStrategy(strategies.get(action.getClass().getSimpleName()));
}
context.execute(firstParam, secondParam); }
This seems like a textbook use case for the Factory Method pattern. You can use the same code you have now (or the Map example in another answer), but put it in a factory - then it's purpose-specific and decoupled from the code that uses it.
Something like this.
public class StrategyFactory {
public static Stategy getStrategy(Action action) {
if(action instanceof ActionOne) {
return new StrategyOne();
} else if(action instanceof ActionTwo) {
return new StrategyTwo();
}
}
}
And then, something like this.
Action action = item.getAction();
action.setStrategy(StrategyFactory.getStrategy(action));
There's another example here: https://dzone.com/articles/design-patterns-the-strategy-and-factory-patterns

Abstract method with different parameters Java

public abstract class CommonClass {
abstract void send(<what should i put here???>) {}
}
public class ClassA extends CommonClass {
void send(List<Comments> commentsList) {
// do stuff
}
}
public class ClassB extends CommonClass {
void send(List<Post> postList) {
// do stuff
}
}
I am new to OODP, I am trying to have a method that is able to take in any kind of List data so that I can abstract things out. How can i do this?
You could make it generic on some type T. Like,
public abstract class CommonClass<T> {
abstract void send(List<T> al);
}
And then, to implement it - use the generic. Like,
public class ClassA extends CommonClass<Comments> {
#Override
void send(List<Comments> commentsList) {
// do stuff
}
}
public class ClassB extends CommonClass<Post> {
#Override
void send(List<Post> postList) {
// do stuff
}
}
Also, as discussed in the comments, your class names could be improved to be more intuitive; something like,
public abstract class AbstractSender<T> {
abstract void send(List<T> al);
}
and then
public class CommentSender extends AbstractSender<Comment> {
#Override
void send(List<Comment> commentsList) {
// do stuff
}
}
public class PostSender extends AbstractSender<Post> {
#Override
void send(List<Post> postList) {
// do stuff
}
}
That has the advantage(s) of being more readable and easier to reason about (I can tell what a PostSender does by reading the name, ClassB not so much).
Finally, this looks like a case where an interface would work since your abstract class is purely virtual (and should be preferred since you can implement multiple interface, but can only extend from a single parent class);
public interface ISender<T> {
void send(List<T> al);
}
public class CommentSender implements ISender<Comment> {
#Override
void send(List<Comment> commentsList) {
// do stuff
}
}
public class PostSender implements ISender<Post> {
#Override
void send(List<Post> postList) {
// do stuff
}
}
In order to achieve this, you can take multiple approaches, I would suggest looking into Generics: https://docs.oracle.com/javase/tutorial/java/generics/index.html
With that said, there is one approach that is the most elegant and simple: you can supply a List<T> where T is a generic type.
public abstract class CommonClass<T> {
abstract void send(List<T>) {}
}
public class ClassA extends CommonClass<Comment> {
void send(List<Comments> commentsList) {
// do stuff
}
}
public class ClassB extends CommonClass<Post> {
void send(List<Post> postList) {
// do stuff
}
}
You can do that with the help of generics. https://www.tutorialspoint.com/java/java_generics.htm
Example
The abstract class
public abstract class CommonClass {
public abstract <T> void send(List<T> data);
}
Its child
public class Child extends CommonClass {
public <T> void send(List<T> data) {
// code here
}
}
Retrieving the list's contents
Retrieving the generified list's contents is similar to retrieving any list's contents. In the scope of the method, "T" is a type of object contained in the list.
for (T t : data) {
// to check if t is a string
if (t instanceof String) {
// code
}
}
You can also use lambdas to retrieve every element in the list.

Sad logic on types

Code base is littered with code like this:
BaseRecord record = // some BaseRecord
switch(record.source()) {
case FOO:
return process((FooRecord)record);
case BAR:
return process((BarRecord)record);
case QUUX:
return process((QuuxRecord)record);
.
. // ~25 more cases
.
}
and then
private SomeClass process(BarRecord record) { }
private SomeClass process(FooRecord record) { }
private SomeClass process(QuuxRecord record) { }
It makes me terribly sad. Then, every time a new class is derived from BaseRecord, we have to chase all over our code base updating these case statements and adding new process methods. This kind of logic is repeated everywhere, I think too many to add a method for each and override in the classes. How can I improve this?
First solution: good old polymorphism.
Simply add an abstract process() method to the BaseRecord class, and override it in every subclass. The code will thus become:
BaseRecord record = ...;
record.process();
If you can't add the process() method into the BaseRecord class (and its subclasses), then implement the visitor pattern. It will leave the process method outside of the BaseRecord class, but each time you add a new subclass, you'll be forced to modify the Visitor interface, and all its implementations. The compiler will thus check for you that you haven't forgotten a case somwhere in a switch.
public interface RecordVisitor<T> {
T visitFoo(FooRecord foo);
T visitBar(BarRecord foo);
...
}
public abstract class BaseRecord {
public abstract <T> T accept(RecordVisitor<T> visitor);
}
public class FooRecord extends BaseRecord {
#Override
public <T> T accept(RecordVisitor<T> visitor) {
return visitor.visitFoo(this);
}
}
public class BarRecord extends BaseRecord {
#Override
public <T> T accept(RecordVisitor<T> visitor) {
return visitor.visitBar(this);
}
}
Now you simply have to implement RecordVisitor for each block of logic described in the question:
RecordVisitor<Void> visitor = new ProcessRecordVisitor();
record.accept(visitor);
Both Visitor Pattern and Strategy pattern can be put in use here. http://en.wikipedia.org/wiki/Strategy_pattern and http://en.wikipedia.org/wiki/Visitor_pattern
I think this is instructive:
package classplay;
public class ClassPlay
{
public void say(String msg) { System.out.println(msg); }
public static void main(String[] args)
{
ClassPlay cp = new ClassPlay();
cp.go();
}
public void go()
{
A someClass = new C();
say("calling process with double dispatch");
someClass.dueProcess(this);
say("now calling process directly");
process(someClass);
}
public void process(A a)
{
say("processing A");
a.id();
}
public void process(B b)
{
say("processing B");
b.id();
}
public void process(C c)
{
say("processing C");
c.id();
}
abstract class A
{
abstract public void id(); // { System.out.println("Class A"); }
public void dueProcess(ClassPlay cp) { cp.process(this); }
}
class B extends A
{
public void id() { System.out.println("Class B"); }
public void dueProcess(ClassPlay cp) { cp.process(this); }
}
class C extends A
{
public void id() { System.out.println("class C"); }
public void dueProcess(ClassPlay cp) { cp.process(this); }
}
}

Implementing a generic factory

I am trying to design a factory for a pluggable interface. The idea is that once you have your factory instance, the factory will return the appropriate subclasses for that particular implementation.
In this case, I am wrapping a third party library that uses a String to represent an ID code, rather than subclasses. Therefore, in the implementation that wraps their library, every implementation class has a method getCode() that is not explicitly required by the interface API. I am using an enum to store this mapping between codes and interface classes.
In nearly all cases, the getCode() method is not needed. However, in just a few situations in the implementation package, I need access to that method. Therefore, my problem is that I would like to have the Factory implementation's signature tell callers that the getCode method exists if they have a reference to the specific Factory implementation.
What follows is a lot of code in my best-effort attempt to digest the situation into an sscce. I know it's very long, but it's simpler than it seems, and one of the words in sscce is "complete".
Public API:
public interface Factory {
public <T extends IFoo> T makeIFoo(Class<T> klass);
}
public interface IFoo {
void doSomething();
}
public interface IFooBar extends IFoo {
void doBarTask();
}
public interface IFooBaz extends IFoo {
void doBazTask();
}
Sample use case:
public class SomeClass {
private Factory myFactory;
public void doSomething() {
IFooBar ifb = myFactory.create(IFooBar.class);
}
}
SSCCE version of implementation:
interface ICode {
String getCode();
}
abstract class BaseCode implements IFoo, ICode {
private String code;
BaseCode(String code) {
this.code = code;
}
#Override
public String getCode() {
return code;
}
#Override
public void doSomething() {
System.out.println("Something");
}
}
class FooBarImpl extends BaseCode implements ICode, IFooBar {
FooBarImpl(String code) {
super(code);
}
#Override
public void doBarTask() {
System.out.println("BarTask");
}
}
class FooBazImpl extends BaseCode implements ICode, IFooBaz {
FooBazImpl(String code) {
super(code);
}
#Override
public void doBazTask() {
System.out.println("BarTask");
}
}
Enum codemapper:
static enum CodeMap {
FOOBAR ("A", IFooBar.class) {
FooBarImpl create() { return new FooBarImpl(getCode()); }
},
FOOBAZ ("B", IFooBaz.class) {
FooBazImpl create() { return new FooBazImpl(getCode()); }
};
private static Map<Class<? extends IFoo>, CodeMap> classMap;
static {
classMap = new HashMap<Class<? extends IFoo>, CodeMap>();
for(CodeMap cm : CodeMap.values()) {
classMap.put(cm.getFooClass(), cm);
}
}
private String code;
private Class<? extends IFoo> klass;
private CodeMap(String code, Class<? extends IFoo> klass) {
this.code = code;
this.klass = klass;
}
String getCode() {
return code;
}
Class<? extends IFoo> getFooClass() {
return klass;
}
static CodeMap getFromClass(Class<? extends IFoo> klass) {
return classMap.get(klass);
}
abstract BaseCode create();
}
Sample use case within implementation package:
public class InternalClass {
CodeFactory factory;
public void doSomething() {
FooBarImpl fb = factory.makeIFoo(IFooBar.class);
}
}
Attempt at factory:
This does not specify that the return will always implement ICode. But the passed-in interface class DOESN'T implement ICode, that's the whole point.
class CodeFactory implements Factory {
#Override
public <T extends IFoo> T makeIFoo(Class<T> klass) {
CodeMap map = CodeMap.getFromClass(klass);
if (map == null) return null; // Or throw an exception, whatever, SSCCE
return (T) map.create();
}
}
What should I do?
I realized I was making this too complicated. If I'm going to implement a factory method for each enum instance, I may as well just have separate factory methods for each interface.
public interface Factory {
IFooBar createFooBar();
IFooBaz createFooBaz();
}
class CodeFactory implements Factory {
public FooBarImpl createFooBar() {
// etc.
}
}
Of course now I have to change the Factory API if there are ever new interfaces, but I expect that will be rare.
A possible solution would be defining a wrapper that implements IFoo and the getCode() method, and your method would return the intended class in one of such wrappers.
If the wrapped instance has a getCode implemented, the wrapper would return its value, return it, otherwise return null.

How would I overload method in an interface?

if I have this interface
public interface someInterface {
// method 1
public String getValue(String arg1);
// method 2
public String getValue(String arg1, String arg2);
}
I want to be able to pass in 1 or 2 string to the getValue method without having to override both in each implementing class.
public class SomeClass1 impelments someInterface
{
#Override
public String getValue(String arg1);
}
public class SomeClass2 implements someInterface
{
#Override
public String getValue(String arg1, String arg2);
}
this won't work because SomeClass1 needs to implement method 2 and SomeClass2 needs to implement method 1.
Am I stuck doing this?
public interface someInterface2 {
public String getValue(String... args);
}
public class SomeClass3 implements someInterface2
{
#Override
public String getValue(String... args) {
if (args.length != 1) {
throw IllegalArgumentException();
}
// code
}
}
public class SomeClass4 implements someInterface2
{
#Override
public String getValue(String... args) {
if (args.length != 2) {
throw IllegalArgumentException();
}
// code
}
}
someInterface2 someClass3 = new SomeClass3();
someInterface2 someClass4 = new SomeClass4();
String test1 = someClass3.getValue("String 1");
String test2 = someClass4.getValue("String 1, "String 2");
Is there a better way of doing this?
An interface serves as a contract for the users of that interface: you specify what methods are available (in all implementations) and how they are called. If two implementations of an interface need a different method, then that method should not be part of the interface:
public interface Lookup {
}
public class MapLookup implements Lookup {
public String getValue(String key) {
//...
}
}
public class GuavaLookup implements Lookup {
public String getValue(String row, String column) {
// ...
}
}
In your program, you will know which implementation you use, so you can simply call the right function:
public class Program {
private Lookup lookup = new MapLookup();
public void printLookup(String key) {
// I hardcoded lookup to be of type MapLookup, so I can cast:
System.out.println(((MapLookup)lookup).getValue(key));
}
}
Alternative approach
If your class Program is more generic and uses dependency injections, you may not know which implementation you have. Then, I would make a new interface Key, which can be either type of key:
public interface Lookup {
// ...
public String getValue(Key key);
}
public interface Key {
}
public MapKey implements Key {
private String key;
// ...
}
public GuavaKey implements Key {
private String row, column;
// ...
}
The dependency injection in your program might come from some factory implementation. Since you cannot know which type of lookup you use, you need a single contract for getValue.
public interface Factory {
public Lookup getLookup();
public Key getKey();
}
public class Program {
private Lookup lookup;
public Program(Factory factory) {
lookup = factory.getLookup();
}
public void printLookup(Factory factory) {
System.out.println((lookup.getValue(factory.getKey()));
}
}
As of Java 8, you can have an interface provide an implementation of a method, through the use of the default keyword. Therefore a new solution would be to provide a default implementation of both methods which maybe throws an exception, then derive the actual implementation from the default interface.
Anyways here is how you can do this:
public interface SomeInterface {
// method 1
default String getValue(String arg1) {
// you decide what happens with this default implementation
}
// method 2
default String getValue(String arg1, String arg2) {
// you decide what happens with this default implementation
}
}
Finally, make the classes override the correct methods
public class SomeClass1 implements SomeInterface {
#Override
public String getValue(String arg1) {
return arg1;
}
}
public class SomeClass2 implements SomeInterface {
#Override
public String getValue(String arg1, String arg2) {
return arg1 + " " + arg2;
}
}
A solution (not very elegant) might look loke this:
public abstract class SomeClass {
public String getValue(String arg1) {
throw new IllegalArgumentException();
}
public String getValue(String arg1, String arg2) {
throw new IllegalArgumentException();
}
}
public class SomeClass1 extends SomeClass {
public String getValue(String arg1) {
// return sth
}
}
public class SomeClass2 extends SomeClass {
public String getValue(String arg1, String arg2) {
// return sth
}
}
However there's a drawback - SomeClass1 and SomeClass2 can't inherit directly other class.
If the second value can be considered optional in a sense and you always have the 2 arguments when calling you could create a wrapper class which implements the 2 parameter interface passing the 1 parameter implementation as a constructor parameter and calling that in the method, e.g. something like this:
interface A{
method1(P1)
}
interface B{
method2(P1, P2)
}
class Wrap implements B{
Wrap(A impl)
override method2(P1, P2){
call impl.method1(P1)
}
}
public interface SomeInterface {
default void print(String s) {
System.out.println(s);
}
}
public class SomeClass implements SomeInterface {
/**
* Note the this overloads {#link SomeInterface#print(String)},
* not overrides it!
*/
public void print(int i) {
System.out.println(i);
}
}

Categories

Resources