[Motoko] Syntactic confusion between objects and blocks

I find the syntax of Motoko a little confusing. See the annotated code below for an illustration of my concern. It isn’t a showstopper by any means, but seeing as Motoko is still an alpha product I feel like I may as well share my thoughts.

My thoughts

I think the shared use of {…} for both objects and blocks is a little confusing, given the similarity of their inner syntax. I know the use of curly braces is motivated by retaining a similarity to JavaScript, but I have a hunch that using a different syntax for blocks (square brackets? Python-esque syntax?) would remove some of the cognitive burden here.

That’s my two cents. What does everyone else think?

Code

(Note: the code window is scrollable)

    // This is a basic object literal.
    let a : {x : Int; y : Int} = {
        x = 0;
        y = 0;
    };

    // Once you add the "object" keyword, you need to start
    // using "let", and you need to explicitly mark public fields.
    let b : {x : Int; y : Int} = object {
        public let x = 0;
        public let y = 0;
    };

    // If we drop the "object" and "public" keywords we now
    // have a block with type Nat. A bit confusing!
    let c : Nat = {
        let x = 0;
        let y = 0;
    };

    // This is also a block!
    let d : Nat = {
        var x = 0;
        let y = 0;
    };

    // If we drop the second declaration we now have an object again!
    let e : {var x : Nat} = {
        var x = 0;
        //let y = 0;
    };
6 Likes

Nick I think I agree with you. Shared functionality of a common piece of syntax such as the curly brace can definitely cause confusion at times. Especially if this was the first language a person was learning.

I would also vote that curly brace for objects be changed to another operator such as parentheses or square brackets as Nick suggested. I think it makes for easier to read code and it would cut down on common programming mistakes.

3 Likes

I just wanted to tag @alexa.smith on the feedback so it doesn’t get lost with the SDK team.

4 Likes

This is a great suggestion Nick. Also tagging members of the engineering team at Dfinity @PaulLiu @stanley.jones for visibility.

2 Likes

Was going through the Block section in the documentation and noticed a few things.

In the following expression,

let z = {
  let x = 1;
  let y = x + 1;
  x * y + x
};

Noticed how the last line of code in the block does not have a semi-colon, it returns a value which is also the type of the block (In this case type is a Nat)

With that, I expected the following to throw an error because these don’t end in expressions that return a Nat. But surprisingly, there was no error.

4 Likes

Thanks for reporting this issue, Nick. We’re following up internally to see what can be done.

4 Likes

Glad to hear this is getting some consideration :slight_smile:

3 Likes