Generalisation of function in Java

100 views Asked by At

How can I generalize pendulumManagement() to take as arguments the names of the functions to fire and the boolean to decide on? I'm using java and processing library.

void pendulumManagement()
{
  if (pendul) {
    singlePendulumManagement();
  } else {
    dublePendulumManagement();
  }
}
2

There are 2 answers

3
Hernán Alarcón On

It seems that you want to use a flag argument. From that article:

A flag argument is a kind of function argument that tells the function to carry out a different operation depending on its value.

[...]

My general reaction to flag arguments is to avoid them. Rather than use a flag argument, I prefer to define separate methods.

[...]

My reasoning here is that the separate methods communicate more clearly what my intention is when I make the call.

My advice would be to think about that design choice again and reconsider if you actually should do it that way. The article mentioned above has more details about cases like the one that you describe.

0
laancelot On

While I like generalization as a general rule, I don't think that your program would benefit from it in this case. Yet I too feel the appeal of shortening these to one-liners.

You can still write them as one-liners and get a similar result, like this:

if (pendul) { singlePendulumManagement(); } else { dublePendulumManagement(); }

But the issue is that if you use auto-format it'll revert to several lines. Another option would be to use the ternary assignment operator '?', but for this to work you would need your methods to have a return type and use it to assign a value, which would be bad practice if unneeded. Still, here's how it would be done with a simple example:

void setup() {
  size(800, 600);
  background(255);

  boolean isRect = true;
  boolean whatever;
  
  whatever = isRect ? drawRectangle() : drawCircle();
  isRect = false;
  whatever = isRect ? drawRectangle() : drawCircle();
}

void draw() {
}

boolean drawRectangle() {
  rect(100, 100, 200, 100);
  return true;
}

boolean drawCircle() {
  circle(600, 300, 100);
  return true;
}

In this example, the whatever boolean has no real purpose, and the method's return either, which is why I dislike the idea, but if your methods had return types you could realistically use this trick to make your calls look like this:

boolean whatever;
switch(mode) {
case 1: //1 - gravitation
  whatever = field ? centralFieldManagement() : homogeneousFieldManagement();
  break;
case 2: //2 - pendulum
  whatever = pendul ? singlePendulumManagement() : dublePendulumManagement();
  break;
// etc etc..
}

Which, as I said, isn't great. If you don't use the auto-format at all, using the first form (to write the if on one line) would not only do the trick but also isn't much different from your initial idea in term of lines, characters and number of arguments.

Good luck!