Would syntax for composition be a useful addition to Java? [closed] - java

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.

Related

Is it meaningful to have abstract classes just for purpose of layering structure? [closed]

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 3 years ago.
Improve this question
Assume a Java class (e.g. a helper class), which has a great bundle of methods that could be separated into different layers. By layers, I mean the design of clearer responsibilities for each class and a reduction of complexity. Is it meaningful in this case, by using abstract class, to achieve the goal, in the sense of clean code and software design?
I encountered the situation in a project where there is a helper class having too much complexity and simply too many rows. The class is somehow playing vital roles, acting as a kind of type helper assisting other objects to fetch and manipulate type information. Each time a new/existing type would need extra type info, this class comes into help, therefore becomes heavier and more complicated in implementing methods. Though I can surely categorize and separate those methods into many classes. I found there be a structural correlation between those methods. Please see the code example below:
Assume a Type can have some TypeProperty:s. Assume also in code that there are a Type class and a TypeProperty class, both with essential getters and setters, meanwhile a Helper class Helper.
public class Helper{
static final T CONSTANT_A = new A(...);
static final T CONSTANT_B = new B(...);
final Type theType;
//constructor etc.
Type getType(){
return theType;
}
Type getTypeByKey(Key typeKey){
//...
}
Collection<TypeProperty> getPropertiesByType(Type t){
//...
}
Collection<TypeProperty> getProperties(){
return theType.getProperties();
}
TypeProperty findSpecificPropertyInTypeByKey(Key propertyKey){
Set<TypeProperty> properties= theType.getProperties();
//loop through the properties and get the property,
//else return null or cast exception if not found
}
boolean isTypeChangeable(){
return findSpecificPropertyInTypeByKey().isChangeable();
}
//many more methods
}
I expect to refactor the Helper class so that the code is easier to maintain and expand, as well as, to be less complex. I think it is possible to separate the methods into different classes, however, this might lead to too many classes and the responsibilities are not straight-forward as they are not in a helper class(es). While in the meantime, the idea of utilizing abstract classes comes into my mind. Would it be meaningful then? Say that after refactoring, there would be
a TopLevelHelper having methods revolving the type itself, e.g. isTypeChangeable & getType(), as well as, all Constants;
a SecondLevelHelper extending TopLevelHelper, which bears the logics as middleware, e.g. getProperties and getPropertiesByType;
a LastLevelHelper extending SecondLevelHelper, which does the concrete and detailed works, e.g. findSpecificPropertyInTypeByKey.
Though none of these classes would have abstract methods but concrete implementations since none of the methods in higher-level helpers would be overridden. It does not seem that such a design is appropriate usage of abstract classes, still, I feel it separates responsibilities into three layers. Should it be done like this or should other techniques be used in this situation?
There's no definite answer of course, but I think you should stick with what you have. Abstract classes are mostly meaningful for implementing template methods and similar patterns. Splitting a class on different hierarchy levels does feel weird in your case, because the methods do seem to belong to different groups, rather than different levels. If java allowed multiple inheritance, traits, or something similar, you could make the mixin classes.
However, a class with multiple methods is fine. Although OOP design guidelines often say you should limit your class to eg 5 method, you class seems more of a smart data structure than a class, and your methods are mostly accessors and properties. So, since they are simple and conceptually similar, there's no real problem having many of them. Java itself does it all the time (for example, see string & collection classes reference).
I would say that layering is not a good approach.
From what you are saying about that 3 layers, they have different responsibilities. If all this 3 responsibilities are coded in the same class, it breaks the Single Responsibility Principle. So the solution that naturally follows is to split each one in its own class and use composition. By doing this you also adhere to the principle that says composition is preferable to inheritance.

