3 ms·
Isn't the difference between compiler-enforced null checking and Option/Maybe type (+no null) mostly superficial? Eg compare and contrast the PPL example from t
by zokier 12y ago
Isn't the difference between compiler-enforced null checking and Option/Maybe type (+no null) mostly superficial? Eg compare and contrast the PPL example from the article:
const nullable string email = system.console?.ask_string ( "Please enter Alice's email address: " )
if email is not null then
system.out.write_line ( """Alice's email address is {{email}}""" )
else
system.out.write_line ( "Alice doesn't have an email address." )
end
to hypothetical option type:
const option<string> email = system.console?.ask_string ( "Please enter Alice's email address: " )
if email.is_present() then
system.out.write_line ( """Alice's email address is {{email.get()}}""" )
else
system.out.write_line ( "Alice doesn't have an email address." )
end
- darylteo 12y agoYup. It's mostly a mental hint to the programmer that "HEY this thingie could be null!".
- lomnakkus 12y agoNot with a good type system, i.e. a type system which supports algebraic types (or equivalent) and which explicitly disallows null. With such a type system you wouldn't be able to write the second example as is since string interpolation/concatenation wouldn't be defined for option<string>, only string. You would write something like: const option<string> maybeEmail = .... case maybeEmail of Some email -> system.out.write_line("....{{email}}") None -> system.out.write_line("Alice doesn't have an email address.") The thing to notice here is that we're accessing "email" and not "maybeEmail" in the Some case. This guarantees that we cannot get a null value (since the possibility has been eliminated by the case match). This simple example doesn't do it justice, however. The real benefit comes when you have functions taking option<X> vs. X arguments and/or returning option<X> vs. X. If you get a plain X (either as a return value or parameter) you know that it cannot be null. No such luck in a language which permits "null" as a value for all (reference) values. Of course algebraic data types go much further than just this. I'd encourage you to look into them in e.g. Haskell or some variant of ML.