Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handling of Null Values in Templating object #13

Open
ghost opened this issue May 28, 2014 · 2 comments
Open

Handling of Null Values in Templating object #13

ghost opened this issue May 28, 2014 · 2 comments

Comments

@ghost
Copy link

ghost commented May 28, 2014

Two Options

1. Better Error Message

document = data.GetType().GetProperties().Aggregate(document, (current, property) =>
{
    if (property.GetValue(data, null) == null)
    {
        throw new NullReferenceException("Field is null : " + property.Name);
    }
    return ReplaceTemplateField(current, property.Name,  property.GetValue(data, null).ToString());
});
  • Less Forgiving
  • More Feedback

2. Swallow the nulls

 document = data.GetType().GetProperties().Aggregate(document,
        (current, property) => ReplaceTemplateField(current, property.Name, 
        String.Format("{0}",property.GetValue(data, null))));
  • No Exception When maybe there should be
  • Approximate 15% performance hit (String.Format vs .ToString())

Thoughts?

Feels like this kind of decision is best left to the person in charge of the code base. Which way feels more true to the vision?

As it currently stands it simply gives an error message that says "Object reference not set to an instance of an object."

@becdetat
Copy link
Member

My feel is that null should translate to an empty string, I've encountered lots of cases where null is used interchangeably with string.Empty. I'm happy with a performance hit but it could be implemented like:

=> {
    var value = property.GetValue(data, null);
    return value == null ? string.Empty : value.ToString();
}

@ghost
Copy link
Author

ghost commented May 29, 2014

It should translate to an empty string.
Changing up the ReplaceTemplateField to accept an object instead of a string and then doing the null check in there also fixes for fields and ExpandoObjects and whatever else to come

   public static string ReplaceTemplateField(string document, string fieldName, object fieldValue)
    {
        return document.Replace(TOKEN_START + fieldName + TOKEN_END, fieldValue == null ? string.Empty : fieldValue.ToString());
    }

It also cleans up the ParseTemplate Method.

Pull Request incoming

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant