java - connecting interface to class member - java

Say I have an interface A and a class B that implements it.
Now, I also have some class C which extends class D (which means that it can't also extends B) but I also need there the functionality of interface A.
The solution I know is to have a member of A instantiated by B in C (which will implement A) and when implementing the functions of A call the matching function from the member of A.
Is there any way to create some connection between the functions of A and the member inside C? (so that java will know that every time it needs to call a function from A it will directly go and and run the matching function from the A member without me needing to write the code for it for every function of A)
A big thank you is waiting to each one of the helpers...

No. As already stated delegation must be implemented manually.
Having said that, you have a few options to simplify this: If you're working with Eclipse, select Source|Generate Delegate Methods... and select your member variable. Eclipse will then generate all the delegate methods for you. I don't know about other IDEs, but I would be surprised, if NetBeans et al. would not have a similar feature.
Another option, if you actually want to decorate existing collection classes, consider Google Guava's Google Guava's Collection Helpers.
Last, but not least, you could consider restructing your code and decorate your classes using Advices. Advices stem from Aspect Oriented Programming (AOP) and typically use a proxying mechanism to enrich original target classes. This is a rather advanced technique, but if you are determined to go down this road, have a look at Spring's AOP support.

So to sum up, here is your class hierarchies:
package common;
public interface A
{
void doStuff();
}
package commom.impl;
public class B implements A
{
void doStuff() {}
}
package real.service;
public class D
{
void doSomeRealStuff() {}
}
package real.service;
public class C extends D
{
void doSomeRealStuffForGood() {}
}
Assuming that each class is declared in its own source file.
Just to recall from the OP, I assume you need B stuff in C and not really A stuff. Because A is nothing but a contract and you need then the real implemting class to be fetched inside your C class in order to call the declared methods on.
In such a case, you may need to use the Inversion of Responsability approach, so that you declare an instacne of type B inside your C clas then you layer each method from B with a one having the same signature and that do nothing but delegate the real call to the instance member:
package real.service;
import common.A;
import common.impl.B;
public class C extends D
{
private A delegate;
public C ()
{
delegate = new B();
}
void doStuff() {
delegate.doStuff(); // Call the real delegate method when doStuff is called on an isntance of C.
}
void doSomeRealStuffForGood() {}
}
Note that this is a legal OO concept, since you are following an HAS-a even though some could consider it a high coupling.
Otherwise if you are not tied to the B class, and you may drop the declare methods in there for some others, you can declare an inner class that implements the A interface the way you need.
Edit:
Java does not support multiple inheritance, though you have provided a common contract in your A interface, so if you need all those methods (behavior) to be availble in your C class, it would be better to implement it directely and override all the interface methods.

Related

Refactoring and avoiding code duplication

I've ran into a problem that is new for me. Basically, someone else has already written a class A. The important parts looks like this
class A{
// some instance variables
public A(){
// Calls methods
build();
// Calls more methods
}
private build(){
item = makeItem();
anotherItem = makeAnotherItem();
// more code
}
private makeItem(){
// Does some things and calls updateItem()
}
private updateItem(){
// Does some things with instance variables of class A
// and calls yet another method in class A.
}
My problem is that build() does exactly what I need, but I need it in another class. Now here are the problems:
class A does a whole lot more than the things I've written, and so I cannot create an object of it. It would be pointless.
I've tried copying the build() method for my class B. However, build() uses other methods. And so I have to copy them as well and of course they call other methods and use instance variables declared in some other methods. Basically, I would have to copy 200 rows of code.
I'm guessing this problem actually has a name but I do not know what it's called and have therefore searched some basic terms only. What can I do to use build() in my class B?
You use the code of the build method in two classes but inheritance is not useful? Then you can reuse the code of the build method with composition. (hint Favor Composition over Inheritance) Create a new class C, which contains the build method. The class C is used by the classes A and B via composition. They delegate to the build method of the class C.
See the refactoring method of Martin Fowler.
https://sourcemaking.com/refactoring/smells/duplicate-code
also see
https://sourcemaking.com/refactoring/replace-inheritance-with-delegation
Always refactor in small steps. e.g. Put stuff together that belongs together, perhaps there is a neccessity for another class C which contains makeItem, makeAnotherItem and the corresponding instance variables. There is no general answer and it depends on how your code exactly looks like
first of all if build() in class A is using other private methods of A, that smells like you will need class A itself.
One option could be to create abstract class containing the common methods (including the build method), and extend this abstract class by class A and B. that way you will not have duplicate code
If for some reason you don't want to touch class A, I suggest you create an interface like :
public interface Builder{
void build()
}
and then implement this interface by your class B, and also extend class A so that you have implementation of the build method.
public class B extends A implements Builder{
// build() of class A will be used
// do other staff
}
In doing so, there is no change to class A at all (this might be desired if it is legacy code or something) + Builder can be used as a type in API you want to expose.

What does decoupling two classes at the interface level mean?

Lets say we have class A in package A and class B in package B . If object of class A has reference to class B, then the two classes are said to have coupling between them.
To address the coupling, it is recommended to define an interface in package A which is implemented by class in package B. Then object of class A can refer to interface in package A . This is often an example in "inversion of dependency".
Is this the example of "decoupling two classes at the interface level". If yes, how does it remove the coupling between classes and retain the same functionality when two classes were coupled?
Let us create a fictive example of two classes A and B.
Class A in package packageA:
package packageA;
import packageB.B;
public class A {
private B myB;
public A() {
this.myB = new B();
}
public void doSomethingThatUsesB() {
System.out.println("Doing things with myB");
this.myB.doSomething();
}
}
Class B in package packageB:
package packageB;
public class B {
public void doSomething() {
System.out.println("B did something.");
}
}
As we see, A depends on B. Without B, A cannot be used. We say that A is tightly coupled to B. What if we want to replace B in the future by a BetterB? For this, we create an Interface Inter within packageA:
package packageA;
public interface Inter {
public void doSomething();
}
To utilize this interface, we
import packageA.Inter; and let B implements Inter in B and
Replace all occurences of B within A with Inter.
The result is this modified version of A:
package packageA;
public class A {
private Inter myInter;
public A() {
this.myInter = ???; // What to do here?
}
public void doSomethingThatUsesInter() {
System.out.println("Doing things with myInter");
this.myInter.doSomething();
}
}
We can see already that the dependency from A to B is gone: the import packageB.B; is no longer needed. There is just one problem: we cannot instantiate an instance of an interface. But Inversion of control comes to the rescue: instead of instantiating something of type Inter within A's constructor, the constructor will demand something that implements Inter as parameter:
package packageA;
public class A {
private Inter myInter;
public A(Inter myInter) {
this.myInter = myInter;
}
public void doSomethingThatUsesInter() {
System.out.println("Doing things with myInter");
this.myInter.doSomething();
}
}
With this approach we can now change the concrete implementation of Inter within A at will. Suppose we write a new class BetterB:
package packageB;
import packageA.Inter;
public class BetterB implements Inter {
#Override
public void doSomething() {
System.out.println("BetterB did something.");
}
}
Now we can instantiante As with different Inter-implementations:
Inter b = new B();
A aWithB = new A(b);
aWithB.doSomethingThatUsesInter();
Inter betterB = new BetterB();
A aWithBetterB = new A(betterB);
aWithBetterB.doSomethingThatUsesInter();
And we did not have to change anything within A. The code is now decoupled and we can change the concrete implementation of Inter at will, as long as the contract(s) of Inter is (are) satisfied. Most notably, we can support code that will be written in the future and implements Inter.
Adendum
I wrote this answer in 2015. While being overall satisfied with the answer, I always thought that something was missing and I think I finally know what it was. The following is not necessary to understand the answer, but is meant to spark interest in the reader, as well as provide some resources for further self-education.
In literature, this approach is known as Interface segregation principle and belongs to the SOLID-principles. There is a nice talk from uncle Bob on YouTube (the interesting bit is about 15 minutes long) showing how polymorphism and interfaces can be used to let the compile-time dependency point against the flow of control (viewer's discretion is advised, uncle Bob will mildly rant about Java). This, in return, means that the high level implementation does not need to know about lower level implementations when they are segretaget through interfaces. Thus lower levels can be swapped at will, as we have shown above.
Imagine that the functionality of B is to write a log to some database. The class B depends on the functionality of the class DB and provides some interface for its logging functionality to other classes.
Class A needs the logging functionality of B, but is does not care, where the log is written to. It does not care for DB, but since it depends on B, it also depends on DB. This is not very desirable.
So what you can do, is to split the class B into two classes: An abstract class L describing the logging functionality (and not depending on DB), and the implementation depending on DB.
Then you can decouple the class A from B, because now A will only depend on L. B now also depends on L, that is why it is called dependency inversion, because B provides the functionality offered in L.
Since A now depends on just a lean L, you can easily use it with other logging mechanism, not depending on DB. E.g. you can create a simple console based logger, implementing the interface defined in L.
But since now A does not depend on B but (in sources) only on the abstract interface L at run time it has to be set up to use some specific implementation of L (B for instance). So there needs to be somebody else that tells A to use B (or something else) during the runtime. And that is called inversion of control, because before A decided to use B, but now somebody else (e.g. a container) tells A to use B during the runtime.
The situation you describe removes the dependence that class A has on the specific implementation of class B and replaces it with an interface. Now class A can accept any object that is of a type that implements the interface, instead of only accepting class B. The design retains the same functionality because class B is made to implement that interface.
This is where DI (Dependency Injection) frameworks really shine.
When you are building interfaces, you are actually building out contracts for implementation. Your calling services will only interact with the contract and the promise that a service interface will always provide the methods that it has specified.
For example...
Your ServiceA will build their logic around ServiceB's interface and does not have to worry about what happens under ServiceB's hood.
This allows you to create multiple implementations of ServiceB without having to change any logic in ServiceA.
For the sake of example
interface ServiceB { void doMethod() }
You can interact with ServiceB in ServiceA without knowing what goes under the hood of ServiceB.
class ServiceAImpl {
private final ServiceB serviceB;
public ServiceAImpl(ServiceBImpl serviceBImpl) {
this.serviceB = serviceBImpl
}
public void doSomething() {
serviceB.doMethod(); // calls ServiceB interface method.
}
}
Now because you have built ServiceA using the contract specified in ServiceB, you are able to change out the implementation as you please.
You can mock the service, create different connection logic to different databases, create different runtime logic. All of these can change and will not at all affect the way ServiceA interacts with ServiceB.
Thus, loose coupling is achieved with IoC (Inversion of Control). You now have a modular and focused codebase.

Creating an implementing class that reuses objects of other implementations of the same interface

I want to create a class that does not implement any method of an interface, but extends any implementation of A with it's own methods.
Let's assume we have the following:
public interface A {
public void a();
}
and
public class B implements A {
#override
public void a() {
System.out.println("a");
}
}
I now want to create a class C that also implements A and takes another random implementation of A:
public class C implements A {
public C(A a) {
//what do I need to do with a here?
}
public void c() {
System.out.println("c");
}
}
Now if I have the following:
A b = new B();
A c = new C(b);
c.a();
The output should be "a".
I can't just
public class C extends B {
...
as C is supposed to be able to work with any implementation of A, not just B.
I also can't
public class C implements A {
private a;
public C(A a) {
this.a = a;
}
#override
public void a() {
a.a();
}
public void c() {
System.out.println("c");
}
}
since that would mean that I have to redirect every single interface method and rewrite C whenever something changes with A.
Is there any way to handle that problem in Java?
For another example, replace A: List; B: ArrayList; C: FooList; a(): size()
What you're looking for is a dynamic proxy, which automatically implements all the methods of an interface by delegating to a concrete implementation of this interface. That's not trivial, but not so complex to do either, using Java's Proxy class.
A concrete example of such a proxy, which "adds" methods to any instance of PreparedStatement by wrapping it, can be found at https://github.com/Ninja-Squad/ninja-core/blob/master/src/main/java/com/ninja_squad/core/jdbc/PreparedStatements.java
Unfortunately, there's no way to do it in Java, other than your last code snippet. Various IDEs will help you with the code generation, though, and marking all methods #override will mean that you'll get a warning or an error if your implementation of C doesn't exactly match A's interface.
For Eclipse (and, apparently, IntelliJ), see the "Generate Delegate Methods" command.
This is probably not going to immediately help you, but if you used Java 8, you could solve this with defender methods, which are methods implemented in the interface.
You would then, for each existing implementation class, add your own class which extends the class and implements your additional interface with the defender methods. The methods would be "mixed into" your class.
Java 8 is just around the corner, though, so it is not a far-off solution. Oracle has promised it will release it by the end of this quarter, meaning in less than a month and a half at the latest.
Is there any way to handle that problem in Java?
Basically, no.
What you are describing a wrapper class that delegates calls to the wrapped method. The only way you can implement that (in regular Java) is to implement all of the methods and have them make the calls.
Another alternative would be to use the Proxy class ... which will effectively generate a dynamic proxy. The problem is that this requires an InvocationHandler that will (I guess) use reflection to make the call to the wrapped object. It is complicated and won't be efficient.
If your goal is simply to avoid writing code, I think this is a bad idea. If your goal is to writing the same code over and over (e.g. because you have lots of exampled of C for a given A), then consider coding an abstract class for the C classes that deals with the wrappering / delegation.
It would also be possible to generate the wrapper class C from nothing, using the BCEL library or similar. But that's an even worse idea (IMO).

Decorator Design Pattern in java

I'm designing of a project I have to do. For that, I have thought to use decorator design pattern. However, I have to adjust my design to the existing implementation of the project. Then, I can't keep completely the decorator design pattern.
The project has an abstract base class (called A) and a set of sub-class (called A1, A2, A3, A4, etc.). I can't modify the code of these classes.
Then, I have to add extra funcionality to these classes. For that, I create an abstract class (called B) that use to class A (Decorator). I also create concrete decorators that use to classes A1,A2,A3,A4,...
NOTE: As you see, I don't use any interface because the class A doesn't use any interface and I can't modify this code.
But I see some issues in this design:
1) Classes B1,B2,B3,B4,... have to add all methods of classes A1,A2,A3,A4,... for calling to methods of classes A1,A2,A3,A4... For example, in class B1:
class B1 {
public A1 objectA1;
B1() {
objectA1 = new A1();
}
public void add(int value) {
objectA1.add(value);
// extra funcionality
}
}
It can be a problem because if other developers modify the code of classes A,A1,A2,A3,A4,... they also need to modify the code of B,B1,B2,B3,B4,...
I WANT TO PREVENT THAT.
2) Moreover, classes A,A1,A2,A3,A4 have protected methods that only can be accessed from the own class or sub-classes. As I need to access to these methods, I can't use the decorator design pattern.
SECOND ALTERNATIVE
I could extend the classes A1,A2,A3,A4 with B1,B2,B3,B4. For example:
class B1 extends A1 {
B1() {
objectA1 = new A1();
}
public void add(int value) {
super.add(value);
// extra funcionality
}
}
Of this way, I solve the second problem and avoid to override all methods of A1, overriding only necessary methods. Even so, each time a sub-class of A is created, it's necessary to create the corresponding class B.
I WANT TO PREVENT THAT because it only is necessary that class B (B1,B2,...) override a method of class A (A1,A2,...).
THIRD ALTERNATIVE
Then, I thought that I could consider to class B (B1,B2,...) as a wrapper of class A (A1,A2,...). Of this way, a instance of B will be created as next:
new BMaker.get(A1, params_of_constructor_A1)
new BMaker.get(A2, params_of_constructor_A2)
new BMaker.get(A3, params_of_constructor_A3)
new BMaker.get(A4, params_of_constructor_A4) or
...
new BMaker.get(AN, params_of_constructor_AN)
where BMaker.get is a static method.
public static <T extends A> A get (T objectA, params ) {
// return anonymous class (*1)
}
My question is if it's possible to implement an anonymous class that inherit of A1, A2, ...
Each call to BMaker.get() should be created a different anonymous class deppending on if the first parameter of BMaker.get() is A1,A2,A3,...
Really, I don't know if it's possible to do this or is there another better way.
Any help would be appreciated!
Answer to the first issue:
Either put an interface I on A so your decorators/delegates can implement same interface, or
Create an interface I (equivalent to A's api) and a wrapper class AW which wraps A and implements I by passing all calls straight onto it.
Convert your client code to use I rather than A, and you can then happily proceed to build decorators/ or delegates using the new interface having "wrapped up" the old crunk in AW.
The one notable issue that arises is that some styles of code using A (IdentityHashMaps, persistence) may want a reference to the "underlying" A. If that comes up, you can put a method in the interface getUnderlyingA(). Try and avoid using that too much, since it obviously bypasses all decoration.
Second issue: decorating subtypes.
The question here is whether the subtypes need to be exposed as different decorator types -- or whether one uniform decorator can be exposed, that (maybe, if necessary) is internally aware of the type-system of the A subtypes that it can wrap.
If the subtypes are well-known & stable, you can implement a "handle style" api in the interface. For example, for file-system entities, you would present a handle of a single type but offer isFile(), isDirectory(), isDevice(), isDrive(), isRaw() etc methods for interrogating the type. A listFiles() method could be available to use the directory subtype.
My question is why you need external access (from the decorator) to protected methods? If you do, those methods should be public and the original design is broken/insufficiently extensible.
Maybe you can create a static helper class in the same package (if not changing the A class itself) that will give you proper access to this legacy crunk from your decorator.
There's a certain point here, where doing your job properly does sometimes involve working with & potentially upgrading legacy code. If there isn't an efficient & maintainable design alternative, that shouldn't be a total sticking point. Doubling up the type-system (creating two parallel heirarchies) is definitely not what you should be doing.
If there isn't a good way to do this, you should work on something else (a different feature/requirement) rather than making the codebase even worse.

Can a Parent call Child Class methods?

Referring here
A is a precompiled Java class (I also have the source file)
B is a Java class that I am authoring
B extends A.
How can logic be implemented such that A can call the methods that B has.
The following are the conditions:
I don't want to touch A(only as a
last option though that is if no
other solution exists).
I don't want to use reflection.
As stated, if needed I could modify A.
What could be the possible solution either way?
Class A should define the methods it's going to call (probably as abstract ones, and A should be an abstract class, per Paul Haahr's excellent guide); B can (in fact to be concrete MUST, if the method are abstract) override those methods. Now, calls to those methods from other methods in A, when happening in an instance of class B, go to B's overrides.
The overall design pattern is known as Template Method; the methods to be overridden are often called "hook methods", and the method performing the calls, the "organizing method".
Yes it seems that if you override the super/base-classes's functions, calls to those functions in the base class will go to the child/derived class. Seems like a bad design in my opinion, but there you go.
class Base
{
public void foo()
{
doStuff();
}
public void doStuff()
{
print("base");
}
}
class Derived extends Base
{
#Override
public void doStuff()
{
print("derived");
}
}
new Derived().foo(); // Prints "derived".
Obviously all of Derived's methods have to be already defined in Base, but to do it otherwise (without introspection) would be logically impossible.
I would be rather hesitant to do this. Please correct me if I am wrong and then I will delete, but it sounds like you want to maintain an A object along with a B object. If they indeed are not the same object, the "tying together" (that's a scientific term) you'll have to do would be pretty ugly.

Categories

Resources