0

The story goes like this:

I have an abstract class called Algorithms and a lot of classes that extend it. Some of them have parameters to tune. Some have none, and some have up to 5.

I would like to have a method in Algorithms that can tune an arbitrary parameter. e.g.:

public static void tune (String paramName, double minValue, double MaxValue) 
{ ... }

So that I can call it like this on 'class SoftRankBoots extends Algorithm':

Algorithm srb = new SoftRankBoost();
srb.tune("delta", 0, 1);

Note that SoftRankBoost has an instance variable 'double delta';

How can I achieve this?

Thank you.

3
  • What happens when you call srb.tune("delta", 0, 1)? Does it use some method to choose an optimal delta? (In which case, how do you want it to work when tuning multiple parameters?) Commented Dec 14, 2010 at 1:48
  • @Michael this would only tune one parameter at a time. Multiple parameters can be tuned as while (...) { blah.tune("one", 0, 1); blah.tune("two", 0, 1); } Commented Dec 14, 2010 at 22:41
  • @Michael the abstract class Algorithm obviously has an abstract method to test performance given current state of parameters. Commented Dec 14, 2010 at 22:42

3 Answers 3

3

Instead of implementing the method tune in the Abstract class leave it an abstract method, that implementing classes must implement.

So

public abstract void tune (String paramName, double minValue, double MaxValue);

With out seeing the whole picture of what you are trying to do it is hard to give you better advice. But what you are suggesting just seems like a bad idea in general.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 for "what you are suggesting just seems like a bad idea in general"
It's a bad idea in general, but this IS one of those cases where it's applicable.
2

Take a look at the Reflections API:

Last link contains example source code.

Note: If you need reflection in Java, then your design may be not as clean, as it could be.

4 Comments

Mhm: I ended up calling: this.getClass().getDeclaredField(paramName).setDouble(...);
If reflection is the solution, there's a very good chance that your design is the problem.
@Laurence: Agreed. Added a short note to my post.
@both of you: My design is just fine. In fact, it is the only way to do this. THE ONLY. I've spent considerable time into this, so just trust me on this one.
0

I think the sub-classes of 'Algorithm' class are differ from each other, so the Template Method pattern or the Strategy pattern may give you some useful concept to solve your problem.

1 Comment

I'm already using the template method. You are not answering the question not one bit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.