remove duplicate code in java - java

class A extends ApiClass
{
public void duplicateMethod()
{
}
}
class B extends AnotherApiClass
{
public void duplicateMethod()
{
}
}
I have two classes which extend different api classes. The two class has some duplicate
methods(same method repeated in both class) and how to remove this duplication?
Edit
Both ApiClass and AnotherApiClass are not under my control

Depending on what the code is you could do something like:
public class Util
{
public static void duplicateMethod()
{
// code goes here
}
}
and then just have the other two duplicateMethods call that one. So the code would not be duplicated, but the method name and the call to the Util.duplicateMethod would be.
If the code in the Util.duplicateMethod needed to access instance/class variables of the A and B class it wouldn't work out so nicely, but it could potentially be done (let me know if you need that).
EDIT (based on comment):
With instance variables it gets less pretty... but can be done. Something like:
interface X
{
int getVar();
void setVar(A a);
}
class A
extends ApiClass
implements X
{
}
class B
extends AnotherApiClass
implements X
{
}
class Util
{
public static void duplicateMethod(X x)
{
int val = x.getVal();
x.setVal(val + 1);
}
}
So, for each variable you need to access you would make a method for get (and set if needed). I don't like this way since it make the get/set methods public which may mean you are making things available that you don't want to be available. An alternative would be to do something with reflection, but I'd like that even less :-)

Sounds like a case for the "Strategy Pattern".
class A extends ApiClass {
private ClassContainingDupMethod strategy;
}
class N extends AnotherApiClass {
private ClassContainingDupMethod strategy;
public methodCallingDupMethod(){
strategy.dupMethod();
}
}
class ClassContainingDupMethod{
public dupMethod(){;}
}
Or is the dupMethod inherted from the Api classes?

Duplicate methods that rely on member variables imply duplicate member variables, too - and that starts to smell like too-large classes. What would those specific member variables, with the method(s), look like, if you were to extract them into their own class, and then compose that class into your other classes? Prefer composition over inheritance.

class BaseApiClass
{
public void duplicateMethod()
{
}
}
class ApiClass extends BaseApiClass
{
}
class AnotherApiClass extends BaseApiClass
{
}
class A extends ApiClass
{
}
class B extends AnotherApiClass
{
}

You need to combine the classes into one object and then all classes using th other two classes, modify their code to use the single class.

Related

Access property/constant in extended classes

I'm trying to achieve the following:
I have a parent class, with some logic. In the child class, I "redefine" constants/properties. Is there any way to make the child properties accessible by methods defined in the parent class? Or to be more specific - is there any way to force the "out" method to write extended rather than base in the following example?
public class BaseTest {
public static final String x = "base";
public void out() {
System.out.println(x);
}
}
public class ExtendedTest extends BaseTest{
public static final String x = "extended";
}
public class Main {
public static void main(String[] args) {
BaseTest base = new BaseTest();
ExtendedTest extended = new ExtendedTest();
base.out(); // base (as expected)
extended.out(); // base (extended expected)
System.out.println(extended.x); // extended (as expected)
}
}
I come mainly from the world of PHP, where this approach works just fine. Dunno if I'm missing something or if the very design of Java does not allow this.
Thank you.
Note: This is not important whether the property is static or not. I just wanted to be able to override a property of any kind in a child class (just like I can override a method) which, on basis of the answers I've received so far, doesn't seem to be possible in Java. In PHP it is absolutely possible and that was why I asked the question.
static fields are not subject to inheritance. The x in the body of the out() method refers to BaseTest.x. Since you are not overriding out(), the body of the out() method still prints the value of BaseTest.x.
Static members are resolved at compile-time, and adding an ExtendedTest.x does not affect the also-existing BaseTest.x, which is what the BaseTest#out() method is linked to.
To accomplish what you're wanting, you need an overridden method:
public class BaseTest {
public String x() {
return "base";
}
public final void out() {
System.out.println(x());
}
}
public class ExtendedTest extends BaseTest {
#Override
public String x() {
return "extended";
}
}
This pattern is commonly used with an abstract method in the base class or interface to require the subclass to define an attribute such as a name or a key.

Have a class be subclass for several super classes

