I have a complex class and I want to simplify it by implementing a facade class (assume I have no control on complex class). My problem is that complex class has many methods and I will just simplify some of them and rest of the will stay as they are. What I mean by "simplify" is explained below.
I want to find a way that if a method is implemented with facade then call it, if not then call the method in complex class. The reason I want this is to write less code :) [less is more]
Example:
Facade facade = // initialize
facade.simplified(); // defined in Facade class so call it
// not defined in Facade but exists in the complex class
// so call the one in the complex class
facade.alreadySimple();
The options that comes to mind mind are:
Option 1: Write a class holding a variable of complex class and implement complex ones then implement simple ones with direct delegation:
class Facade {
private PowerfulButComplexClass realWorker = // initialize
public void simplified() {
// do stuff
}
public void alreadySimple() {
realWorker.alreadySimple();
}
// more stuff
}
But with this approach I will need to implement all the simple methods with just a single delegation statement. So I need to write more code (it is simple though)
Option 2: Extend the complex class and implement simplified methods but then both simple and complex versions of these methods will be visible.
In python I can achieve similar behaviour like this:
class PowerfulButComplexClass(object):
def alreadySimple(self):
# really simple
# some very complex methods
class Facade(object):
def __init__(self):
self.realworker = PowerfulButComplexClass()
def simplified(self):
# simplified version of complex methods in PowerfulButComplexClass
def __getattribute__(self, key):
"""For rest of the PowerfulButComplexClass' methods use them as they are
because they are simple enough.
"""
try:
# return simplified version if we did
attr = object.__getattribute__(self, key)
except AttributeError:
# return PowerfulButComplexClass' version because it is already simple
attr = object.__getattribute__(self.data, key)
return attr
obj = Facace()
obj.simplified() # call the one we have defined
obj.alreadySimple( # call the one defined in PowerfulButComplexClass
So what is the Java way to achieve this?
Edit: What I mean by "simplify": A complex method can be either a method with too many arguments
void complex method(arg1, arg2, ..., argn) // n is sufficiently large
or a set of related methods that will almost always called together to achieve a single task
outArg1 = someMethod(arg1, arg2);
outArg2 = someOtherMethod(outArg1, arg3);
actualResult = someAnotherMethod(outArg2);
so we want to have something like this:
String simplified(arg1, arg2, arg3) {
outArg1 = someMethod(arg1, arg2);
outArg2 = someOtherMethod(outArg1, arg3);
return someAnotherMethod(outArg2);
}