Reputation: 168
I have an old code in Java which has a method that returns a guava ArrayTable<>. Now, I have a requirement in which I want to check the number of rows which will be in the arrayTable and depending upon the number, I need to take a decision to actually fetch the ArrayTable or not.
ArrayTable foo(..args) {}
The method calls internal APIs whose results I combine to form the ArrayTable. Those internal APIs have their row count utilities which fetch row count without any overhead.
My question is what would be the best way to go about this? From what I could think, there may be 2 ways:
Change return type based on an extra parameter by using Generic return type
T foo(..args, boolean fetchRowCount) {
if (fetchRowCount == true) {
return (Integer) rowCount;
}
else {
//do the normal thing
return (ArrayTable<>) output;
}
}
Upvotes: 0
Views: 62
Reputation: 715
No, that is not advisable.
You could create a new class FooResult
that contains a flag, and can contain either the rowCount or the output:
class FooResult {
private boolean outputAvailable;
private Integer rowCount;
private ArrayTable<> output;
public FooResult(Integer rowCount) {
this.outputAvailable = false;
this.rowCount = rowCount;
}
public FooResult(ArrayTable output) {
this.outputAvailable = true;
this.output = output;
}
// getters
}
Then your foo
method should have FooResult
as its return type, and return like this:
if (/* some condition */) {
return new FooResult(rowCount);
} else {
return new FooResult(output);
}
Finally the process that calls this should check the flag, and get either the rowCount or the output from the result object depending on the value of the flag.
if (result.isOutputAvailable()) {
// do stuff with result.getOutput()
} else {
// do stuff with result.getRowCount()
}
It's probably simpler to just create two separate methods though.
Upvotes: 1
Reputation: 112
I would simply use two methods and reconsider how I consume the methods instead. I would call the method that retrieves the row count first and then based on that decide whether to call the second one or not.
Upvotes: 0
Reputation: 114
I would suggest to override the method with the extra param, and use the existing method to fetch the arrayTable, and only do the extra work (computing the number of rows) in the overridden method.
ArrayTable foo(... args) {} //existing method
Integer foo(... args, fetchRows) {
arrayTable = foo(args);
// do the rest here
}
This way you can mitigate the risk of adding any regression, and also the code change you have to make for this would be minimal.
Upvotes: 1