user1883212
user1883212

Reputation: 7849

Method with ignored parameters

The parameter "y" here is totally ignored under some circumstances (when x > 10):

public doTask(int x, int y) {

    if (x > 10) {
        return x * 10;
    }
    else {
        return (x * 10) + y
    }
}

I think it's quite misleading to have a method whose parameters can be ignored. How could I rewrite the above code to avoid this problem?

Upvotes: 1

Views: 234

Answers (4)

n0idea
n0idea

Reputation: 742

What about this?

public doTask(int x, int y) {
    return x * 10 + (x > 10 ? 0 : y);
}

Upvotes: 0

James Perkins
James Perkins

Reputation: 1

You are using the if else statemenet exactly how it should be used, yes technically you could if coding using Java 8 standards use the Optional (https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html) but for the example above would be more than overkill. What you have is perfectly acceptable and makes the most sense.

Upvotes: 0

TheLostMind
TheLostMind

Reputation: 36304

You could use Java 8's Optional type and pass y in it if needed. But I strongly feel that that would be an overkill. y is being used in atleast one code flow, so it is completely valid to accept it in the method signature as it is.

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234635

You could use return x * 10 + y * (x > 10 ? 0 : 1);

But I don't really see an issue with what you currently have, and my alternative might be less clear to some readers.

There are plenty of cases in mathematical programming when for certain cases, a variable has no effect. For example, the amplitude function A * Math.sin(omega * t), occasionally does not "require" A.

Appropriate unit tests on your function could weed out any bugs.

Upvotes: 2

Related Questions