Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to avoid duplicate code when using Fragments

I have an app ready and running in the Google Play store, now i am implementing fragments.

so,i already have a class A which extends B with some methods, now i have class which C extends FragmentActivity, so now i need use the same methods as in class A but here since i am extending FragmentActivity i cannot make use of class B, so here there are duplicate methods which are same as class A but i need to reuse the methods.

This below example shows my situation:

Eg:

Current implementation

class A extends B{

one();
two();

}

After integrating fragments,

Eg:

class C extends FragmentActivity{

one();// same methods as in class A
two();// same methods as in class A

}

1) What is the best way to re-use the methods in this case and how?

2) I have approach in my mind like creating a class and make the methods as static and re-use the methods in both A and C class, but is my approach good and can i make the methods as static and is it a good approach ?

3) Another approach that i have thought of "Strategy Pattern".

Eg:
class A extends ApiClass {
   private ClassContainingDupMethod strategy;
}

class N extends AnotherApiClass {
   private ClassContainingDupMethod strategy;

   public methodCallingDupMethod(){
      strategy.dupMethod();
   }
}

class ClassContainingDupMethod{
   public dupMethod(){;}
}

Is the "Strategy Pattern". a good approach ? as i need to create object of common class in both the classes.

Any suggestions on this would be appreciated.

like image 836
Goofy Avatar asked Dec 16 '13 11:12

Goofy


People also ask

What is duplicate code fragment?

Code Inspection: Duplicated code fragmentReports duplicated blocks of code from the selected scope: the same file or the entire project. The inspection features quick-fixes that help you to set the size of detected duplicates, navigate to repetitive code fragments, and compare them in a tool window.

How do you avoid code duplication in C++?

The conventional approach to reduce this kind of code duplication is to move the common code to a member function, which can be called from all the constructors. Usually, that member function is called init.

How do I ignore duplicate codes in Intellij?

Ignore names and values while searching for duplicatesPress Ctrl+Alt+S to open the IDE settings and select Editor | Duplicates. Select file types to which the analysis should apply and select the checkboxes next to the constructs that you want to anonymize. Apply the changes and close the dialog.

What refactoring can be used when a method is too long has duplicated code?

If the duplicate code is inside a constructor, use Pull Up Constructor Body. If the duplicate code is similar but not completely identical, use Form Template Method. If two methods do the same thing but use different algorithms, select the best algorithm and apply Substitute Algorithm.


4 Answers

Get rid of inheritance as much as you can. You don't need it. Class inheritance is almost always a bad idea, especially if you expect lots of future changes in your implementation. The only time it is really necessary is when a poorly designed framework requires you to extend some base class.

When reading the old design patterns from Gamma et al., bear in mind that they were written for a world where C++ and Pascal were the dominant OO languages. Java was still in its infancy and introduced a novelty (interfaces) that neither of those languages had. So, you should mentally replace a lot of the uses of extends with implements and you'll end up with better code.

Basically, keeping coherence high, and coupling low is a good idea in object oriented design. Class inheritance can easily lead to highly coupled classes with low coherence (lots of unrelated functionality in one class). The reason is that the base class ends up having functionality that is not needed by all sub classes, or code paths that are only relevant for some. Additionally, as your design evolves, you end with lots of classes that inherit from each other and are very tightly coupled. I personally hate having to deal with code with multiple levels of inheritance. It's hard to read and the semantics of inheritance make testing more painful as well. I never use extends other than for interfaces and I've been doing Java since the mid nineties.

@Babibu's suggestion of using composition and delegation is a much better alternative for this reason. It leads to more coherent classes that are much less tightly coupled. Easier to maintain, easier to recompose, easier to test, etc.

like image 157
Jilles van Gurp Avatar answered Oct 16 '22 18:10

Jilles van Gurp


Its more simple than you describe. All you need to do is create D like this:

public class D{
   one();
   two();
}

Change class A to use class D.

   public Class A{
       public D dLogic;
   }

Same with class C.

public Class C extends FragmentActivity{
       public D dLogic;
   }

This is some thing very basic in object-oriented programming it call composition.

like image 33
Ilya Gazman Avatar answered Oct 16 '22 19:10

Ilya Gazman


I suspect you have some utility methods, just put them inside a class Utils, make them static and call them from wherever you want. I have lot of utility classes in my application like WifiUtils, LogUtils, NumberUtils and so on.

like image 21
M-WaJeEh Avatar answered Oct 16 '22 17:10

M-WaJeEh


If you want to force the same API, you can try adding an interface to both A and C classes, while keeping an instance of A as a field of C. C will act as a wrapper class of A.

Class A:

class A extends B implements CommonApi {
    public void one() {
        ...
    }

    public boolean two() {
        ...
    }
}

Class C:

class C extends FragmentActivity implements CommonApi {
    private A a;

    public void one() {
        a.one();
    }

    public boolean two() {
        return a.two();
    }
}
like image 37
Juan Sánchez Avatar answered Oct 16 '22 19:10

Juan Sánchez