Method overloading vs factory - java

Lets say we need some logic change in multiple methods of multiple classes on basis of a flag, while keeping backwards compatibility.
There are two ways..
1.overload every method in every class. then end up with an if-else ladder in caller code to call correct method.
2.Make a common interface and a Factory. Return objects of either on basis of flag passed to factory. Callers don't need any change. only a little change is needed while object creation. Is it logical to create factory for two types only ?
Based on your experience which will you choose ? How to decide between these two ways ? Any better approach you can suggest ?

Logic change suggests behavior which suggests the Strategy Pattern. This avoids a change to the existing method signature.
But you can still use a factory to centralize the creation of the concrete strategy object which handles the logic.
import java.util.Random;
public class App {
public static void main(String[] args) {
App app = new App();
app.calculateSomething(new Random().nextBoolean());
}
private void calculateSomething(boolean isUsingLegacyLogic) {
CalculationStrategyFactory factory = new CalculationStrategyFactory();
CalculationStrategy strategy = factory.getCalculationStrategy(isUsingLegacyLogic);
Calculator calculator = new Calculator(strategy);
calculator.calculate();
}
class Calculator {
CalculationStrategy calculationStrategy;
Calculator(CalculationStrategy calculationStrategy) {
this.calculationStrategy = calculationStrategy;
}
// ...
public double calculate() {
// original code
// ...
// System.out.println("Calculation steps were done in sequential order.");
// return 0;
return calculationStrategy.calculate(this);
}
}
private interface CalculationStrategy {
double calculate(Calculator c);
}
private class SequentialCalculationHandler implements CalculationStrategy {
public double calculate(Calculator c) {
// ...
System.out.println("Calculation steps were done in sequential order.");
return 0;
}
}
private class ParallelCalculationHandler implements CalculationStrategy {
public double calculate(Calculator c) {
// ...
System.out.println("Calculation steps were done in parralel.");
return 0;
}
}
private class CalculationStrategyFactory {
public CalculationStrategy getCalculationStrategy(boolean isUsingLegacyLogic) {
if (isUsingLegacyLogic || Runtime.getRuntime().availableProcessors() == 1) {
return new SequentialCalculationHandler();
}
return new ParallelCalculationHandler();
}
}
}

Related

How to create a new object based on interface implementation

