Best Practice: function return value or byref output parameters? - function

I have a function called FindSpecificRowValue that takes in a datatable and returns the row number that contains a particular value. If that value isn't found, I want to indicate so to the calling function.
Is the best approach to:
Write a function that returns false if not found, true if found, and the found row number as a byref/output parameter, or
Write a function that returns an int and pass back -999 if the row value isn't found, the row number if it is?

Personally I would not do either with that method name.
I would instead make two methods:
TryFindSpecificRow
FindSpecificRow
This would follow the pattern of Int32.Parse/TryParse, and in C# they could look like this:
public static Boolean TryFindSpecificRow(DataTable table, out Int32 rowNumber)
{
if (row-can-be-found)
{
rowNumber = index-of-row-that-was-found;
return true;
}
else
{
rowNumber = 0; // this value will not be used anyway
return false;
}
}
public static Int32 FindSpecificRow(DataTable table)
{
Int32 rowNumber;
if (TryFindSpecificRow(table, out rowNumber))
return rowNumber;
else
throw new RowNotFoundException(String.Format("Row {0} was not found", rowNumber));
}
Edit: Changed to be more appropriate to the question.

functions that fail should throw exceptions.
If failure is part of the expected flow then returning an out of band value is OK, except where you cannot pre-determine what an out-of-band value would be, in which case you have to throw an exception.
If I had to choose between your options I would choose option 2, but use a constant rather than -999...

You could also define return value as Nullable and return Nothing if nothing found.

I would choose option 2. Although I think I would just use -1 not -999.
Richard Harrison is right that a named constant is better than a bare -1 or -999.

I would go with 2, or some other variation where the return value indicates whether the value was found.
It seems that the value of the row the function returns (or provides a reference to) already indicates whether the value was found. If a value was not found, then it seems to make no sense to provide a row number that doesn't contain the value, so the return value should be -1, or Null, or whatever other value is suitable for the particular language. Otherwise, the fact that a row number was returned indicates the value was found.
Thus, there doesn't seem to be a need for a separate return value to indicate whether the value was found. However, type 1 might be appropriate if it fits with the idioms of the particular language, and the way function calls are performed in it.

Go with 2) but return -1 (or a null reference if returning a reference to the row), that idiom is uses extensively (including by by .nets indexOf (item) functions), it's what I'd probably do.
BTW -1 is more acceptable and widly used "magic number" than -999, thats the only reason why it's "correct" (quotes used there for a reason).
However much of this has to do with what you expect. Should the item always be in there, but you just don't know where? In that case return the index normally, and throw an error/exception if it's not there.

In this case, the item might not be there, and that's an okay condition. It's an error trap for unselected values in a GridView that binds to a datatable.

Another few possibilities not yet mentioned:
// Method 1: Supports covariance; can return default<T> on failure.
T TryGetThing(ref bool success);
// Method 2: Does not support covariance, but may allow cleaner code in some cases
// where calling code would use some particular value in in case of failure.
T TryGetThing(T DefaultValue);
// Method 3: Does not support covariance, but may allow cleaner code in some cases
// where calling code would use some particular value in case of failure, but should
// not take the time to compute that value except when necessary.
T TryGetThing(Func<T> AlternateGetMethod);
// Method 4: Does support covariance; ErrorMethod can throw if that's what should
// happen, or it can set some flag which is visible to the caller in some other way.
T TryGetThing(Action ErrorMethod);
The first approach is the reverse of the method Microsoft developed in the days before support existed for covariant interfaces. The last is in some ways the most versatile, but is likely to require the creation of a couple of new GC object instances (e.g. a closure and a delegate) each time it's used.

Related

Lisp function exists or not checking