How interfaces in java used for code reuse? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am learning java, and came to know that Java doesn't support multiple inheritance. So, java introduced interfaces for that. How does the problem of multiple inheritance is solved by interface?
What I read online : "Inheritance in java means code reuse".
If i implement an interface in class say A, I will have to give my own implementation for it in A, and same in B, which means methods in interface (say I) will have different implementation in A and B. How does it use the code re-usability feature?
You haven't given proper citations for any of the assertions that you make in your Question, so it is impossible to know what they are actually saying ... or why you think that they are say these incorrect or misleading things.
I am learning java, and came to know that Java doesn't support multiple inheritance.
That is correct.
So, java introduced interfaces for that.
That is INCORRECT. Java introduced interfaces to support polymorphism. Specifically polymorphism that does not depend on class inheritance.
How does the problem of multiple inheritance is solved by interface?
It isn't.
Multiple inheritances are about inheritance of method and field declarations from multiple parent classes. Interfaces does not provide that, and it does not solve the problem.
Interfaces do allow you to declare a common API (or APIS) and implement that API without necessarily sharing code. But with careful design you can do code-sharing under the hood any; e.g. by using the Delegation design pattern.
What I read online : "Inheritance in java means code reuse".
I doubt that what it actually said. Anyway, it is INCORRECT.
Inheritance (of classes) is one way to achieve code reuse, but it is only one of many ways to achieve reuse. There are many others.
If i implement an interface in class say A, I will have to give my own implementation for it in A, and same in B, which means methods in interface (say I) will have different implementation in A and B.
I presume that you mean something like this:
public interface I {
void someMethod();
}
public class A implements I {
void someMethod() {
// some code
}
}
public class B implements I {
void someMethod() {
// some code
}
}
How does it use the code re-usability feature?
There is no code reuse in that example. But this is not inheritance of classes (which I described as one way to achieve code reuse). It is a class implementing an interface.
(Now in Java 8, you can put code into interfaces in certain circumstances; read up on the default methods feature. And that does allow direct code reuse via an interface. But I doubt that is what the sources you have been looking at are talking about.)
Java solved the problem of multiple inheritance (or rather the problems that come with this feature) by allowing single inheritance, that is allowing only one super class. This design created a new problem of a class that needs to implement multiple contracts. a contract, like is explained in #Kermi's answer, allows other objects to refer to the same Object as different types, for various purposes, the most common one is for storing in Collections. an interface can be regarded as a super class that has no implementation (all the methods are pure virtual if you like)
So, Java removed the problems that come with multiple inheritance (the famous diamond problem) but also the advantages that come with it such as code reusability. This design follows the principal of making Java simple and easy and predictable by removing "advanced" (some say confusing) C++ features like multiple inheritance, operator overloading, pointer manipulation (among others).
There are several technics that allow Java to restore most of the code reusability of multiple inheritance. One such technic is composition: so if we take #Kermi's example, you can have a GeneralAnimal class that implements the most common behavior of an Animal. every Dog instance holds a reference to a GeneralAnimal instance (obtained through ctor or factory or dependency injection or ...) and can delegate some messages (=method calls) to that instance. The same is done in Cat instances and so on.
Interface doesn't resolve multiple inheritance problem or rather it doesn't create a multiple inheritance problem. It gives you a possibility to reuse existing implementations.
For example:
class Dog implements Comparable<Dog>, Animal
As your class implements 2 interfaces you can use them in difeerent ways. To use TreeSet object needs to implement Comparable methods (it is not the only possibility). When Dog is passed to TreeSet implementation of that structure is then sure that object has compareTo(Dog dog) method and can use it.
But than you want to store a List of Animals, and than iterate through that list with execution method declared for Animal, than you would not use Comparable interface, but Animal.
List<Animals> animals = new ArrayList<>();
animals.add(dog);
animals.add(cat);
for (Animal animal : animals) {
animal.walk();
}
Interface is a criterion, I think.
A and B should conform to it. In addition, A and B do different things such as ArrayList and LinkedList.
"Inheritance in java means code reuse" is right, but Interface is not. It embodies a norm.
When you learn Collections, you will understand it clearly.

OOP: Any idiom for easy interface extraction and less verbose auto-forwarding?

EDIT
Even though I use a pseudo-Java syntax below for illustration, this question is NOT limited to any 1 programming language. Please feel free to post an idiom or language-provided mechanism from your favorite programming language.
When attempting to reuse an existing class, Old, via composition instead of inheritance, it is very tedious to first manually create a new interface out of the existing class, and then write forwarding functions in New. The exercise becomes especially wasteful if Old has tons of public methods in it and whereas you need to override only a handful of them.
Ignoring IDE's like Eclipse that though can help with this process but still cannot reduce the resulting verbosity of code that one has to read and maintain, it would greatly help to have a couple language mechanisms to...
automatically extract the public methods of Old, say, via an interfaceOf operator; and
by default forward all automatically generated interface methods of Old , say, via a forwardsTo operator, to a composed instance of Old, with you only providing definitions for the handful of methods you wish to override in New.
An example:
// A hypothetical, Java-like language
class Old {
public void a() { }
public void b() { }
public void c() { }
private void d() { }
protected void e() { }
// ...
}
class New implements interfaceOf Old {
public New() {
// This would auto-forward all Old methods to _composed
// except the ones overridden in New.
Old forwardsTo _composed;
}
// The only method of Old that is being overridden in New.
public void b() {
_composed.b();
}
private Old _composed;
}
My question is:
Is this possible at the code level (say, via some reusable design pattern, or idiom), so that the result is minimal verbosity in New and classes like New?
Are there any other languages where such mechanisms are provided?
EDIT
Now, I don't know these languages in detail but I'm hoping that 'Lispy' languages like Scheme, Lisp, Clojure won't disappoint here... for Lisp after all is a 'programmable programming language' (according to Paul Graham and perhaps others).
EDIT 2
I may not be the author of Old or may not want to change its source code, effectively wanting to use it as a blackbox.
This could be done in languages that allow you to specify a catch-all magic method (eg. __call() in php). You could catch any function call here that you have not specifically overriden, check if it exists in class Old and if it does, just forward the call.
Something like this:
public function __call($name, $args)
{
if (method_exists($old, $name))
{
call_user_func([$obj, $name], $args);
}
}
First, to answer the design question in the context of "OOP" (class-oriented) languages:
If you really need to replace Old with its complete interface IOld everywhere you use it, just to make New, which implements IOld, behave like you want, then you actually should use inheritance.
If you only need a small part of IOld for New, then you should only put that part into the interface ICommon and let both Old and New implement it. In this case, you would only replace Old by ICommon where both Old and New make sense.
Second, what can Common Lisp do for you in such a case?
Common Lisp is very different from Java and other class-oriented languages.
Just a few pointers: In Common Lisp, objects are primarily used to structure and categorize data, not code. You won't find "one class per file", "one file per class", or "package names completely correspond to directory structure" here. Methods do not "belong" to classes but to generic functions whose sole responsibility it is to dispatch according to the classes of their arguments (which has the nice side effect of enabling a seamless multiple dispatch). There is multiple inheritance. There are no interfaces as such. There is a much stronger tendency to use packages for modularity instead of just organizing classes. Which symbols are exported ("public" in Java parlance) is defined per package, not per class (which would not make sense with the above obviously).
I think that your problem would either completely disappear in a Common Lisp environment because your code is not forced into a class structure, or be quite naturally solved or expressed in terms of multiple dispatch and/or (maybe multiple) inheritance.
One would need at least a complete example and large parts of the surrounding system to even attempt a translation into Common Lisp idioms. You just write code so differently that it would not make any sense to try a one-to-one translation of a few forms.
I think Go has such a mechanism, a struct can embed methods from another struct.
Take a look here. This could be what you are asking as second question.

