Best practice: function return value or byref output parameters?

I have a function called FindSpecificRowValue that takes as datatable and returns the row number that contains the specific value. If this value is not found, I want to point to the calling function.

Best approach to:

  • Write a function that returns false if not found, true if it is found, and the number of the found line as the byref / output parameter, or
  • Write a function that returns an int and passes back -999 if the string value is not found, the line number if it is?
+3
source share
8 answers

Personally, I would not have done a method with this name.

Instead, I would do two methods:

TryFindSpecificRow
FindSpecificRow

Int32.Parse/TryParse, # :

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));
}

: , .

+12

Nullable Nothing, .

+3

2. , -1 -999.

, , -1 -999.

+2

, .

, - , , , , .

, 2, , -999...

+2

2 , , .

, , ( ), , . , , , , , -1 Null , . , , , .

, , , , . 1 , , .

+1

Go 2), -1 ( , ), ( .nets indexOf (item)), , , , .

BTW -1 " ", -999, , "" (, - ).

, . , , ? /, .

+1

, . GridView, .

0

, :

// 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 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 method developed by Microsoft a few days before covariant interface support existed. The latter is in some ways the most universal, but it seems that each time it is used, it may be necessary to create several new instances of the GC object (for example, closure and delegate).

0
source

Source: https://habr.com/ru/post/1698868/


All Articles