Automatic casting of variables?

Questions about GP commands and how to do things

Moderator: MSandro

Post Reply
SvenJ
Posts: 25
Joined: Jul 6th, '17, 08:03

Automatic casting of variables?

Post by SvenJ » Jul 14th, '17, 10:39

Hey :)

Snap automatically casts variables (or rather, resets them to a default value of the target data type):
if you set a variable x to "hello", and then increase the value of x by 5, the result comes out as 5.

In GP, currently, this results in a syntax error thrown by the debugger (see attachment) .Is this because automatic casting is not yet implemented, or is it a deliberate decision? GP does have other forms of explicit casting, like the "to string" and "to number" blocks, so I imagine it could very well be an intentional design choice.
Attachments
deb.png

JohnM
Posts: 379
Joined: Sep 11th, '15, 14:42

Re: Automatic casting of variables?

Post by JohnM » Jul 14th, '17, 12:10

Yep, that's a deliberate design choice.

Snap follows Scratch in how it handles type conversions (casting). The Scratch design is fabulous for people just getting started. However, as one aspires to larger and more complex programs, aggressive type conversions can mask errors. In your example, it's unlikely that the user really intended to increment the string "hello" by 5. More likely, they meant to increment a different variable, or the value "hello" was stored into that variable by mistake. GP's debugger can help the user discover such problems earlier and closer to where the bug was actually introduced -- as opposed to silently converting the string into a number and probably causing errors or unexpected behavior later on.

As I'm sure you understand, neither of these design choices is "better" in an absolute sense; each choice is tailored to the needs of a particular target audience.

SvenJ
Posts: 25
Joined: Jul 6th, '17, 08:03

Re: Automatic casting of variables?

Post by SvenJ » Jul 14th, '17, 12:15

I see :)

Thank you very much for clearing this up for me!

Post Reply