Returning multiple values from a method - methods

I have a method drive that goes like this:
public double drive(double milesTraveled, double gasUsed)
{
gasInTank -= gasUsed;
return totalMiles += milesTraveled;
}
I know I can't return multiple values from a method, but that's kind of what I need to do because I need both of these values in my main method, and as it is now it's obviously only returning the one. I can't think of anything that would work. Sorry if this is a super beginner question. What can I do to get both values to return from the method?

You can return multiple value from a function. To do this You can use structure.
In the structure you can keep required field and can return structure variable after operation.
You can also make a class for the required field if You are using OOPS supporting language but Structure is best way.

In most languages you can only return a single value from a method. That single value could be a complex type, such as a struct, array or object.
Some languages also allow you to define output parameters or pass in pointers or references to outside storage locations. These kinds of parameters also allow you to return additional values from your method.

not sure, but can you take array of your values?
array[0]=gasInTank;
array[0] -= gasUsed;
array[1]=milesTraveled;
array[1] -= milesTraveled;
return array;

Related

Returning multiple values in UDF

I have written an AggregateFactory Vertica UDF which returns a single value
getReturnTypes(si,columnTypes args,columnTypes returnTypes){
returnTypes.addVarbinary(512);
//I want to add second returnType
returnTypes.addFloat("");
}
getProtoType(si,columnTypes args,columnTypes returnTypes){
returnTypes.addVarbinary(512);
//I want to add second returnType
returnTypes.addFloat("");
}
this is not working, how can I return two values from an AggregateFactory UDF?
You cannot. User Defined Aggregate Functions (as explained in the fine manual) return ONE value per group. You might want to write a User Defined Transform Function (maybe a multi-phase Transform Function).

Bang methods in Groovy

Does Groovy have something similar to bang methods on Ruby?
From this blog post:
In Ruby, you can write methods whose names end in ! (exclamation point or “bang”). There’s a lot of confusion surrounding the matter of when, and why, you would want to do so.
The ! in method names that end with ! means, “This method is dangerous”—or, more precisely, this method is the “dangerous” version of an otherwise equivalent method, with the same name minus the !. “Danger” is relative; the ! doesn’t mean anything at all unless the method name it’s in corresponds to a similar but bang-less method name.*
And this site:
You'll find a number of pairs of methods, one with the bang and one without. Those without the bang perform an action and return a freshly minted object, reflecting the results of the action (capitalizing a string, sorting an array, and so on). The bang versions of the same methods perform the action, but they do so in place: Instead of creating a new object, they transform the original object.
This is not a convention in Groovy like it is in Ruby. However you can write methods with names that contain characters like ! with the limitation that it must always be quoted like a string:
// define method with quoted name
def 'dangerous!'() {
// do something dangerous
}
// invoke method with quoted name
'dangerous!'()
No, groovy (currently as of v2.1.4) doesn't have anything like this
To add to your options, another solution that would be more Groovy-like or Java-like would be to include an optional parameter that enabled in-place (a.k.a. dangerous) modification, like so:
def processFoo(Foo item, mutate = false) {
if(!mutate) {
Foo temp = new Foo()
// copy item properties
item = temp
}
item.bar = 'blah blah'
// process item here
return item
}
processFoo(myFoo) // makes a copy
processFoo(myFoo, true) // modifies original
This pattern is used — albeit in the opposite manner — with the sort method on collections. Calling sort(false) on Lists prevents changing the original array. Calling sort() or sort(true) will modify it directly.

Why/How to use passed constants in function?

I've seen classes where constants are passed to methods, I guess its done to define some kind of setting in that function. I cant find it anywhere now to try to find out the logic, so I though I could ask here. How and why do you use this concept and where can I find more information about it?
The example below is written in PHP, but any language that handles constants would do I guess..
// Declaring class
class ExampleClass{
const EXAMPLE_CONST_1 = 0;
const EXAMPLE_CONST_2 = 1;
function example_method($constant(?)){
if($constant == ExampleClass::EXAMPLE_CONST_1)
// do this
else if($constant == ExampleClass::EXAMPLE_CONST_2)
// do that
}
}
// Using class
$inst = new ExampleClass();
$inst->example_method(ExampleClass::EXAMPLE_CONST_1);
To me its more clear to pass "ExampleClass::EXAMPLE_CONST_1" than to just pass "1", but it's that the only reason to pass constant?
Simply passing 1 doesn't say much. By having a constant you can have a description about the settings in the name.
example:
constant RAIN = 1;
method setWeather(RAIN);
Atleast that's how and why I use it.
It is always a good idea to avoid literals being passed around. By assigning a name, anyone reading your code has a chance to understand what that value means - a number has no meaning. It might also help you maintaining your code: If for some requirement the value has to be changed, you can easily do it in one place, instead of checking each and every value occurrence.

