Home > Software design >  Create a TryMapOrReturnDefault pattern
Create a TryMapOrReturnDefault pattern

Time:10-20

I am currently trying to work out a 'TryMapOrReturnDefault' pattern, I already have a map method which throws an exception in case it fails, but I need in some cases to have it return something (either user specified or null by default)

but how I do actually do it,

It seem wrong to "just" wrap the map method in a try finally, and in case an exception is being triggered return default value or am I wrong here - seem like I am misusing the fact an exception is being triggered, or is that the way to do it?

public static CustomModel? TryMapOrDefault(FieldType value, string title, CustomModel? defaultValue = null)
{
    CustomModel? returnValue = defaultValue;
    try
    {
        returnValue = Map(value, title);
    }
    finally
    {

    }
    return returnValue;
}

CodePudding user response:

It seem wrong to "just" wrap the map method in a try finally, and in case an exception is being triggered return default value or am I wrong here - seem like I am misusing the fact an exception is being triggered, or is that the way to do it

In my view, you can use try-catch statement because you have plan B when your program meet an exception. So, it is perfectly eligible to me to use try-catch statement here because you can return default value and this is plan b.

It is not the case when an error is unrecoverable. E.g., you cannot read data from table because table was dropped recently from database. On the other hand, if error can be recovered, then you can go with try-catch

UPDATE:

If Map function does not throw exception, then it is possible to check null and then just return default value:

public static CustomModel? TryMapOrDefault(FieldType value, string title, 
    CustomModel? defaultValue = null)
{
    CustomModel? returnValue = defaultValue;
    
    returnValue = Map(value, title);

    if (returnValue is null) 
        returnValue = defaultValue; 

    return returnValue;
}

If you want to return defaultValue when Exception is thrown, then you can use catch statement to assign default value.

Let me show an example:

public static CustomModel? TryMapOrDefault(FieldType value, string title, 
    CustomModel? defaultValue = null)
{
    CustomModel? returnValue = defaultValue;
    try
    {
        returnValue = Map(value, title);
    }
    catch (Exception ) {
        returnValue = defaultValue; 
    }
    return returnValue;
}
  • Related