HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Reading data with different but similar semantics

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
readingsemanticswithbutdifferentsimilardata

Problem

I am writing code that reads data from a DB, where boolean values are stored as 0/1 nullable integers.

I decided to write a simple function to encapsulate the logic which converts the integer values to boolean. Thing is, I sometimes need to regard the db null value as boolean false, and sometimes just as null.

So I've come up with the following two extension methods:

// Read the specified column value from row as nullable boolean,
// treating integer 0 as false, and any other non-null value as true.
public static bool? ReadAsBoolNullable(this DataRow row, string columnName)
{
    if (row.IsNull(columnName))
    {
        return null;
    } 
    else 
    {
        return row[columnName] != 0;
    } 
}

// Read the specified column value from row as boolean,
// treating null and integer 0 as false, and any other value as true.
public static bool ReadAsBool(this DataRow row, string columnName) 
{
    bool? data = row.ReadAsBoolNullable(columnName);
    return data.HasValue ? data.Value : false;
}


My main concern about this code is that I potentially have hundreds of millions of records, each having up to 10 boolean (not nullable) columns. So the second function will be executed a lot and will have to call the first one a lot. Could this damage performance significantly, given that the function itself doesn't do much?

Solution

As with all performance related questions, if and only if you can gather profiling evidence that shows that your current code is meaningfully detrimental to performance, don't call the first method in the second one, but rather repeat the code. This goes slightly against DRY (just barely, considering the very short code), but you will have to weigh the value of maintainability vs that of whatever performance gain is achieved.

In practice, I suspect that the effect on performance will be negligible if not non-existent. It's not as if you're not calling a slew of other methods and properties anyways.

The key point is profile profile profile.

Context

StackExchange Code Review Q#106022, answer score: 4

Revisions (0)

No revisions yet.