Firstly, I believe my question is badly worded but don't really understand how to phrase it.
I have a starting interface that is being implemented by a number of classes. What I want to do is to see if there is a way to create a new object such that I am being passed the generic interface, then based on the method .getClass().getSimpleName(), create a new object based on that string.
Is the only way to create a switch case statement? As the number of implementing classes are too many (about 100 or so).
Reference code:
public interface MyInterface {
public void someMethod();
}
then I would have my implementing classes:
public class MyClass1 implements MyInterface {
public void someMethod() { //statements }
}
public class MyClass2 implements MyInterface {
public void someMethod() { //statements }
}
public class MyClass3 implements MyInterface {
public void someMethod() { //statements }
}
What I want to have in the end is another class which is passed an argument of type MyInterface, get the simple name from that and create a new instance of MyClassX based on that simple name.
public class AnotherClass {
public void someMethod(MyInterface interface) {
if (interface == null) {
System.err.println("Invalid reference!");
System.exit(-1);
} else {
String interfaceName = interface.getClass().getSimpleName();
/**
* This is where my problem is!
*/
MyInterface newInterface = new <interfaceName> // where interfaceName would be MyClass1 or 2 or 3...
}
}
}
Any help is highly appreciated!
You can use reflection for this:
public void someMethod(MyInterface myInterface) {
Class<MyInterface> cl = myInterface.getClass();
MyInteface realImplementationObject = cl.newInstance(); // handle exceptions in try/catch block
}
This is a common problem with many solutions. When I face it, I never use reflection because it is difficult to maintain if it is part of a big project.
Typically this problem comes when you have to build an object based on a user selection. You can try a Decorator pattern for that. So, instead of building a different object for each option. You can build a single object adding functionality depending on a selection. For instance:
// you have
Pizza defaultPizza = new BoringPizza();
// user add some ingredients
Pizza commonPizza = new WithCheese(defaultPizza);
// more interesting pizza
Pizza myFavorite = new WithMushroom(commonPizza);
// and so on ...
// then, when the user checks the ingredients, he will see what he ordered:
pizza.ingredients();
// this should show cheese, mushroom, etc.
under the hood:
class WithMushroom implements Pizza {
private final Pizza decorated;
public WithMushroom(Pizza decorated) {
this.decorated = decorated;
}
#Override
public Lizt<String> ingredients() {
List<String> pizzaIngredients = this.decorated.ingredients();
// add the new ingredient
pizzaIngredients.add("Mushroom");
// return the ingredients with the new one
return pizzaIngredients;
}
}
The point is that you are not creating an object for each option. Instead, you create a single object with the required functionality. And each decorator encapsulates a single functionality.

How to change multiple main variables at the same time in Java

In my understanding of Java, the most common ways to set the instance variables of a class object are:
foo.setFooStuff(bar); // put a setter method inside the class
foo = modifyFooStuff(foo, bar); // pass & return entire object
Let's say my main() has an object of class bigA, which contains a collection of class littleA objects (which contain instance variables), and another object of class bigB, which contains a collection of class littleB objects (which have different instance variables from littleA). How do I write a method to modify instance variables of one or more littleA and littleB objects at the same time?
(Note: I suspect this is a common question, but I searched and didn't find it. Maybe I'm using the wrong terminology.)
Edit: more concrete example: Let's say I'm making Monopoly. A player has money (in various denominations) and properties (some with houses). She wants to upgrade some properties to hotels. Money has to be added and subtracted, as do houses and hotels. I know how to do this in a pass-by-reference language, but not using pass-by-value, unless I make the entire game state into one huge object and pass it around, which seems like a lot of memory shuffling and basically the same as using global variables, which is bad, right?
If I understand your question correctly, you write a method on the bigA/bigB classes that take the value you want to set and then walk the collection of littleA/B objects setting the instance variables as you go. Like:
// Assuming Foo has a member collection of smallFoo
Foo A = new Foo();
// do stuff that populates the collection of smallFoo in A
A.setSmallFooZipCode("23444");
public void setSmallFooZipCode(String zip_ {
// for thisSmallFoo in smallFoo
thisSmallFoo.setZip(zip);
// end for
)
Objects (including your container objects) should represent something--thinking of them in terms of A/B makes this a little tough.
On top of that, if you are always modifying an attribute in two classes at once I'd suggest that's a pretty bad code smell...
Off the top of my head I can't think of anything I'd model this way, so it's hard to come up with an example. Either A and B should be contained in a parent ab class (and that class should have the attribute), or a and b should be the same interface--in either case these would then go into a single collection in a parent container.
So that said, you should have a method on the parent container object that does the work. In most cases it shouldn't be a method like "setAttribute...", it should be a method like "doAction". In other words, if your container is a "Herd" and it contains a bunch of Elephants, then you would tell the Herd to move to a certain location and let the Herd object send a message to each elephant telling it where to go.
If you think of methods in terms of "Asking an object to do something for you" rather than operating on an object, it helps make some of these decisions much easier.
You would simply encapsulate BigA and BigB in another object:
class BigWrapper {
private BigA bigA;
private BigB bigB;
public void someMethod() {
bigA.someMethod();
bigB.someMethod();
}
}
someMethod() within BigA would modify the LittleA instances. Same for BigB:
class BigB {
private LittleA[] littles;
public void someMethod() {
//do something with the littles
}
}
Of course, this solution doesn't allow you to specify which Little instances to target, as well as doesn't allow you to specify which behavior should be performed (which specific method to invoke via the littles).
If you want that flexibility, use callbacks:
interface Little { }
class LittleA implements Little { }
class LittleB implements Little { }
interface Callback<T extends Little> {
void perform(int currentIndex, T currentLittle);
}
class CallbackHandler<T extends Little> {
private int[] indexes;
private Callback<T> callback;
public CallbackHandler(int[] indexes, Callback<T> callback) {
this.indexes = indexes;
this.callback = callback;
}
public void perform(T[] littles) {
for(int i = 0; i < indexes.length; i++) {
int index = indexes[i];
callback.perform(i, littles[index]);
}
}
}
class BigWrapper {
private BigA bigA;
private BigB bigB;
public BigWrapper(BigA bigA, BigB bigB) {
this.bigA = bigA;
this.bigB = bigB;
}
public void perform(CallbackHandler<LittleA> aCallback, CallbackHandler<LittleB> bCallback) {
bigA.perform(aCallback);
bigB.perform(bCallback);
}
}
class BigA {
private LittleA[] littles;
public BigA(LittleA[] littles) {
this.littles = littles;
}
public void perform(CallbackHandler<LittleA> callback) {
callback.perform(littles);
}
}
class BigB {
private LittleB[] littles;
public BigB(LittleB[] littles) {
this.littles = littles;
}
public void perform(CallbackHandler<LittleB> callback) {
callback.perform(littles);
}
}
The CallbackHandler maps the actual callback to the indexes you want to target.
So you would first create the callback:
Callback<LittleA> aCallback = (currentIndex, currentLittle) -> {
//do what you want to the littles
};
Then pass that to a CallbackHandler, which allows you to specify the indexes you wish to target:
int[] indexes = { 0, 1, 2 };
CallbackHandler<LittleA> aCallbackHandler = new CallbackHandler<>(indexes, aCallback);
BigWrapper exposes a perform(CallbackHandler<LittleA>, CallbackHandler<LittleB>), so you would pass the handlers to that method.
An MCVE would look like:
public static void main(String[] args) {
LittleA[] littleA = {
new LittleA(),
new LittleA(),
new LittleA()
};
LittleB[] littleB = {
new LittleB(),
new LittleB(),
new LittleB()
};
BigA bigA = new BigA(littleA);
BigB bigB = new BigB(littleB);
BigWrapper big = new BigWrapper(bigA, bigB);
Callback<LittleA> aCallback = (index, little) -> {
//...
};
Callback<LittleB> bCallback = (index, little) -> {
//...
};
CallbackHandler aCallbackHandler = new CallbackHandler(new int[] { 2, 3, 4 }, aCallback);
CallbackHandler bCallbackHandler = new CallbackHandler(new int[] { 5, 6, 7 }, bCallback);
big.perform(aCallbackHandler, bCallbackHandler);
}

getting correct objects from string parameter in factory

I've been trying to figure out if theres a way to pass a string to a factory or constructor and create the correct object without having to map the string to an object, or without having a bunch of if/else statements or switch statements.
Keep in mind, this is a simple example so I can apply what I learn to more complicated situations in web apps, etc.
let's take a simple calculator app, written in JAVA, as an example
assuming this is command line, and a person can pass in 3 values
- first number
- math operation (+ , - , / , x)
- second number
and we have an interface
public interface ArithmeticOperation {
public double performMathOperation(double firstNum, double secondNum);
}
with 4 classes that implement it
public class AdditionOperation implements ArithmeticOperation {
public double performMathOperation(double firstNum, double secondNum) {
return firstNum + secondNum;
}
}
// public class Subtraction operation returns firstNum - secondNum
// etc...
and we have our actual Calculator class and UserInput class
public class UserInput {
public UserInput(double firstNum, double secondNum, String operation) {
this.firstNum = firstNum;
// etc...
}
}
public class Calculator {
public UserInput getInput() {
// get user input, and return it as a UserInput object
// return a UserInput object
}
public performOperation() {
UserInput uInput = getInput();
double answer = ArithmeticOperationFactory
.getSpecificOperation(uInput.operation)
.performMathOperation(uInput.firstNum, uInput.secondNum);
// send answer back to user
}
}
finally, the place where the question mostly revolves around, the factory
public class ArithmeticOperationFactory {
public static ArithmeticOperation getSpecificOperation(String operation) {
// what possibilities are here?
// I don't want a map that maps strings to objects
// I don't want if/else or switch statements
// is there another way?
}
}
also, if theres a better way to architect a system like this or a design pattern that can be applied, please share. I'm really trying to learn some good object oriented design
There is a different way. I'm not sure it's better.
We have to go back to the interface and add another method so that the class can identify the operator.
public interface ArithmeticOperation {
public boolean isOperator(String operator);
public double performMathOperation(double firstNum, double secondNum);
}
We code the concrete methods like this:
public class AdditionOperation implements ArithmeticOperation {
#Override
public boolean isOperator(String operator) {
return operator.equals("add");
}
#Override
public double performMathOperation(double firstNum, double secondNum) {
return firstNum + secondNum;
}
}
We put all of the ArithmeticOperation classes in a List
List<ArithmeticOperation> operations = new ArrayList<>();
operations.add(new AdditionOperation());
...
Finally, we perform the operation like this.
double answer = 0D;
for (ArithmeticOperation operation : operations) {
if (operation.isOperator(currentOperator) {
answer = operation.performMathOperation(firstNum, secondNum);
break;
}
}
I would implement it using switch case. This is Factory Design Pattern.
class ArithmeticOperationFactory {
public static ArithmeticOperation getSpecificOperation(String operation) {
switch (operation) {
case "ADD":
return new AdditionOperation();
case "SUBTRACT":
return new SubtractOperation();
// You can define the rest of the operation here.
default:
throw new UnsupportedOperationException("OPeratino is not supported: " + operation);
}
}
}
You can also define Enum for each operation and use them in switch-case.
There is no method which is much better than solutions you have seen before. You can only make it slightly more elegant. In essence you can have:
Bunch of if/else/switch (probably least elegant but fast)
if("typeAsString").equals("operation"){
return new SomeType()
}
Map
Map<String, Class<? extends YourType> map = new HashMap<>();
You can make it bit better with dependency injection or you can make each subclass to add its own entry in this map. I'd favor keeping configuration away from factory class and moving it to subclasses.
Kind of chain of responsibility
You have to create Collection of all your subtypes. Each subtype has to have method like isItCorrectSubtype(). Client class has to iterate through whole collection and check which implementation is correct
#Autowired
List<InterfaceOfYourTypes> allSubtypes;
..
public void doStuff(){
for(InterfaceOfYourTypes subtype: allSubtypes){
if(subtype.isCorrectSubtype()){
//create instance
}
}
}
What are you asking for is a mapping operation because you have a String as input and you want an Object implementing and interface (ArithmeticOperation) back. If a mpa dose not fit you needs you must "configure" the mapping in a different way, this is my suggestion:
Change the interface to
public interface ArithmeticOperation {
public double performMathOperation(double firstNum, double secondNum);
public double getName();
}
Your add operation will result as the following one:
public class AdditionOperation implements ArithmeticOperation {
public double performMathOperation(double firstNum, double secondNum) {
return firstNum + secondNum;
}
public double getName() {
return "+";
}
}
In you method factory all you need is to find all the classes implementing the ArithmeticOperation interface; something like:
public class ArithmeticOperationFactory {
private List<ArithmeticOperation> availableOperations=null;
//to be called at application startup
public static void findAvailableOperations() {
// a strategy for finding implementations that fills
// availableOperations
}
public static ArithmeticOperation getSpecificOperation(String operation) {
for (ArithmeticOperation arithmeticOperation : availableOperations) {
if (operation.equalsIngoreCase(arithmeticOperation.getName)) {
return arithmeticOperation;
}
}
}
Here are some method you can yous to implement findAvailableOperations:
If you are using Spring you can get the api getBeansOfType and retrieve all the implementations (I'm assuming you are configuring the concrete operations as Spring beans).
If you are not using spring you can scan the classpath in order to find the classes that implement your interface; you can start from this project or this one.
Another solution is to put the implementation class names into a file (.properties, .xml, .json, etc), read the class names and create them via reflection.
You could use a Factory like this
public class ArithmeticOperationFactory {
public static ArithmeticOperation getSpecificOperation(String operation) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
return (ArithmeticOperation) resolveClass(operation).newInstance();
}
private static Class resolveClass(String className) throws ClassNotFoundException {
return Class.forName(className);
}
}

The pattern of final array instead of non-final variable for boolean flag in inner class

I often have a situation in my Java code when I need to set a boolean flag inside an inner class. It is not possible to use primitive boolean type for that, because inner class could only work with final variables from outside, so I use pattern like this:
// class from gnu.trove is not of big importance, just to have an example
private final TIntIntHashMap team = new TIntIntHashMap();
// ....... code ............
final boolean[] flag = new boolean[]{false};
team.forEachValue(new TIntProcedure() {
#Override
public boolean execute(int score) {
if(score >= VICTORY_SCORE) {
flag[0] = true;
}
return true; // to continue iteration over hash map values
}
});
// ....... code ..............
The pattern of final array instead of non-final variable works well, except it is not look beautiful enough to me. Does someone know better pattern in Java ?
Use AtomicBoolean.
Here's a popular StackOverflow question about this issue: Why are only final variables accessible in anonymous class?
How about having a generic holder class which holds object of any type. In your case, it can hold a Boolean type. Something like:
class Holder<T> {
private T genericObj;
public Holder(T genericObj) {
this.genericObj = genericObj;
}
public T getGenericObj() {
return genericObj;
}
public void setGenericObj(T genericObj) {
this.genericObj = genericObj;
}
}
And use it as:
public class Test {
public static void main(String[] args) throws Exception {
final Holder<Boolean> boolHolder = new Holder<Boolean>(Boolean.TRUE);
new Runnable() {
#Override
public void run() {
boolHolder.setGenericObj(Boolean.FALSE);
}
};
}
}
Of course, this has the usual problems that occur with mutable objects that are shared across threads but you get the idea. Plus for applications where memory requirements are tight, this might get crossed off when doing optimizations in case you have a lot of invocations of such methods. Also, using AtomicReference to swap/set references should take care of use from multiple threads though using it across threads would still be a bit questionable.
There are situations where this is the best pattern.
The only improvement I can suggest is return false when you have found a match.
One problem is that the TIntIntHashMap does not have a fold/reduce method so you have to simulate it using foreach. You could try to write your own class extending TIntIntHashMap adding a reduce method.
Other solution is to just extend TIntProcedure to have a value. Something like:
abstract class TIntProcedureWithValue<T> implements TIntProcedure {
private T accumulator;
public T getValue() {return accumulator;}
}
Then you can pass an instance of this class to foreach, set the internal accumulator instead of the external flag array, and get the resulting value afterwards.
I am not familiar with gnu.trove, but generally it's better for the "algortihm" function to be more specific, leaving less code here.
private final IntIntHashMap team = new IntIntHashMap();
boolean found = team.value().containsMatch(new IntPredicate() {
public boolean is(int score) {
return score >= VICTORY_SCORE;
}
});
(More concise syntax should be available in Java SE 8.)
maybe something like that? (implements or extends... I don't know what is TIntProcedure, unfortunately) :
class FlagResult implements TIntProcedure {
boolean flag = false;
#Override
public boolean execute(int score) {
flag = score >= VICTORY_SCORE;
return !flag;
}
};
FlagResult result = new FlagResult();
team.forEachValue(result);
boolean flag = result.flag;

Array of function pointers in Java [duplicate]

This question already has answers here:
How to call a method stored in a HashMap? (Java) [duplicate]
(3 answers)
Closed 8 years ago.
I have read this question and I'm still not sure whether it is possible to keep pointers to methods in an array in Java. If anyone knows if this is possible (or not), it would be a real help. I'm trying to find an elegant solution of keeping a list of Strings and associated functions without writing a mess of hundreds of if statements.
Cheers
Java doesn't have a function pointer per se (or "delegate" in C# parlance). This sort of thing tends to be done with anonymous subclasses.
public interface Worker {
void work();
}
class A {
void foo() { System.out.println("A"); }
}
class B {
void bar() { System.out.println("B"); }
}
A a = new A();
B b = new B();
Worker[] workers = new Worker[] {
new Worker() { public void work() { a.foo(); } },
new Worker() { public void work() { b.bar(); } }
};
for (Worker worker : workers) {
worker.work();
}
You can achieve the same result with the functor pattern. For instance, having an abstract class:
abstract class Functor
{
public abstract void execute();
}
Your "functions" would be in fact the execute method in the derived classes. Then you create an array of functors and populate it with the apropriated derived classes:
class DoSomething extends Functor
{
public void execute()
{
System.out.println("blah blah blah");
}
}
Functor [] myArray = new Functor[10];
myArray[5] = new DoSomething();
And then you can invoke:
myArray[5].execute();
It is possible, you can use an array of Method. Grab them using the Reflection API (edit: they're not functions since they're not standalone and have to be associated with a class instance, but they'd do the job -- just don't expect something like closures)
Java does not have pointers (only references), nor does it have functions (only methods), so it's doubly impossible for it to have pointers to functions. What you can do is define an interface with a single method in it, have your classes that offer such a method declare they implement said interface, and make a vector with references to such an interface, to be populated with references to the specific objects on which you want to call that method. The only constraint, of course, is that all the methods must have the same signature (number and type of arguments and returned values).
Otherwise, you can use reflection/introspection (e.g. the Method class), but that's not normally the simplest, most natural approach.
I found the reflection approach the cleanest -- I added a twist to this solution since most production classes have nested classes and I didn't see any examples that demonstrates this (but I didn't look for very long either). My reason for using reflection is that my "updateUser()" method below had a bunch of redundant code and just one line that changed (for every field in the user object) in the middle that updated the user object:
NameDTO.java
public class NameDTO {
String first, last;
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
}
UserDTO.java
public class UserDTO {
private NameDTO name;
private Boolean honest;
public UserDTO() {
name = new NameDTO();
honest = new Boolean(false);
}
public NameDTO getName() {
return name;
}
public void setName(NameDTO name) {
this.name = name;
}
public Boolean getHonest() {
return honest;
}
public void setHonest(Boolean honest) {
this.honest = honest;
}
}
Example.java
import java.lang.reflect.Method;
public class Example {
public Example () {
UserDTO dto = new UserDTO();
try {
Method m1 = dto.getClass().getMethod("getName", null);
NameDTO nameDTO = (NameDTO) m1.invoke(dto, null);
Method m2 = nameDTO.getClass().getMethod("setFirst", String.class);
updateUser(m2, nameDTO, "Abe");
m2 = nameDTO.getClass().getMethod("setLast", String.class);
updateUser(m2, nameDTO, "Lincoln");
m1 = dto.getClass().getMethod("setHonest", Boolean.class);
updateUser(m1, dto, Boolean.TRUE);
System.out.println (dto.getName().getFirst() + " " + dto.getName().getLast() + ": honest=" + dto.getHonest().toString());
} catch (Exception e) {
e.printStackTrace();
}
}
public void updateUser(Method m, Object o, Object v) {
// lots of code here
try {
m.invoke(o, v);
} catch (Exception e) {
e.printStackTrace();
}
// lots of code here -- including a retry loop to make sure the
// record hadn't been written since my last read
}
public static void main(String[] args) {
Example mp = new Example();
}
}
You are right that there are no pointers in java because a reference variables are the same as the & syntax in C/C++ holding the reference to the object but no * because the JVM can reallocate the heap when necessary causing the pointer to be lost from the address which would cause a crash. But a method is just a function inside a class object and no more than that so you are wrong saying there are no functions, because a method is just a function encapsulated inside an object.
As far as function pointers, the java team endorses the use of interfaces and nested classes which all fine and dandy, but being a C++/C# programmer who uses java from time to time, I use my Delegate class I made for java because I find it more convenient when I need to pass a function only having to declare the return type of the method delegate.
It all depends on the programmer.
I read the white pages on why delegates are not support but I disagree and prefer to think outside the box on that topic.

Categories

Resources