Is there a name for this anti-pattern/code smell?

前端 未结 13 2483
轻奢々
轻奢々 2021-02-12 16:00

Let me start by saying that I do not advocate this approach, but I saw it recently and I was wondering if there was a name for it I could use to point the guilty party to. So h

13条回答
  •  我寻月下人不归
    2021-02-12 16:09

    Konrad is right, C# uses dual return values all the time. But I kind of like the TryParse, Dictionary.TryGetValue, etc. methods in C#.

    int value;
    if (int.TryParse("123", out value)) {
        // use value
    }
    

    instead of

    int? value = int.TryParse("123");
    if (value != null) {
        // use value
    }
    

    ...mostly because the Nullable pattern does not scale to non-Value return types (i.e., class instances). This wouldn't work with Dictionary.TryGetValue(). And TryGetValue is both nicer than a KeyNotFoundException (no "first chance exceptions" constantly in the debugger, arguably more efficient), nicer than Java's practice of get() returning null (what if null values are expected), and more efficient than having to call ContainsKey() first.

    But this is still a little bit screwy -- since this looks like C#, then it should be using an out parameter. All efficiency gains are probably lost by instantiating the class.

    (Could be Java except for the "string" type being in lowercase. In Java of course you have to use a class to emulate dual return values.)

提交回复
热议问题