Sujet : Re: New VSI post on Youtube
De : arne (at) *nospam* vajhoej.dk (Arne Vajhøj)
Groupes : comp.os.vmsDate : 25. Aug 2024, 03:04:30
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vae3fe$1j523$1@dont-email.me>
References : 1 2 3 4 5 6
User-Agent : Mozilla Thunderbird
On 8/24/2024 9:33 PM, Stephen Hoffman wrote:
On 2024-08-20 12:36:51 +0000, Simon Clubley said:
One thing I wish was available in all languages is the ability to return multiple values from a function call so you can return both a status and the value(s) in one assignment. Ie: "a, b, c = demo_function(param1, param2);".
>
In languages with dynamic associative arrays (such as PHP), I simulate this by returning an associative array from a function call with both status and value fields. Makes coding _so_ much cleaner and robust.
For those following along at home, C supports returning a struct.
Languages including Swift allow returning an "optional", where you either get a value such as an object, or an indication or its absence. Swift uses the concept of "unwrapping" a result marked optional, which means you have to check before access.
Returning objects is more widely available, and hides a lot of this mess, as well as hiding dealing with potentially-larger data buffers. Objects and message-passing is akin to itemlist-based APIs, dragged forward a few decades.
In other languages, support for an optional requires explicit code, whether that might return a struct, or might return a value and a sentinel, or ilk.
I don't know Swift but I will assume Swift optional is similar to
optional in other languages.
It solves the return both status and value problem. But it is
not a general multiple return value solution. And it is really
just a small evolution of the traditional "return null
indicate an error".
$ type OptionalDemo.java
import java.util.Optional;
public class OptionalDemo {
public static String oldStyleAPI(int v) {
if(v > 0) {
return Integer.toString(v);
} else {
return null;
}
}
public static Optional<String> newStyleAPI(int v) {
if(v > 0) {
return Optional.of(Integer.toString(v));
} else {
return Optional.empty();
}
}
public static void testOldStyleAPI(int v) {
String s = oldStyleAPI(v);
if(s != null) {
System.out.println(s);
} else {
System.out.println("No result");
}
}
public static void testNewStyleAPI(int v) {
Optional<String> s = newStyleAPI(v);
if(s.isPresent()) {
System.out.println(s.get());
} else {
System.out.println("No result");
}
}
public static void testNewStyleAPISmarter(int v) {
Optional<String> s = newStyleAPI(v);
System.out.println(s.orElse("No result"));
}
public static void main(String[] args) {
testOldStyleAPI(123);
testOldStyleAPI(0);
testNewStyleAPI(123);
testNewStyleAPI(0);
testNewStyleAPISmarter(123);
testNewStyleAPISmarter(0);
}
}
$ javac OptionalDemo.java
$ java "OptionalDemo"
123
No result
123
No result
123
No result
Arne