There are several (5+) classes, in code I cannot change, that I need to extend by a few fields. Is there any way to do this without writing (and editing every time I need to change something) the almost exactly same code 5 times? So is there any more elegant way than this:
class Subclass1 extends Superclass1 {
private String newField;
public String getNewField() {
return newField;
}
public void setNewField(String newField) {
this.newField = newField;
}
}
class Subclass2 extends Superclass2 {
private String newField;
public String getNewField() {
return newField;
}
public void setNewField(String newField) {
this.newField = newField;
}
}
//...
I do NOT want multiple inheritance, I want 5 seperate subclasses - just without the duplicate code, because the subclasses all add exactly the same.
The only alternative I can think of is copying the original classes and having the copy extend a Superclass which is probably even worse.
No, you can't do this in Java. You can in certain other JVM-based languages, such as Scala (traits). However, if you must use plain Java, you might consider the following:
Determine the (hopefully single) purpose of the fields you are adding, and the behavior that you want.
Create a new class encompassing all of the fields and the new methods. For example:
public class ExtraFields // Don't use this name!
{
private String myExtraField1;
private String myExtraField2;
// etc.
public void doSomethingWithExtraFields() {
// etc.
}
}
Then, you could take one of the following approaches:
Subclass each of the five classes, and add one field, which is an instance of the class you created above, and delegate behavior accordingly. You will have to use this approach if you must have the extra fields in places where you must pass in one of your five classes. For example:
public class Subclass1 extends Superclass1
{
private ExtraFields extraFields;
public MySubclass()
{
super();
extraFields = new ExtraFields();
}
public void doSomethingWithExtraFields()
{
extraFields.doSomethingWithExtraFields();
}
}
Create a new wrapper class that contains an instance of both your new class created above, and one of those five subclasses. You can make this typesafe using generics. For example:
public class Wrapper<T> // Don't use this name either...
{
private ExtraFields extraFields;
private T myClass;
public Wrapper(T myClass) {
this.myClass = myClass;
this.extraFields = new ExtraFields();
}
}
In this second approach, you don't strictly need the ExtraFields class. But it's still often a good idea to do this so as to encapsulate related functionality.
Hope that helps!
Since you can't change the base classes, it's impossible to eliminate the redundancy. Eric Galluzzo's idea to store the extra fields in a separate class is the best one so far, but I don't know if that's practical in your case. If it isn't, create an interface that defines the extra fields. You'll still have to do a lot of repetitive typing, but at least you'll know immediately when you've made a mistake.
You could use a generic wrapper class, as long as it wouldn't be too tedious to change the rest of the code that works with it.
class Wrapper<E> {
private E obj;
private String newField;
public Wrapper (E obj) {
this.obj = obj;
}
public E get() {
return obj;
}
public String getNewField() {
return newField;
}
public void setNewField(String newField) {
this.newField = newField;
}
}

Two ways to implement a callback, so what is he difference

I have a class which has a method called connect(par1, par2, par3), par3 is an interface/listenr.
To provide par3 i can do as follows:
connect(par1, par2, asynchCallBack2 );
private class asynchCallBack2 implements MqttCallback {
...
...
}
OR:
connect(par1, par2, asynchCallBack2 );
MqttCallback asynchCallBack2 = new MqttCallback {
...
...
}
And in either cases, every thing works jus fine. So what is the difference and in which scenarios each of the implementation is used?
In one case (i.e. where you say implements) you are defining full fledge method local class.
While for the other you are defining anonymous class which is similar to the one where you said implements. Just that you aren't defining the name and say like implements myinterface which is implicit to compiler.
It's just the way you define your class, nothing changes in terms of functionality.
The difference is requirement and handling exceptional cases ,Hope this pseudo code clears it for you
interface Engine{
public void start();
}
private class FerrariEngine implements Engine{
public void preStartRoutine(){}
public void Start(){}
}
private class Main{
private void main(){
Engine engine=getEngine();
if(engine instanceOf FerrariEngine){
((FerrariEngine)engine).preStartRoutine();
}
engine.start();
}
private Engine getEngine(){
if(System==Generic)
return new Engine{
#override
public void start(){
//Do start
}
}
else if(System==Ferrari)
return new FerrariEngine();
}
}
As a general principle,If u need more functionality whilst still being able to adhere to older version, creating an instance of an extended version of that class instead of making an anonymous instance makes sense.

Finite State Machine design problem on Java

