It would be better to use something like the Option type as a container for return types that might be missing. They are common in most functional languages such as Scala. Useful for the case when you care about something succeeding or failing, and you don't care why. e.g. Parsing integers.
int num;
Using the Option type, you can define an int parser that completes volatile ugliness and returns a clean parameter. it reduces your complexity if it is possible only in ONE PLACE. avoids duplication and mutation.
public Option<int> IntParse(string str) { int num; // mutable if (!int.TryParse(str, out num)) return Option.None<int>(); else return Option.Some<int>(num); }
use elsewhere:
int result = IntParse(someString).GetOrElse(defaultValue);
As you can see, this leads to a much more complex usage pattern, since the branching was hidden.
Alternatively, if your function should return two things, it is likely that:
- The function is too complex and needs to be shared (do something well!) Or
- Return values are closely related and should be related to each other in a new type
Thing to think about!
Ben hardy
source share