How do I Extract a Method That Assigns Two Values?

Extract Method (a refactoring from Fowler's book) works great if your method doesn't assign any values. If it assigns one value, that becomes the return value of the extracted method. What if it assigns two values?
Some C# code to illustrate:
private void someBigFunction() {
doSomething();
doSomethingElse();
// start extraction here
string first = Database.Select(...);
// ...
// next is dependent on the value of "first"
int next = Database.Select(...);
// ...
// stop extraction here
doMoreUselessStuff();
}
The exact code or values are not important here. The point is extracting this method. (The two values are linked, so it makes sense to have them in the same method -- and not to make two methods.)
Possible answers to this question would be "return both in an array," "return them both in a pair-like data structure," or "use out parameters (pass by reference)" -- but I'm looking for something cleaner. (The actual code is in Delphi, not C#)
Perhaps Sprout Class is what you're looking for. Make the two members instance variables of a new class and extract this method into that class, assigning the instance variables and providing getters for the caller. Or, of course, you could convert the local variables to be instance variables of the original class. That conversion frequently makes Extract Method easier, but you wind up with what is arguably an excess of instance variables. With Sprout class, you have a class whose only purpose is to retrieve and provide those values, so there's no question that they deserve to be instance variables in it.

Which syntax is better for return value?

I've been doing a massive code review and one pattern I notice all over the place is this:
public bool MethodName()
{
bool returnValue = false;
if (expression)
{
// do something
returnValue = MethodCall();
}
else
{
// do something else
returnValue = Expression;
}
return returnValue;
}
This is not how I would have done this I would have just returned the value when I knew what it was. which of these two patterns is more correct?
I stress that the logic always seems to be structured such that the return value is assigned in one plave only and no code is executed after it's assigned.
A lot of people recommend having only one exit point from your methods. The pattern you describe above follows that recommendation.
The main gist of that recommendation is that if ou have to cleanup some memory or state before returning from the method, it's better to have that code in one place only. having multiple exit points leads to either duplication of cleanup code or potential problems due to missing cleanup code at one or more of the exit points.
Of course, if your method is couple of lines long, or doesn't need any cleanup, you could have multiple returns.
I would have used ternary, to reduce control structures...
return expression ? MethodCall() : Expression;
I suspect I will be in the minority but I like the style presented in the example. It is easy to add a log statement and set a breakpoint, IMO. Plus, when used in a consistent way, it seems easier to "pattern match" than having multiple returns.
I'm not sure there is a "correct" answer on this, however.
Some learning institutes and books advocate the single return practice.
Whether it's better or not is subjective.
That looks like a part of a bad OOP design. Perhaps it should be refactored on the higher level than inside of a single method.
Otherwise, I prefer using a ternary operator, like this:
return expression ? MethodCall() : Expression;
It is shorter and more readable.
Return from a method right away in any of these situations:
You've found a boundary condition and need to return a unique or sentinel value: if (node.next = null) return NO_VALUE_FOUND;
A required value/state is false, so the rest of the method does not apply (aka a guard clause). E.g.: if (listeners == null) return null;
The method's purpose is to find and return a specific value, e.g.: if (nodes[i].value == searchValue) return i;
You're in a clause which returns a unique value from the method not used elsewhere in the method: if (userNameFromDb.equals(SUPER_USER)) return getSuperUserAccount();
Otherwise, it is useful to have only one return statement so that it's easier to add debug logging, resource cleanup and follow the logic. I try to handle all the above 4 cases first, if they apply, then declare a variable named result(s) as late as possible and assign values to that as needed.
They both accomplish the same task. Some say that a method should only have one entry and one exit point.
I use this, too. The idea is that resources can be freed in the normal flow of the program. If you jump out of a method at 20 different places, and you need to call cleanUp() before, you'll have to add yet another cleanup method 20 times (or refactor everything)
I guess that the coder has taken the design of defining an object toReturn at the top of the method (e.g., List<Foo> toReturn = new ArrayList<Foo>();) and then populating it during the method call, and somehow decided to apply it to a boolean return type, which is odd.
Could also be a side effect of a coding standard that states that you can't return in the middle of a method body, only at the end.
Even if no code is executed after the return value is assigned now it does not mean that some code will not have to be added later.
It's not the smallest piece of code which could be used but it is very refactoring-friendly.
Delphi forces this pattern by automatically creating a variable called "Result" which will be of the function's return type. Whatever "Result" is when the function exits, is your return value. So there's no "return" keyword at all.
function MethodName : boolean;
begin
Result := False;
if Expression then begin
//do something
Result := MethodCall;
end
else begin
//do something else
Result := Expression;
end;
//possibly more code
end;
The pattern used is verbose - but it's also easier to debug if you want to know the return value without opening the Registers window and checking EAX.

Resources