I have a big method doComplicateCalculation in abstract class - AbstractClass.
Also have small class Descendant that extends AbstractClass.
I need to introduce in method doComplicateCalculation small changes like:
..............
if (val<0){
continue;
}
..................
The problem also more difficulta that big method in internal class of abstract class.
How it can be done?
Thanks.
This might not be the best answer; but it is the best answer I can give with the information provided. If anything it will get you thinking in the about ways you can address this (because if you're going to be programming for a while, then it won't be the last time you run into problems like this).
In your abstract class, put this:
if (doContinue(val)){
continue;
}
Then, define the method in your abstract class...
protected boolean doContinue(int val) {
// Or, put return true if you always want it to do this
return false;
}
Then, override this method in your concrete class, like this...
protected boolean doContinue(int val) {
return val < 0;
}
You need to break the big method in pieces, so that you can override the part you need.
That is a difficult question to try to answer generically. One thing that you could do is to try to break up the algorithm in doComplicateCalculation as much as possible. To add the validation maybe make each class extending doComplicateCalculation implement a public boolean
validate
You could even do this before or at different times throughout the algorithm. If that isn't possible you could also just override this method (or override some part of the method if you could break it up).
Related
There is a possible optimization I could apply to one of my methods, if I can determine that another method in the same class is not overridden. It is only a slight optimization, so reflection is out of the question. Should I just make a protected method that returns whether or not the method in question is overridden, such that a subclass can make it return true?
I wouldn't do this. It violates encapsulation and changes the contract of what your class is supposed to do without implementers knowing about it.
If you must do it, though, the best way is to invoke
class.getMethod("myMethod").getDeclaringClass();
If the class that's returned is your own, then it's not overridden; if it's something else, that subclass has overridden it. Yes, this is reflection, but it's still pretty cheap.
I do like your protected-method approach, though. That would look something like this:
public class ExpensiveStrategy {
public void expensiveMethod() {
// ...
if (employOptimization()) {
// take a shortcut
}
}
protected boolean employOptimization() {
return false;
}
}
public class TargetedStrategy extends ExpensiveStrategy {
#Override
protected boolean employOptimization() {
return true; // Now we can shortcut ExpensiveStrategy.
}
}
Well, my optimization is a small yield on a case-by-case basis, and it only speeds things a lot because it is called hundreds of times per second.
You might want to see just what the Java optimizer can do. Your hand-coded optimization might not be necessary.
If you decide that hand-coded optimization is necessary, the protected method approach you described is not a good idea because it exposes the details of your implementation.
How many times do you expect the function to be called during the lifetime of the program? Reflection for a specific single method should not be too bad. If it is not worth that much time over the lifetime of the program my recommendation is to keep it simple, and don't include the small optimization.
Jacob
Annotate subclasses that overrides the particular method. #OverridesMethodX.
Perform the necessary reflective work on class load (i.e., in a static block) so that you publish the information via a final boolean flag. Then, query the flag where and when you need it.
maybe there is a cleaner way to do this via the Strategy Pattern, though I do not know how the rest of your application and data are modeled but it seem like it might fit.
It did to me anyhow when I was faced with a similar problem. You could have a heuristic that decides which strategy to use depending on the data that is to be processed.
Again, I do not have enough information on your specific usage to see if this is overkill or not. However I would refrain from changing the class signature for such specific optimization. Usually when I feel the urge to go against the current I take it as a sing that I had not forseen a corner case when I designed the thing and that I should refactor it to a cleaner more comprehensive solution.
however beware, such refactoring when done solely on optimization grounds almost inevitably lead to disaster. If this is the case I would take the reflecive approach suggested above. It does not alter the inheritance contract, and when done properly needs be done once only per subclass that requires it for the runtime life of the application.
I know this is a slightly old question, but for the sake of other googlers:
I came up with a different solution using interfaces.
class FastSub extends Super {}
class SlowSub extends Super implements Super.LetMeHandleThis {
void doSomethingSlow() {
//not optimized
}
}
class Super {
static interface LetMeHandleThis {
void doSomethingSlow();
}
void doSomething() {
if (this instanceof LetMeHandleThis)
((LetMeHandleThis) this).doSomethingSlow();
else
doSomethingFast();
}
private final void doSomethingFast() {
//optimized
}
}
or the other way around:
class FastSub extends Super implements Super.OptimizeMe {}
class SlowSub extends Super {
void doSomethingSlow() {
//not optimized
}
}
class Super {
static interface OptimizeMe {}
void doSomething() {
if (this instanceof OptimizeMe)
doSomethingFast();
else
doSomethingSlow();
}
private final void doSomethingFast() {
//optimized
}
void doSomethingSlow(){}
}
private static boolean isMethodImplemented(Object obj, String name)
{
try
{
Class<? extends Object> clazz = obj.getClass();
return clazz.getMethod(name).getDeclaringClass().equals(clazz);
}
catch (SecurityException e)
{
log.error("{}", e);
}
catch (NoSuchMethodException e)
{
log.error("{}", e);
}
return false;
}
Reflection can be used to determine if a method is overridden. The code is a little bit tricky. For instance, you need to be aware that you have a runtime class that is a subclass of the class that overrides the method.
You are going to see the same runtime classes over and over again. So you can save the results of the check in a WeakHashMap keyed on the Class.
See my code in java.awt.Component dealing with coalesceEvents for an example.
it might be another workaround which is similar to override another protected method returns true/false
I would suggest creating an empty interface, markup interface, then make the subclass implements this interface and inside the superclass check that this instance is instanceof this interface before calling the overridden expensive method.
My Java is rusty-as-hell, and this threw me completely. I'm sure the answer is simple, but here's a simple example method that switches one Thingy off (if there's one already on) and another on:
private Thingy store;
public void switchiton(final Thingy pThingy) {
if (store != null)
store.endit();
pThingy.startit();
store = pThingy;
}
Problem: pThingy may be a subclass (e.g. CleverThingy) and not the superclass (Thingy), and CleverThingy overrides the endit method.
That code will always run the endit method in Thingy though - not the overridden one in CleverThingy (as it's declared as a Thingy and not a CleverThingy).
Obviously the method has no idea (and should not need one) about subclasses.
What am I missing that is staring at me in the face?
Update:
The subclass in this case is created "on the fly" (not sure of the correct term) rather than formally extended - e.g. in my Game class I have:
startthingy = new Thingy();
gamethingy = new Thingy() {
#Override
public void endit() {
// override things in here
super.endit();
}
}
switchiton(gamethingy); // DOES call gamethingy's overridden startit
switchiton(startthingy); // << gamethingy's overridden endit is NOT called!?
Simplest way to close this off is to answer it myself I think...
The commenters confirmed that how I thought it SHOULD work is how it actually should - this means the error is clearly elsewhere in the code...
I'm going to re-write all the anonymous classes to make them easier to debug and change a few of it's more dubious behaviours in the hope that tracks the error down
The core problem I asked - isn't really a problem tho, so...
Thanks for that!
I don't know if this is exactly the answer you are looking for (because it changes the Thingy class instead of the switchItOn() method), but I think I found a fairly easy and safe solution to your problem. If you are worried about someone extending Thingy and not properly doing whatever the endit() method needs to do, you could make it final. This will make it so that whatever is required to do in the endit() method will always be done and that method can't be overridden.
If you still want subclasses to be able to have flexability with that class, you could try something like this:
public class Thingy {
public void storeIt() {
//do stuff
}
public final void callEndIt() {
//do whatever stuff needs to be done every time in order for your program to work
endIt();
}
public void endIt() {
//this can be extended by subclasses safely
}
}
Then, you can just always call callEndIt() instead of endIt() so that whatever safety precautions you need to have done get fulfilled.
I have read Item 16 from Effective Java and
Prefer composition over inheritance? and now try to apply it to the code written 1 year ago, when I have started getting to know Java.
I am trying to model an animal, which can have traits, i.e. Swimming, Carnivorous, etc. and get different type of food.
public class Animal {
private final List<Trait> traits = new ArrayList<Trait>();
private final List<Food> eatenFood = new ArrayList<Food>();
}
In Item 16 composition-and-forwarding reuseable approach is suggested:
public class ForwardingSet<E> implements Set<E> {
private final Set<E> s;
public ForwardingSet(Set<E> s) {this.s = s;}
//implement all interface methods
public void clear() {s.clear();}
//and so on
}
public class InstrumentedSet<E> extends ForwardingSet<E> {
//counter for how many elements have been added since set was created
}
I can implement ForwardingList<E> but I am not sure on how I would apply it twice for Animal class. Now in Animal I have many methods like below for traits and also for eatenFood. This seems akward to me.
public boolean addTrait (Trait trait) {
return traits.add(trait);
}
public boolean removeTrait (Trait trait) {
return traits.remove(trait);
}
How would you redesign the Animal class?
Should I keep it as it is or try to apply ForwardingList?
There is no reason you'd want to specialize a List for this problem. You are already using Composition here, and it's pretty much what I would expect from the class.
Composition is basically creating a class which has one (or usually more) members. Forwarding is effectively having your methods simply make a call to one of the objects it holds, to handle it. This is exactly what you're already doing.
Anyhow, the methods you mention are exactly the sort of methods I would expect for a class that has-a Trait. I would expect similar addFood / removeFood sorts of methods for the food. If they're wrong, they're the exact sort of wrong that pretty much everyone does.
IIRC (my copy of Effective Java is at work): ForwardingSet's existence was simply because you cannot safely extend a class that wasn't explicitly designed to be extended. If self-usage patterns etc. aren't documented, you can't reasonably delegate calls to super methods because you don't know that addAll may or may not call add repeatedly for the default implemntation. You can, however, safely delegate calls because the object you are delegating to will never make a call the wrapper object. This absolutely doesn't apply here; you're already delegating calls to the list.
This is really a general Java question but I figured it would be easier to explain with the specific Webdriver perspective from which it arose.
I have a complicated page object that I now want to make abstract, because I found another page that is very similar but different in key ways. Now many of my methods, which had returned instances of the page object, are broken. I want to keep the bulk of the code for these methods in the abstract class and still have them return instances of the new subclasses; these methods should return new instances of whatever subclass called them.
Here is an example with a navNextPage method which is common to both of the subclasses. This seems to work, but it feels wrong:
public abstract class PresContentPage {
protected PresContentPage navNextPage() {
// code to navigate to the next page goes here
return null;
}
}
public class MainContent extends PresContentPage {
public MainContent navNextPage() {
super.navNextPage();
return new MainContent(...);
}
}
// And so on with another subclass...
So, this does what I want: the code for the navNextPage method is siloed in the abstract class, but the version that gets called will return the page object of the type that invoked the method.
I just feel wrong having my protected method, which is not and cannot be void, return null. But since it's protected, and it's an abstract class, no one will ever be able to call it anyway, right? Does that make it okay? Is there a way better way to do this that I just never learned?
Another option I thought of is to just make a void method with a different name like navNextPageVoid and have the subclasses call that instead of super.navNextPage, but... that seems sort of gross in a different way.
Thanks in advance!
Typically if you want to force a method to be implemented in a specialisation you make it abstract in the generalisation. Therefore
public abstract class PresContentPage {
abstract PresContentPage navNextPage(); }
What I wanna do is a method that can
generate instance of Class X (a class variable passed in arg) and
override some of it's method
More specifically, the parent class X I want to override contains
Contains no default constructor (e.g. all constructors with args)
Constructors calling non-private method within the same class
Originally I thought it's quite simple to use reflection or something similar,
Then I found there's limitation on implementing my requirement.
For refection: Can only override "interface" via java.lang.reflect.Proxy
http://download.oracle.com/javase/1.3/docs/guide/reflection/proxy.html
for cglib: it cannot create instance of no default constructor and constructor calling non-private member methods
http://insufficientinformation.blogspot.com/2007/12/spring-dynamic-proxies-vs-cglib-proxies.html
I think this is achievable, since Mockito can do all kinds of method injection runtime.
Please anyone give some advise, Thanks.
The pseudo-code I image is like this:
createAndOverride(Class X) {
X newObj = X.newInstance(args) {
#override
methodOfX(args2) {
...
}
}
return newObj;
}
Original problem scenario
I was intended to test a Class which has several methods calling X1.get(), X2.get(), X3.get()
In some test case, I need to make Xn.get() to return something I can control for test (e.g. null)
Due to below constraint:
But due to mock tool restriction to JMock 1.0 (I have no control :( ), so I cannot just simply mock Xn.get() to returns "someSpecifiedObjects"
Xn has no null constructors and constructors calling non-private member
My workaround is self made Xn Class and pass them to test case to let Cn.get() to be expected
code example:
ClassToTest.SomeMethod(new X1() {
#override
get() {
return someSpecifiedObjects;
}
});
And this kind of thing is spread-ed over the Test Case.
Therefore, In order to reduce duplicate code, I would like to build a method to generate Xn instance with specified overrided method for test. e.g.
X1 x1 = createAndOverride(X1);
Then, the problem of this post comes
are you looking for something like javassist? You can instrument code and inject your methods at runtime. I personally try to avoid byte code manipulation as much as possible. Can you not have these overrides in your code base rather than doing on the fly? May be something like wrappers?
So what I think you need is a similar functionality to C#'s Reflection.Emit:
Using Reflection.Emit to create a class implementing an interface
Java Equivalent of Reflection.Emit
Dynamically Create Java Classes With JavaClassCreator
While I haven't done this myself, I think you should be able to use reflection/emission and dynamic type creation in order to achieve what you're looking for. However, I would still like to mention that if you're trying to test "functionality" that's not int he code path of the function you're testing, then you probably shouldn't be testing it at all. For example:
SomeObjectInterface get()
{
if(_someObjectStateIsSet)
{
// Return a concrete implementation A
return new ConcreteImplA();
}
else
{
// Return a concrete implementation B
return new ConcreteImplB();
}
}
In this case get has no code path that would return null, so you shouldn't need to test for null. I'm not sure if I understood your question 100% correctly, especially why you're testing for null, but consider the above advice and see what works for you.