Wednesday, March 30, 2016

Highfalutin code #4. With great power, comes great responsibility.

No matter how powerful our programming language is..

foreach (var item in documentFields.SelectMany(documentField => documentField.Options, (documentField, option) => new { documentField, option }))
{
   item.option.DocumentField = item.documentField;
}


..we still have a great responsibility to make our code readable and maintainable:
foreach (var documentField in documentFields)
    foreach (var option in documentField.Options)
    {
        option.DocumentField = documentField;
    }


SelectMany's intent is to flatten *ALL* the option collection from all fields, and then assign each option item in collection to their parent field.

Though the objective of the first code is to make the program's intent obvious, its verbosity blurs the intent of the code.

In fact, if we want to make it appear we are flattening the collection, we can also do it as follows:

foreach (var documentField in documentFields) foreach (var option in documentField.Options)
{
    option.DocumentField = documentField;
}


If we look at the two for loops as projecting a table with two columns, the projected options will now look like flattened rows.

We just have to tilt our perspective sometimes :)


Disclaimer: I won't use the last code.

No comments:

Post a Comment