I want to check a function definition exists in a lisp program or not to decide which program block to run.
The function definition is written on another file with.Net & I am working for AutoCAD.
Please help.
There are many ways to do this, but ultimately you need to check whether the symbol corresponding to the function name holds a value (for example using the boundp function), and perhaps additionally whether such value is of SUBR, USUBR, or EXRXSUBR data type (using the type function).
For example:
(member (type YourFunctionName) '(subr usubr exrxsubr))
In this case, if the symbol YourFunctionName is null, (type YourFunctionName) will return nil which will cause the member expression to return nil. Similarly, if the value held by the YourFunctionName symbol is anything other than a function, the member function will return nil.
Since any non-nil value in AutoLISP is interpreted as True, the use of member will validate an if test expression, even though member does not explicitly return a boolean value.
Lee's Answer is great, many time to check function is loaded or not I am use (and functionName) it return T if exist or if not returns Nil.

Is there a way to make Typescript consider function types non-equivalent when they have different parameter counts?

Consider the following code:
function typeTest(callback:(item1:number, item2:string)=>number):number {
return callback(5, "foo");
}
//This works:
typeTest((num : number, str : string) => { return num;} )
//But surprisingly, so does this, even though the supplied callback doesn't have enough parameters
typeTest((num : number) => { return num;} )
I'm trying to tell the compiler that the function "typeTest" takes a callback with two parameters. However, if I give it a callback with fewer parameters, it still works.
I presume Typescript thinks that the function defined as "(num : number) => number" implements the function type of "(number, item2)", basically ignoring the second parameter. That makes some sense, but we re-defined a callback type to take more parameters, and expected the compiler to tell us where we'd forgotten to re-implement the old callbacks.
I might be running into a fundamental property of Typescript's type system, but is there a way to tell the compiler, "No really - the passed in function needs to take all of these parameters"?
Edit :
As for the motivation: In our case, the we used to have a "setSortFunction" method that expected a method that took a single item and returned an integer. If you compared that integer amongst all of the items, you could sort the array. Later we changed it to accept the more standard, "take two items, compare them, and return -1, 0, or 1". So, now we know for a fact that our sort functions passed in need to take two items and compare them. If they don't, they are probably broken. So, we wanted a way to enforce the requirement that the sortFunction passed in accepted two parameters.
However, if I give it a callback with fewer parameters, it still works.
Yes. This is by design. Think about it : it's safe for the caller to call a function that doesn't care about the last few arguments. This is the way JS works in conventional code bases.
This will clarify it a bit more : https://github.com/Microsoft/TypeScript/wiki/Type%20Compatibility#comparing-two-functions

Method/function return type in call stack

I was trying to find the existence of return type constraint in method call stack. Event any language you use, (java / c++), we specify the return type of method/function. When this method enters into call stack (or in memory, I'm not sure) how does it uses our specified return type?
Another thing is why can't we specify two return types in header? like
public (int, float) myMethod(){
return (1, 2.5);
}
So this function could return two values (one int and one float).
I'm not asking here about returning more than one value from method. That off course i can do using array or creating a custom object. My question is, how this is mapped in the stack so that it take notice of return type constraint and why we can't specify more than one return type?
As you can see, the picture of call stack, I can't see anything about return type here.
So finally I summarize my question.
1) How will you modify this attached image to specify the return type and why?
2) I can not specify more than one return type in any language (that i know), why?
Any help will be appreciated!
I got it by myself.
First question:
1) How will you modify this attached image to specify the return type and why?
Answer: There is no point of return type in call stack. In many languages you don't even specify return type, like python, PHP etc. So there is no relation of return type with call stack.
2nd question:
2) I can not specify more than one return type in any language (that i know), why?
Answer: It depends on requirement. Language designer don't feel any need to return more than one value (Off course they provide alternate like returning array, but value returned only one, that is reference to array). If language designers feel the need to return two values, I think they can. But there is no need of that.

True until disproven or false until proven?