I want to implement FSM like below
First Level Most basic State is BASE_STATE. All
states derive from BASE_STATE.
Second Level, WAITING_STATE,
RUNNING_STATE, END_STATE, ... so on
(Derived from BASE_STATE. No new
functionality)
Third level, There are 2 groups
states (ACTIVE and PASSIVE),
One-on-one matching for all second level states
like
ACTIVE_WAITING_STATE , ACTIVE_RUNNING_STATE , ACTIVE_END_STATE, so on
PASSIVE_WAITING_STATE, PASSIVE_RUNNING_STATE, PASSIVE_END_STATE, so on
most functionalities are common for ACTIVE and PASSIVE states, just some small functions overrided. There is no problem until here. Problem is, All third level group have common functions. I mean, For example I have to implement 2 different increment() function one of is ACTIVE_xxx_STATEs, another one is PASSIVE_xxx_STATEs. How to do this without re-written for all states (eg. ACTIVE_WAITING_STATE , ACTIVE_RUNNING_STATE , ACTIVE_END_STATE, and also PASSIVE states)
To clearify my questions, my ugly sol'n. Problem is increment functions is same and re-written for all ActivexxxState (and also PassiveXXXState).
public class BaseState {
// Lots of functions
}
public class WaitingState extends BaseState{
// Lots of functions
}
public class RunningState extends BaseState{
// Lots of functions
}
public class EndState extends BaseState{
// Lots of functions
}
public Class ActiveWaitingState extends WaitingState {
// Few unique functions
private void increment() {
System.out.println("increment active");
}
}
public Class ActiveRunningState extends RunningState {
// Few unique functions
private void increment() {
System.out.println("increment active");
}
}
public Class ActiveEndState extends EndState {
// Few unique functions
private void increment() {
System.out.println("increment active");
}
}
public Class PassiveWaitingState extends WaitingState {
// Few unique functions
private void increment() {
System.out.println("increment passive");
}
}
public Class PassiveRunningState extends RunningState {
private void increment() {
System.out.println("increment passive");
}
}
public Class PassiveEndState extends EndState {
private void increment() {
System.out.println("increment passive");
}
}
I would make increment() a protected method in BaseState so it is implemented once.
I have written an article on using enums to build a state machine. This can avoid the need to create classes everywhere for each state and still support some inheritance.
In answer to your comment.
abstract class BaseState {
public abstract boolean isPassive();
public boolean increment() {
System.out.println("increment "+(isPassize() ? "passive" : "active");
}
}
class PassiveState {
public boolean isPassive() { return true; }
}
If you don't want to have multiple isPassive methods you could assume a class naming convention
public boolean isPassive() { return getClass().getSimpleName().startsWith("Passive"); }
I'm not sure to have fully understand your question. Anyway, I'll suggest you to model active/passive state like a property in your class rather then use inheritance.
Make your hierarchy something like:
public class BaseState {
boolean active; //active or passive
}
public class WaitingState extends BaseState {
}
...
If you share common behaviour in your state machine you have two possibilities to implement that.
1) You can add the common implementation to the base state, so it can be called by any state implementation that inherits from the base state. The visibility of these methods would be protected.
2) A better solution in my oppinion is that you move the common behaviour into its own class that is not related to the states class hierarchy at all.
So you can think about a strategy class that implements the common behaviour and is referenced by the base class and can be called by any state.
The second solution is better because it increases the testability of both, the state machine and the strategy class.

Inner class within Interface

