C++ Logo

std-proposals

Advanced search

Re: Initialisers in ternary operators

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Sun, 13 Sep 2020 18:07:18 -0400
On Sun, Sep 13, 2020 at 5:37 AM Dvir Yitzchaki via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
>
>
> On Sun, 13 Sep 2020 at 11:49, Jorg Brown via Std-Proposals <std-proposals_at_[hidden]> wrote:
>>
>>
>> OK, so if I only use local control structures, and eschew goto and return, then how do I write the typical multiple-error-return flow, without ending up with code that is increasingly indented, right up until the end? What's the right way, according to your model, of writing:
>>
>> std::optional<std::string> FindUsersCity(bool non_default) {
>> std::optional<std::string> city = std::nullopt;
>> std::optional<ContactsServer> contacts = GetOrOpenContactsServerConnection();
>> if (contacts) {
>> std::optional<UserId> uid = contacts->GetUserId();
>> if (uid) {
>> std::optional<GeoServer> geo = GetOrOpenGeoServerConnection();
>> if (geo) {
>> std::optional<Location> uloc = geo->GetLocation(*uid);
>> if (uloc) {
>> city = uloc->GetCityName();
>> }
>> }
>> }
>> }
>> return city;
>> }
>
>
> with [P0798] it can be something like:
>
> std::optional<std::string> FindUsersCity(bool non_default) {
> return GetOrOpenContactsServerConnection()
> .transform([](auto&& contacts) { return contacts->GetUserId(); })
> .and_then([](auto&& uid) {
> return GetOrOpenGeoServerConnection().transform(
> [&uid](auto&& geo) { return geo->GetLocation(*uid); });
> })
> .transform([](auto&& uloc) { return uloc->GetCityName(); });
> }

This code as written is basically unreadable. It reminds me of Herb's
original example way back in the past for why C++ needed async/await
as a core language feature. The before code was some nightmare of
lambdas and other garbage, while the await version was just mostly
normal code.

To me, this gordian knot of code represents the
unwillingness/inability to use exceptions. So to me, the desire to
write this code is a response to not having static exceptions. None of
those functions should be returning `optional` anything. They should
be returning a `T` and throwing if it's not valid.

Received on 2020-09-13 17:07:29