开发者

Test for NULL & return a string if needed - what are the pro's/con's

开发者 https://www.devze.com 2023-02-27 05:05 出处:网络
I have a simple class which has a ToString implemented which I am happy with the content. I am trying to decide what is the (most) correct way by seeing if there are any pro\'s/con\'s for the various

I have a simple class which has a ToString implemented which I am happy with the content. I am trying to decide what is the (most) correct way by seeing if there are any pro's/con's for the various options.

For the example below:

  • Class: Astronaut
  • Variable of type Astronaut: person

Options that I am just snow balling here:

  1. string result = person == null ? "Unknown Astronaut" : person.ToString();
  2. string result = person.ToString() ?? "Unknown Astronaut";
  3. string result = (person ?? "Unknown Astronaut").ToString();
  4. string result = person ?? (object)"Unknown Astronaut";

My views on those are

  1. Very verbose & I don't need that level of verbosity.
  2. Much better than 1 but the ToString feels ugly plus worried of exceptions in that ToString code.
  3. This seems popular (here & here) but I am not sure it will work. Won't the compiler complain about a string & a Astronaut type not being the same type and thus can not be used in a coalese.
  4. This is the one I am happiest with now, but it means a box & ToString should person be null.
开发者_JAVA技巧

In summary:

  • Any pro's/con's to any of the above?
  • Any options you can think of?


I prefer an extension method:

public static string SafeToString(this Object obj)
{
   return obj.SafeToString(string.Empty);
}

public static string SafeToString(this Object obj, string defaultString)
{
   return obj == null ? defaultString : obj.ToString();
}

So to your question:

string result = person.SafeToString("Unknown Astronaut");


Create a static ToString method and just call it like:

string result = Astronaut.ToString(person);

Best way to factor out common code.


I remember a design patterns book telling me about some object that you instantiate for the sole purpose of filling in null objects. They would return things like the empty string for name, or 0 for length, and so on. Doesn't sound like a bad idea.

You could also implement it as a static method of the Astronaut class:

String result = Astronaut.getName(person);


You could also place a static method in the class that converts an Astronaut to string or returns "Unknown astronaut" if the argument was null.

In a similar vein, you could make it an extension method and call it directly on a variable of that type, even if it's null.

0

精彩评论

暂无评论...
验证码 换一张
取 消