I've noticed something about my coding that is slightly undefined. Say we have a two dimension array, a matrix or a table and we are looking through it to check if a property is true for every row or nested dimension.
Say I have a boolean flag that is to be used to check if a property is true or false. My options are to:
Initialize it to true and check each cell until proven false. This
gives it a wrong name until the code
is completely executed.
Start on false and check each row until proven true. Only if all rows are true will the data be correct. What is the cleanest way to do this, without a counter?
I've always done 1 without thinking but today it got me wondering. What about 2?
Depends on which one dumps you out of the loop first, IMHO.
For example, with an OR situation, I'd default to false, and as soon as you get a TRUE, return the result, otherwise return the default as the loop falls through.
For an AND situation, I'd do the opposite.
They actually both amount to the same thing and since you say "check if a property is true for every row or nested dimension", I believe the first method is easier to read and perhaps slightly faster.
You shouldn't try to read the value of the flag until the code is completely executed anyway, because the check isn't finished. If you're running asynchronous code, you should guard against accessing the value while it is unstable.
Both methods "give a wrong name" until the code is executed. 1 gives false positives and 2 gives false negatives. I'm not sure what you're trying to avoid by saying this - if you can get the "correct" value before fully running your code, you didn't have run your code in the first place.
How to implement each without a counter (if you don't have a foreach syntax in your language, use the appropriate enumerator->next loop syntax):
1:
bool flag = true;
foreach(item in array)
{
if(!check(item))
{
flag = false;
break;
}
}
2:
bool flag = false;
foreach(item in array)
{
if(!check(item))
{
break;
}
else if(item.IsLast())
{
flag = true;
}
}
Go with the first option. An algorithm always has preconditions, postconditions and invariants. If your invariant is "bool x is true iff all rows from 0-currentN have a positve property", then everything is fine.
Don't make your algorithm more complex just to make the full program-state valid per row-iteration. Refactor the method, extract it, and make it "atomic" with your languages mechanics (Java: synchronized).
Personally I just throw the whole loop into a somewhat reusable method/function called isPropertyAlwaysTrue(property, array[][]) and have it return a false directly if it finds that it finds a case where it's not true.
The inversion of logic, by the way, does not get you out of there any quicker. For instance, if you want the first non-true case, saying areAnyFalse or areAllTrue will have an inverted output, but will have to test the exact same cases.
This is also the case with areAnyTrue and areAllFalse--different words for the exact same algorithm (return as soon as you find a true).
You cannot compare areAnyFalse with areAnyTrue because they are testing for a completely different situation.
Make the property name something like isThisTrue. Then it's answered "yes" or "no" but it's always meaningful.
In Ruby and Scheme you can use a question mark in the name: isThisTrue?. In a lot of other languages, there is a convention of puttng "p" for "predicate" on the name -- null-p for a test returning true or false, in LISP.
I agree with Will Hartung.
If you are worried about (1) then just choose a better name for your boolean. IsNotSomething instead of IsSomething.

What is the term for "catching" a return value

I was training a new developer the other day and realized I don't know the actual term for "catching" a return value in a variable. For example, consider this pseudocoded method:
String updateString(newPart) {
string += newPart;
return string;
}
Assume this is being called to simply update the string - the return value is not needed:
updateString("add this");
Now, assume we want to do something with the returned value. We want to change the call so that we can use the newly updated string. I found myself saying "catch the return value", meaning I wanted to see:
String returnedString = updateString("add this");
So, if you were trying to ask someone to make this change, what terminology would you use? Is it different in different languages (since technically, you may be calling either a function or a method, depending on the language)?
assign the return value to a variable?
Returned values can be assigned or discarded/ignored/not used/[insert synonym here].
There isn't really a technical term for it.
I would say "returnedString is to be initialised with the return value of updateString".
"Catch" makes me think of exceptions, which is a bit misleading. How about something like "use" or "store" or "assign"?
Common ones that I know:
You assign a value to a variable.
You store a value into a variable.
check the function's return value, do not ignore return values
In the example, you're simply assigning the return value of the function to a new variable.
When describing the behavior of that single line of code, it doesn't really matter that the return value is not essential to the use of the function. However, in a broader context, it is very important to know what purpose this "Interesting Return Value" serves.
As others have said there isn't really a word for what you describe. However, here's a bit of terminology for you to chew on: the example you give looks like it could be a Fluent Interface.
I suggest "cache", meaning store it for later.
Maybe there's a subliminal reason you're saying "catch".
It's better too state the purpose rather than the implementation details (because actual implementation can be different in different programming langugages).
Generally speaking:
- Save the return value of the call.
If you know the return value is a result of something:
- Save the result of the call.
If you know the return value is to signify a status (such as error):
- Save the status of the call.
By using the word "save", you can use that same statement across the board, regardless of the mechanism used in that particular language to save the return value.