Each method in Facade Object is combination of several other methods exposed in several interfaces. Over the period of time this object will also grow as we will come to know about different operations that can be achieved by combining different interfaces available in complex system and its method.
My question is simple:
1) It is a better option to go ahead with Facade or do we have some other option available? because as we increase the number of methods to accommodate each new operation in Facade object, it also becomes complex. A possible solution that I can think of is to create one more Facade
2) Also, is there a limit-on methods exposed by facade when we will say it become complex?
Update: my analysis says stop adding more method to a Facade if it is making hard to understand and rethink your design; is that it?
Since your question is very abstract, it's hard to answer it in a way that is guaranteed to be good for the specifics of what you're writing.
As far as I can tell, the question you're asking is really, if you have
interface A { public void a(); }
interface B { public void b(); }
class ABFacade {
private final A a = ...
private final B b = ...
public void ab() { a.a(); b.b(); }
}
then is that useful or not?
The answer is going to depend on
The problem domain - how well defined is it?
How you name things - will people understand it?
Code reuse - is there more than one thing that will ever need to call a facade method?
I don't think there is a single right answer - at least not with specific examples. It also depends on what the purpose for using this pattern is - better code reuse? Fewer sets of duplicate code that does something complex? Creating choke points all code that does X must pass through? Clarity for other developers? The answers to that question profoundly affects what your code should look like.
I can suggest some general things that might help result in something useful:
If a facade method will only be used in one place, it probably does not deserve to be in the facade - if it the code only has one client, it probably makes more sense to do all the steps inline
Can some operation on the facade be given clear naming? Would the result be more intuitive to use than writing out everything the facade does? If so, then that probably should be on the facade
At the end, it's just a pattern. If it lets you write smaller, better or more reliable software, use it; if it doesn't, don't bother.
Related
I want to use the strategy pattern in Java. However, my boss doesn't like it if I add lots of files to the code base or write verbose code. It seems that with the strategy pattern I'd have to make one file for an interface and then five additional files so I can have a class for each of my five possible strategies.
Is there a way to express the strategy pattern in Java with fewer files and less code?
I think it would be ideal if my strategy variations could be represented on an Enum or one Set that is easy to assemble.
I think you should sit down with your boss and explain to him/her that less files != good code. At least attempt to explain the pattern itself and how having multiple classes, each with it's own specific purpose is better for testing, maintenance, etc....
Personally, i find code more verbose with lots of IF statements littered about the place where proper polymorphism would make the code much easier to understand.
PS: And yes, enums can have behavior by using the anonymous subclassing construct:
public enum Foo {
BAR() {
public void baz() { ... }
};
public abstract void baz();
}
Though i'm not sure i'd recommend using that unless you absolutely have to.
I have a pretty complex java class with over 60 small helper methods used for easy readability and understanding.Just wondering, do you think having these many methods in a class could affect performance in any way?
class MyClass() {
//Some static final variables
MyInnerClass m = loadAllVariables();
private void update(){
}
...
//All 60 methods come here
....
private MyInnerClass loadAllVariables() {
MyInnerClass m = new MyInnerClass();
//load all variables with pre-initialized values
}
private MyInnerClass() {
int a, b, c; //In reality, I have over 20 variables
}
}
No. The number of methods in a method doesn't matter much. Only the methods used are really loaded. If you have thousands of methods this is more likely to be a problem for you (the developer)
Keeping your code simple and clear is more likely to improve performance.
Performance wouldn't be really affected that much. Just make sure you are not implementing the God-anti-pattern.
From an engineering perspective, it might be confusing for other developers to navigate through your complex hierarchy of inner classes.
May be you need to use Extract Class. It is common methodology for solving Feature Envy code smell (these are both taken from Martin Fowler's Refactoring).
About the many methods in one class - I reacall that I've read somewhere that the JVM will optimize additionaly your code, will inline methods, etc.
It depend !!!
First, It likes Peter Lawrey has said, just the methods you use in your answer will take some time. for example:
public void update(){
if (sth) methodA();
else if(sth other) methodB();
else if(sth other) methodC();
}
in above example, always one method will be called.
Seconly, It depends on your platform. If you are developing for desktop, 60 methods make nonsense, unless you use thousand and thousand methods. But if you are developing on Android, 60 methods for one update() function really a big problem. That why many expert say you shouldn't use Getter/Setter on Mobile Platform. And of course, this work will anti again Design pattern :)) That the reason why when you develop on Mobile Platform, you will have hard choice between performance and Maintenance. (It means your code will be clear and easily to read )
Hope it's clear for you :)
Sorry folks, the answers are wrong or not addressing the really important point.
All methods in the class above are private. This means there is no polymorphism going on and the JVM can invoke the method directly and not via invoke dynamic. "private" implies "final".
Further more, all the tiny methods get inlined by the JIT. So there is no performance difference.
I know one of the goals of pure functional programming is to eliminate mutability, and therefore to preclude side-effects. But let's face it, Java is not a functional language even with all of the functional-programming libraries that exist. In fact it seems that some of the FP-libraries know and expect this. For instance in Functional Java, there is the Effect class. In the Jedi FP library, there is the Command interface. This allows you to -- among other things -- apply a command pattern with type-safety to elements of an Iterable without the nasty for-loop boilerplate.
Command<PhoneNumber> makeCall = new Command<PhoneNumber> {
public void execute(PhoneNumber p) { p.call(); }
}
List<PhoneNumber> phoneList = ...
FunctionalPrimitives.forEach( phoneList, makeCall );
So the question is, is there anything like that in Guava?
EDITED AFTER ANSWER ACCEPTED FOR CLARIFICATION
I am developing a framework that helps with the "vertical problem" inherent in most Java FP-libraries, under a certain set of circumstances. So I would not actually make the code example as shown above: i.e., explicitly declare a new class implementation of Command with all of its vertical-noise icky-ness, simply for the purpose of immediately applying it right after the declaration.
I was thinking more along the lines of the actual command pattern, where there may be several possible commands declared elsewhere, and only one of them gets passed into the code which wants to apply it iteratively. Furthermore, the goal of my framework is to make it more idiomatic to create functional-interface objects (functions, predicates, commands, other simple lambdas) without simply moving the vertical problem elsewhere. I have long realized this is not within the scope of Guava. But as Command-like interface are available in other FP libraries, I just wanted to know if an analog existed in Guava.
A more complete code example, using my framework, might be something like this:
class Stuff {
private final Stuff CALLS_TO = callsTo(Stuff.class); // a proxy
public static final Command<Stuff> CMD1 = commandFor(CALLS_TO.someMethod1());
public static final Command<Stuff> CMD2 = commandFor(CALLS_TO.someMethod2());
// methods exist for use elsewhere, but are conveniently also wrapped as commands
public void someMethod1() {...}
public void someMethod2() {...}
}
class Activity {
public void handleIt(List<Stuff> stuffs, Command<Stuff> doCmd) {
doSomeThings();
...
forEach(stuffs, doCmd);
...
doOtherThings();
}
}
Nope!
Kevin Bourrillion, the Guava project lead, has said on Guava's functional features:
“The syntax sucks. At the same time, this stuff is now, has always been and will always be nothing but a stopgap measure until the right language change can come along, at which time we can finally really decide on the optimal syntax and have functional-style programming start actually making lives better in Java for once. So I’m undecided how much effort to put into the Function/Predicate stuff; it’s in the library more because it sort of had to be, not so much because we think it’s a crown jewel.”
We will probably change our strategy significantly when Java 8 comes along, but that won't be for a while yet.
Also, we haven't found many use cases for which we think the Command interface you describe would be the best solution. For example, we think that your above code would be much better written as
for(PhoneNumber phone : phoneList) {
phone.call();
}
the old-fashioned way. We could potentially be convinced of the merit of Command, but I think the "for-each" use case is almost always better done the old-fashioned way.
I wonder what is the best way in terms of strict OOP to add functionality to built-in types like Strings or integers or more complex objects (in my case the BitSet class).
To be more specific - I got two scenarios:
Adding a md5 hashing method to the String object
Adding conversion methods (like fromByteArray() or toInteger()) to the BitSet class.
Now I wonder what the best practices for implementing this would be.
I could e.g. create a new Class "BitSetEx" extending from BitSet and add my methods. But I don't like the idea since this new class would need describing name and "BitSetWithConversionMethods" sound really silly.
Now I could write a class consisting only of static methods doing the conversions.
Well I got a lot of ideas but I wan't to know what would be the "best" in sense of OOP.
So could someone answer me this question?
There are a few approaches here:
Firstly, you could come up with a better name for the extends BitSet class. No, BitsetWithConversionMethods isn't a good name, but maybe something like ConvertibleBitSet is. Does that convey the intent and usage of the class? If so, it's a good name. Likewise you might have a HashableString (bearing in mind that you can't extend String, as Anthony points out in another answer). This approach of naming child classes with XableY (or XingY, like BufferingPort or SigningEmailSender) can sometimes be a useful one to describe the addition of new behaviour.
That said, I think there's a fair hint in your problem (not being able to find a name) that maybe this isn't a good design decision, and it's trying to do too much. It is generally a good design principle that a class should "do one thing". Obviously, depending on the level of abstraction, that can be stretched to include anything, but it's worth thinking about: do 'manipulating the set/unset state of a number of bits' and 'convert a bit pattern to another format' count as one thing? I'd argue that (especially with the hint that you're having a hard time coming up with a name) they're probably two different responsibilities. If so, having two classes will end up being cleaner, easier to maintain (another rule is that 'a class should have one reason to change'; one class to both manipulate + convert has at least 2 reasons to change), easier to test in isolation, etc.
So without knowing your design, I would suggest maybe two classes; in the BitSet example, have both a BitSet and (say) a BitSetConverter which is responsible for the conversion. If you wanted to get really fancy, perhaps even:
interface BitSetConverter<T> {
T convert(BitSet in);
BitSet parse(T in);
}
then you might have:
BitSetConverter<Integer> intConverter = ...;
Integer i = intConverter.convert(myBitSet);
BitSet new = intConverter.parse(12345);
which really isolates your changes, makes each different converter testable, etc.
(Of course, once you do that, you might like to look at guava and consider using a Function, e.g. a Function<BitSet, Integer> for one case, and Function<Integer, BitSet> for the other. Then you gain a whole ecosystem of Function-supporting code which may be useful)
I would go with the extending class. That is actually what you are doing, extending the current class with some extra methods.
As for the name: you should not name at for the new features, as you might add more later on. It is your extended BitSet class, so BitSetEx allready sounds better then the BitSetWithConversionMethods you propose.
You don't want to write a class with the static methods, this is like procedural programming in an OOP environment, and is considered wrong. You have an object that has certain methods (like the fromByteArray() you want to make) so you want those methods to be in that class. Extending is the way to go.
It depends. As nanne pointed out, subclass is an option. But only sometimes. Strings are declared final, so you cannot create a subclass. You have at least 2 other options:
1) Use 'encapsulation', i.e. create a class MyString which has a String on which it operates (as opposed to extending String, which you cannot do). Basically a wrapper around the String that adds your functionality.
2) Create a utility/helper, i.e. a class with only static methods that operate on Strings. So something like
class OurStringUtil {
....
public static int getMd5Hash(String string) {...}
....
}
Take a look at the Apache StringUtils stuff, it follows this approach; it's wonderful.
"Best way" is kinda subjective. And keep in mind that String is a final class, so you can't extend it.
Two possible approaches are writing wrappers such as StringWrapper(String) with your extra methods, or some kind of StringUtils class full of static methods (since Java 5, static methods can be imported if you wan't to use the util class directly).
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
First off, I know next to nothing about language theory, and I barely know any other languages except Java, but I had an idea that I think would be cool, but I need you guys to tell me:
a: why it sucks
b: how language x has had that for years
c: how my mind sucks
d: all of the above
The idea would give composition the same ease of code reuse that extends does.
So if you had a class like this:
public interface A {
public void methodInA();
}
And then you had a class like this:
public class B {
private composed A;
public B() {
// construct A within constructor
}
}
You would then be able to do this:
B myB = new B();
myB.methodInA();
Without having to add in the delegation in B's class. But you could also do the same as with inheritance, ie:
#Overrides
public void methodInA(){
// B's own delegation method
}
Disadvantages include:
methods are hidden in the source code, making it less obvious where the call is coming from, but this is also the case with extends
if composed fields share the same method signature there needs to be a conflict resolved (how do conflicting interfaces solve this?)
if you wanted to have several composed fields of the same type, there would be an obvious conflict for which field to delegate to
probably 100 other things I've not thought of
Like I say, I'm obviously no language theorist, and I haven't spent ages thinking about it, the idea just popped in my head and I wanted to know how wrong I am. I just think it would be kind of cool.
It sounds cool but I think it makes for some horrible language constructs. Obviously there is a problem if you declare more than one 'composition' of the same class, but even if you forbid that what about the case where a call matches a method in more than one of the (different) composed classes? You would have to specify which one was called in the main class, and you would need extra syntax for that. The situation becomes even worse if there are public members in the classes.
Composition is used to prevent problems with multiple inheritance. Allowing composition like this is effectively permitting multiple inheritance, at least in terms of resolving which method to call. Since a key design decision with Java was to disallow multiple inheritance (for good reasons) I think it unlikely that this would ever be introduced to Java.
I think if you restricted it such that a class could only use this feature to compose a single class it would be somewhat useful and would avoid a lot of the headaches that are being discussed.
Personally I hate inheritance of concrete classes. I'm a big proponent of Item 14 from Bloch's Effective Java, Favor composition over inheritence. I think that something like this would make it a little easier to implement the idiom he recommends in that item.
Honestly, if you really knew what you were doing I'll bet you could write a compiler annotation that would handle this. So assuming you had a class Bar that implemented the interface IBar, your class would look like this:
public class Foo {
#Delegate(IBar.class)
private Bar bar;
// initialize bar via constructor or setter
}
Then during compilation Foo could be made to implement IBar and any of the methods on that interface that weren't already implemented by Foo would end up being generated to look like this:
public Baz method1(Qux val) {
return bar.method1(val);
}
As mentioned above you would want to make the restriction that only one field per class could use this annotation. If multiple fields had this annotation you'd probably want to throw a compilation error. Alternatively you could figure out a way to encode some sort of precedence model into the parameters passed to it.
Now that I've written this out that seems kinda cool. Maybe I'll play around with it next week. I'll update this if I manage to figure anything out.
I'm not sure that I see a clear advantage to doing this though. I understand the point you are making. At the moment to call a method on A you have to myB.getAInstance().methodInA(), but you want to make that myB.methodInA().
But, what happens if you have multiple instances of A? How would the method call be resolved? Many times composition implies a one to many association so B has many A instances. What happens then?
I agree with your disadvantages listed. It may simply cause too much confusion than it is worth.
Check out what is called "Mixins" in some languages, and "Roles" in the Perl 5 Moose OO system.
There's also the difference between composition and aggregation to consider. How does the compiler know whether you mean 'is-a' or 'has-a' relationships?
Does the whole object graph become eligible for garbage collection or only the head of the graph?
A couple of the ORM mapping tools and frameworks over/around them provide for belongsTo or has-many relationships between persistent objects and some also provide for the cascading delete (for composition). I don't know of one off hand that provides the simple syntactic sugar you're looking for.
Actually, on second thought, Groovy's MetaClass and MetaProgramming idiom(s) may provide something very similar, with 'auto-magic' delegation.
Multiple inheritance is allowed in C++, I know that different but it is along the same thought process. Java was designed to not allow multiple inheritance so that there would be less confusion, therefore bugs and exploits.
What you have suggested is in direct conflict with the principles of java.
Having said that, it would be cool (not necessarily useful). I'm a java programmer who switched from C++. I like being able to make my own mistakes.