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.
Related
In my Java project, I have the method addType1AndType2() which has windows where you expand lists and select objects from the list. It was very complicated and time consuming to create, as things must be scrolled and xpaths keep changing. There are two lists in this which are actual names but, due to company proprietary info, I will just call them Tyep1 and Type2.
Now I have an UpdateType1 class which uses all the complicated methodology in the AddType1AndType2 but has nothing related to Type2 in it. I could copy the AddType1AndType2 and cut everything I do not need, but that would be replicating and changes would have to be duplicated in both classes. This defeats the purpose of inheritance and reusability.
I can make a class UpdateType1 extends AddType1AndType2{} which I have done. But there are still methods like selectType2Value() which are inherited but not possible in the subclass.
If I do an #Override and declare the class as private in the sub class, I get an error that I cannot reduce the visibility in a subclass.
Any idea what I can do? Right now I am just putting a throw new AssertError("Do not use") but that seems kind of lame. Is there a better thing to do that would even give a compile-time error rather than an assert at run time, or is this the best way?
The thing is: your model is wrong.
Inheritance is more than just putting "A extends B" in your source code. A extends B means: A "is a" B.
Whenever you use a B object, you should be able to put an A object instead (called Liskov substitution principle).
Long story short: if B has methods that A should not have ... then you should not have A extends B.
So the real answer is: you should step back and carefully decide which methods you really want to share. You put those on your base class. Anything else has to go. You might probably define additional interfaces, and more base classes, like
class EnhancedBase extends Base implements AdditionalStuff {
Edit: given your comment; the best way would be:
Create interfaces that denote the various groups of methods that should go together
Instead of extending that base class, use composition: create a new class A that uses some B object in order to implement one/more of those new interfaces.
And remember this as an good example why LSP really makes sense ;-)
Create the interfaces
public interface IAddType1 {... /* methods signtatures to add Type1 */}
public interface IAddType2 {... /* methods signtatures to add Type2 */}
public interface IUpdateType1 {... /* methods signtatures to update Type1 */}
then your current code at AddType1AndType2 will become just a base helper class:
public abstract class BaseOperationsType1AndType2{
//code originally at AddType1AndType2: methods that add Type1 and Type2
}
then your new AddType1AndType2 class will be:
public class AddType1AndType2
extends BaseOperationsType1AndType2,
implements IAddType1 , IAddType2 {
//nothing special.
}
and your new UpdateType1can be defined as
public class UpdateType1
extends BaseOperationsType1AndType2
implements IUpdateType1 {
//
}
Voila.
You can use 'final' keyword to prohibit extending a method in a subclass.
A method with a 'final' modifier cannot be overriden in a subclass.
I'm creating a grid based game.
I need to implement a set of obstacles that take random positions within the grid.
I've created an abstract class ALifeForm, that holds the common methods for every item within the grid. Obviously, abstract classes can't be initialised, so I was going to create a new class AObstacle, which will extend ALifeForm.
Only issue is, my AObstacle class isn't specialised. All the methods it needs are within ALifeForm.
Can I have an empty class?
Is it bad programming practice? And if so, what can I implement instead?
Of course...
class AObstacle { }
(Plus whatever inheritance model you're using.) There's nothing stopping you from doing this.
Remember that a class isn't really a thing that you're defining. A type is. The class is just the language/syntax construct used to describe the type. If the type being described has no attributes or operations aside from the inheritance model, then there's nothing else to add to it.
Though you are adding one thing. You're giving it a name. It doesn't sound like much, but defining a semantic concept with a concrete name (particularly in a statically typed environment) is very important. Your type now has an identity apart from other types in the system. If things are added to it later, there's a place to add them without refactorings and breaking changes.
Well to do it you don't need to have an abstract class and a class that extends it, or an empty class(wich is possible too).
First way:
You just need to implement two classes: The class that contains the methods and the variables you need to use and the second calss that has an instance of your first class:
public class A{
public void firstMethod(){
//do your stuff here
}
....
}
public class B{
public static void main(String[] args) {
A a=new A(); //instantiate your class here
a.firstMethod();// then just use its methods
}
}
Because if you implement a class that extends an abstract class it should implement all its methods.
Second way:
Or if you want your second class to be specialized you could have :
your first class wich should not be abstract and the second one can extend it and use all its methods, and have its specific methods
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.
First of all this is not a question about how to implement an interface in Java, or about an error with interfaces. This is a question about the right way to do it, depending on the situation.
First of all i would like to apologize if this is not the correct "stack" to post this question, please let me know and i'll move it to another one.
Let's begin.
What i'm trying to guess is which is the best way to implement an interface in Java. Let's say we have a class A like:
public Class A {
public A(){}
public void fooA() {}
}
And an interface
public interface MyListener {
public void fooListener();
}
Inside fooA() I'm making use of interface B this way:
...
something.setFooListener(/**Doubts here**/)
....
What should we type inside setFooListener(...)
Options are (As far as i know):
A) Define the behavior inside the setFooListener function:
new MyListener.fooListener() {
/** Implementation of fooListener() **/
}
Pros:
Easy and readable as you're reading the function.
You can access directly to FINAL variables defined in fooA().
Cons:
If your implementation is long enough it would end up in a lack of readability and a too long function.
If you're implementing the interface in a few places on the same class you are going to repeat a lot of code.
B) Create an inner class implementing the interface:
private class MyListenerImplementation implements MyListener {
private String var1;
private int var2;
public MyListenerImplementation() {/** constructor **/}
public void fooListener() {
/** Do logic here **/
}
}
Pros:
You can keep a reference to the object MyListenerImplementation.
You can define variables, functions and everything as it's an object like any other one.
Cleaner code.
Cons:
Maybe needs more memory.
Maybe creating unnecessary classes
C) Hold a variable with a reference to the interface implementation
private MyListener.FooListener myListenerVar = new MyListener.FooListener() {
/** Logic goes here **/
};
Pros:
I actually can't sees anyone comparing to B, but a lot of cons.
Cons:
Not a clean code. Doing this on top of your class would be, at least, a war crime.
I don't think it's correct to assign a block of code to a variable.
I don't like how this looks ;)
D) The last one i could think of; define a function and inside return the implementation
private MyListener.fooListener createMyListener() {
return new MyListener.fooListener() {
/** Logic goes here **/
}
}
Pros:
It's cleaner than C.
Reusability
Cons:
Almost the same ones as C.
I don't think it's correct to return a whole block of code.
To sum up: Which i like the most is "B", but i would like to know what does SO thinks of this.
Thanks in advice.
Option A is not syntaxically correct. Your pros and cons are valid.
Option B:
Maybe needs more memory: no.
Maybe creating unnecessary classes: no. Option A also creates a class. It's anonymous, but it's a class, that must be loaded by the ClassLoader like any other class.
Option C: it's exactly the same as A (anonymous class usage), except you initialize a field with the listener. The rule is the same as for any other variable: reduce its scope as much as possible. If you need a field scope, use this option. If you only need the listener in one method, then use a local variable (option A).
Option D: once again, it's the same as A, except you return the created listener instead of only using it.
My recap: you're mixing three orthogonal problems here.
Should I use an anonymous inner class, a named nested class, or a top-level class. This depends on the amount of code contained in the class, and on where you need to use this class: in a single top-level class, or in many top-level classes.
Should I use local variables or instance variables. it's a matter of scope and state, not a matter of interface implementations. Your field or local variable can be initialized with an instance of any kind of your interface implementation
Should you use a factory method returning instances, or should you use new directly. Once again, that has nothing to do with how your interface is implemented. If you want to be loosely coupled, because the factory method might return different implementations of the same interface, use a factory. Otherwise, new is fine.
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.