Artem Kachanovskyi
Artem Kachanovskyi

Reputation: 1969

Which way would you suggest to return default value that is not null?

I use C# language, but I think this question is not limited with language. I have the next function and method to return image name:

public Func<string> GetImageNameFunc { get; set; }

private string getImageName()
{
    if (GetImageNameFunc != null)
    {
        string imageName = GetImageNameFunc();
        if (!string.IsNullOrEmpty(imageName))
        {
            return imageName;
        }
    }
    return "default.png";
}

In the past the logic was next:

Now I'd like to give one more possibility to user: he must be able to specify, that he wouldn't like to have image at all. So, he must be able to return some value from function, which would mean, that he doesn't wish to get image at all: let's say, Image.None.

I guess I can use some constant like

public const string NoImageName = "|";

, which would have a value that is inconsistent for image, and specify this constant in event comments. But I don't really like that way.

Any suggestions?

Upvotes: 1

Views: 71

Answers (1)

usr
usr

Reputation: 171218

Split the method into two cases:

string TryGetImageName()
{
    if (GetImageNameFunc != null)
    {
        string imageName = GetImageNameFunc();
        if (!string.IsNullOrEmpty(imageName))
        {
            return imageName;
        }
    }
    return null; //no default!
}

string GetImageNameOrDefault() {
 return TryGetImageName() ?? "default.png";
}

Your method was doing two things at once.

Alternative:

string TryGetImageName(string @default = "default.png") {
 //...
 return @default;
}

NoImageName = "|" that is not a good idea. It is a confusing hack. Rather than using magic strings create a class that holds a string and a boolean informing the caller whether the default was used or not.

Upvotes: 3

Related Questions