Using Facade Design Pattern | Drawbacks/ Solutions/ Suggestions

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.

Interface or Class for a list of static finals? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 years ago.
Improve this question
I am maintaining some Java code that utilizes an interface (let's call it BunchOfConstants) to simply store an abundance of public static final Strings. Occasionally these string names change or string names are added / removed. (which causes a bit of a headache for maintanance)
The only current use for this interface is to compare to input later in a big ugly if/then construct like this:
if(BunchOfConstants.CONSTANT1.equals(whatImLookingFor)){
doSomeStuff(whatImLookingFor)
}else if(BunchOfConstants.CONSTANT2.equals(whatImLookingFor)){
doSomeStuff(whatImLookingFor)
}else if(BunchOfConstants.CONSTANT3.equals(whatImLookingFor)){
doSomeStuff(whatImLookingFor)
}
...
I thought it would be more elegant to create a class that implements Iterable or even a class that stores this data in a hashMap.
I can not figure out why the original developers decided to use an interface for this design as the interface is never actually implemented anywhere. Does anyone have any input?
Would you agree that an iterable class with these members as constants would be more appropriate?
Use enums. Then get myenum.values() and then apply a for-each loop over the values.
I would consider using enums instead as constants are not type safe (e.g., they are just ints, or strings, etc.).
This (having dedicated interface for storing constants) was a fairly common way of storing constants before the era of enums. (Pre Java 5 times.) It saved you the hassle of prefixing your constants with the containing class name. I personally never really liked this practice, but this is the reason people did it.
As for what it can be replaced with:
An enum and a switch/case construct. This requires the least modification but only has modest benefits in readability. It does give you type and value safety, plus you can get warnings out of your IDE if you forget to handle a possible value (no case for it and no default block either).
A properties file. This obviously only works if you don't want to branch based on your constant values. (I.e. if your constants don't have to appear in your source code.) This is important, otherwise you'd end up with a secondary set of constants and a properties file, which is as bad as it gets.
A doSomeStuff() factory. For this you have to wrap your doSomeStuff() implementations in separate operation classes and you can configure your factory either statically or from a properties file. (via a constant value->operation class mapping). This is the most "enterprisey" solution, which means that although it looks nice and is very flexible, a lot of the time it is an overkill.
I think this is a good candidate for enum
Well, this looks like the Constant Interface antipattern and maybe should not be used. Using an enum might be a way as suggested, or at least using a final class with private constructor.
If you want to have different implementations for doSomeStuff based on the input string, you might also consider using the strategy pattern, i.e. have a Map<String, Strategy> and then lookup the strategy for whatImLookingFor. If you found the strategy, execute its doSomeStuff, otherwise handle the "not found" case.
I would suggest you to use a property file to store all your constants. This way you can load your properties into a HashMap as you suggest in your question.
Note that property support is brought natively with java: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Properties.html
Well, enums are the way to go ... but if the 'dosomestuff' is semantically dependent upon the specific value then why not add a 'dosomestuff' method to the enum itself. That is one that this is really great about Java enums - they are not merely data but as all good objects they have semantics. Then you just loop over the enums invoking dosomestuff(whatIamLookingFor) and whatever happens happens.
Hard to say.
Yes, I agree, that it will be more elegant - at least for you. But think, what the next programmer will think about it. It will be even more complicated.
Previously mentioned strategy pattern and java's enum are definitely better solution, but since you are maintaining this code, I'm not sure if your boss will be happy with time consuming refactoring. My advice would be to use enums - not so big code change.

Categories

Resources