Lately I spent quite some time thinking about perfect “
else if” syntax (don’t confuse it with “
if-else”), and I just wonder how much time I will spend on this subject.
Let’s start from easy one — in all C-like languages function call and condition would like this:
if ((idx = str.indexOf("hello")) != -1) ...
This is ugly. Not only we have to add extra scope (not shown here) to avoid variable leak, but we are using magic number. Worse — what about such values as “
-2”? They are valid for “
idx” but they are invalid in context of “
Before you even warm up consider more difficult case — reading values from a map (associative array, dictionary):
value = dict["hello"];
This won’t fly, if there is no such key we will get an exception. So maybe like this:
if (dict.ContainsKey("hello")) value = dict["hello"];
OK, this is safe, but now we hit map twice. In case of C# the following is the best approach:
if (dict.TryGetValue("hello",out value)) // we have valid value here
One can say — not so bad — but! First of all you have to mark your “trying” functions in some way to distinguish them from “regular” functions. For me it is not appealing to have bunch of “
TryConcat” and alike. Secondly, such syntax is inconsistent with already existing notion:
result ← expression
I have nothing against switching the flow (to — from left to right), however what bothers me here is inconsistency. I wouldn’t like to see this happening to Skila.
What are the other options? “
if (!(value = dict["hello"]).isEmpty()) Console.WriteLine(value.get());
Such code is efficient (kind of), with result being kept on left, but it is too elaborate. And all the time you use value, you have to use “
get” method for it (or introduce temporary variable).
I was struggling with some mad ideas of dual variable, which is partially and implicitly converted to “bool”, or solving the issue with tuples (Skila style):
if ((success:@,value) = dict["hello"]).success then // we have direct access to value // success is dropped
But the concept of failure from Icon struck me as really elegant. Map indexer could “return” failure in case of missing key, and this would cause “
if” to fail.
I didn’t write even “hello world” in Icon, so better read about Icon from somewhere else, Wikipedia may be a good starting point.
At first glance it looks, oh, so charming — I am afraid though that this beauty might come at cost of problematic maintenance, workflow which is hard to understand, not to mention complex implementation.
But this approach will be my first to investigate. As usual, if you have better, or simply other ideas worth considering, I am all ears.