Is it possible to create an inner class within an interface?
If it is possible why would we want to create an inner class like that since
we are not going to create any interface objects?
Do these inner classes help in any development process?
Yes, we can have classes inside interfaces. One example of usage could be
public interface Input
{
public static class KeyEvent {
public static final int KEY_DOWN = 0;
public static final int KEY_UP = 1;
public int type;
public int keyCode;
public char keyChar;
}
public static class TouchEvent {
public static final int TOUCH_DOWN = 0;
public static final int TOUCH_UP = 1;
public static final int TOUCH_DRAGGED = 2;
public int type;
public int x, y;
public int pointer;
}
public boolean isKeyPressed(int keyCode);
public boolean isTouchDown(int pointer);
public int getTouchX(int pointer);
public int getTouchY(int pointer);
public float getAccelX();
public float getAccelY();
public float getAccelZ();
public List<KeyEvent> getKeyEvents();
public List<TouchEvent> getTouchEvents();
}
Here the code has two nested classes which are for encapsulating information about event objects which are later used in method definitions like getKeyEvents(). Having them inside the Input interface improves cohesion.
Yes, you can create both a nested class or an inner class inside a Java interface (note that contrarily to popular belief there's no such thing as an "static inner class": this simply makes no sense, there's nothing "inner" and no "outter" class when a nested class is static, so it cannot be "static inner").
Anyway, the following compiles fine:
public interface A {
class B {
}
}
I've seen it used to put some kind of "contract checker" directly in the interface definition (well, in the class nested in the interface, that can have static methods, contrarily to the interface itself, which can't). Looking like this if I recall correctly.
public interface A {
static class B {
public static boolean verifyState( A a ) {
return (true if object implementing class A looks to be in a valid state)
}
}
}
Note that I'm not commenting on the usefulness of such a thing, I'm simply answering your question: it can be done and this is one kind of use I've seen made of it.
Now I won't comment on the usefulness of such a construct and from I've seen: I've seen it, but it's not a very common construct.
200KLOC codebase here where this happens exactly zero time (but then we've got a lot of other things that we consider bad practices that happen exactly zero time too that other people would find perfectly normal so...).
A valid use, IMHO, is defining objects that are received or returned by the enclosing interface methods. Tipically data holding structures. In that way, if the object is only used for that interface, you have things in a more cohesive way.
By example:
interface UserChecker {
Ticket validateUser(Credentials credentials);
class Credentials {
// user and password
}
class Ticket {
// some obscure implementation
}
}
But anyway... it's only a matter of taste.
Quote from the Java 7 spec:
Interfaces may contain member type declarations (ยง8.5).
A member type declaration in an interface is implicitly static and public. It is permitted to redundantly specify either or both of these modifiers.
It is NOT possible to declare non-static classes inside a Java interface, which makes sense to me.
An interesting use case is to provide sort of a default implementation to interface methods through an inner class as described here: https://stackoverflow.com/a/3442218/454667 (to overcome the problem of single-class-inheritance).
Yes it is possible to have static class definitions inside an interface, but maybe the most useful aspect of this feature is when using enum types (which are special kind of static classes). For example you can have something like this:
public interface User {
public enum Role {
ADMIN("administrator"),
EDITOR("editor"),
VANILLA("regular user");
private String description;
private Role(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
public String getName();
public void setName(String name);
public Role getRole();
public void setRole(Role role);
...
}
It certainly is possible, and one case where I've found it useful is when an interface has to throw custom exceptions. You the keep the exceptions with their associated interface, which I think is often neater than littering your source tree with heaps of trivial exception files.
interface MyInterface {
public static class MyInterfaceException extends Exception {
}
void doSomething() throws MyInterfaceException;
}
What #Bachi mentions is similar to traits in Scala and are actually implemented using a nested class inside an interface. This can be simulated in Java. See also java traits or mixins pattern?
Maybe when you want more complex constructions like some different implementation behaviours, consider:
public interface A {
public void foo();
public static class B implements A {
#Override
public void foo() {
System.out.println("B foo");
}
}
}
This is your interface and this will be the implementee:
public class C implements A {
#Override
public void foo() {
A.B b = new A.B();
b.foo();
}
public static void main(String[] strings) {
C c = new C();
c.foo();
}
}
May provide some static implementations, but won't that be confusing, I don't know.
I found a use fir this type of construct.
You can use this construct to defines and group all the static final constants.
Since, it is an interface you can implement this on an class.
You have access to all the constants grouped; name of the class acts as a namespace in this case.
You can also create "Helper" static classes for common functionality for the objects that implement this interface:
public interface A {
static class Helper {
public static void commonlyUsedMethod( A a ) {
...
}
}
}
I'm needing one right now. I have an interface where it would be convenient to return a unique class from several of it's methods. This class only makes sense
as a container for responses from methods of this interface.
Hence, it would be convenient to have a static nested class definition, which is associated only with this interface, since this interface should be the only place where this results container class is ever created.
For instance traits (smth like interface with implemented methods) in Groovy. They are compiled to an interface which contains inner class where all methods are implemented.

Categories