This is more of a best practice / performance related question specific to Android.(I understand this could be a generic discussion but I wanted it to be narrowed down taking into account the Android environment).
Lets say I have a method (which checks for conditions and redirect the user to various activities). This method is used by a lot of classes.
I'm unable to decide whether to add this method in a utility class, make it static and call it from every activity that requires it.
Or
Create a base activity, add the method in there, and any activity that needs to use this method, inherit from the base activity. (Assuming we're Ok with single inheritance in this particular case).
Thoughts ?
EDIT These are the related SO posts I have checked related to this. Couldn't form a decision based on these
If a "Utilities" class is evil, where do I put my generic code?
There would also be the possibility to inject the class in the constructor when it is needed. When you use this approach you could easily mock this class behind an interface and it is possible to create tests with a mock.
As example some pseudo code:
Your Utility
class:
public class Utility implements IUtility {
@Override
public void add() { ... }
@Override
public void remove() { ... }
}
Your Utility
using class:
public class UtilityUsingClass {
private IUtility utility;
public UtilityUsingClass(IUtility utility) {
this.utility = utility;
}
public void myMethod() {
// Use Utility class
utility.add();
...
}
}
In the test it can look like this:
@Test
public void testMyMethod() {
UtilityUsingClass testClass = new UtilityUsingClass(new UtilityMock());
testClass.myMethod();
// assert stuff
}
The UtilityMock
:
public class UtilityMock implements IUtility {
@Override
public void add() { // Implements mock logic ... }
@Override
public void remove() { // Implements mock logic ... }
}