Hacker News new | ask | show | jobs
by SloopJon 2014 days ago
I ported some null-heavy Java code to C++. The source frequently returns an object, or null in case of error; e.g.,

    BigInteger bi = rational.asBigInteger();
    if (bi != null) {
        ...
    }
One of the classes is essentially a node in a graph, so in my first pass its objects were wrapped in a shared_ptr, which can be null. However, objects of the other two types are typically passed by value in C++, so I had to think about that. Exactly what std::optional was designed for, but do I want to require C++17, both in the implementation and the public interface? The syntax looks nice enough:

    if (auto bi = rational.asBigInteger()) {
        ... // bi is like a non-null pointer
    }
Java has java.util.Optional, but the source predates Java 8.

TypeScript's type guard approach is really clever. Once you've checked the value, you can use it like normal. No need for a wrapper class, or different syntax.