I often encounter this problem – I need to get some value, if it exists, and then do something with that value.
Getting that value becomes a separate method, and since that value might not exist, I need to indicate that somehow. For example, I might have a method that returns a productId
if a product is attached to the form the user is filling out. If it doesn’t exist, I can return 0, which is an invalid productId, which is a magic number.
My current problem with this instance is this:
public int GetProductIdFromFormIfAny(JObject form) { int productId = 0; //default to 0 IList<FormComponentMetadata> formFields = ParseFormForDropdowns(form); bool isProductAttached = formFields.Any(field => field.DataLookupTable == "Products"); if(isProductAttached){ FormComponentMetadata productField = formFields .Single(field => field.DataLookupTable == "Products"); string filterStringContainingProductId = productField.DataLookupFilter; productId = filterStringContainingProductId.Split("=")[1]; } return productId; }
I don’t know how to get around the magic number issue. I can create a new class, which holds an id and a bool
indication whether or not that id exists, but that seems very heavy-handed and a LOT of extra code that someone has to maintain, even though the tradeoff is clarity.
As a side note, this is what comes back for the filterStringContainingProductId
: "data_lookup_filter":"Product_ID=9"
– I am not sure how to make the Split("=")[1]
clear without comments or constants, which, again, seem heavy.