Why NOT use optionals in Swift? -
i reading on how program in swift, , concept of optionals bugged me little bit. not in terms of why use optionals, makes sense, more in case not want use optionals. understand, optional allows object set nil, why not want feature? isn't setting object nil way tell arc release object? , don't of functions in foundation , cocoa return optionals? outside of having type character each time refer object, there reason not use optional in place of regular type?
there tons of reasons not use optional. main reason: want express value must available. example, when open file, want file name string, not optional string. using nil
filename makes no sense.
i consider 2 main use cases: function arguments , function return values.
for function arguments, following holds: if argument needs provided, option should not used. if handing in nothing okay , valid (documented!) input, hand in optional.
for function return values returning no optional nice: promise caller receive object, not either object or nothing. when not return optional, caller knows may use value right away instead of checking null first.
for example, consider factory method. such method should return object, why should use optional here? there lot of examples this.
actually, apis should rather use non-optionals instead of optionals. of time, passing/receiving possibly nothing not want. there rather few cases nothing option.
each case optional used must thoroughly documented: in circumstances method return nothing? when okay hand nothing method , consequences be? lot of documentation overhead.
then there conciseness: if use api uses optional on place, code cluttered null-checks. of course, if every use of optional intentional, these checks fine , necessary. however, if api uses optional because author lazy , using optional on place, checks unnecessary , pure boilerplate.
but beware!
my answer may sound if concept of optionals quite crappy. opposite true! having concept optionals, programmer able declare whether handing in/returning nothing okay. caller of function aware of , the compiler enforces safety. compare plain old c: not declare whether pointer null
. add documentation comments state whether may null
, such comments not enforced compiler. if caller forgot check return value null, received segfault. optionals can sure noone dereferences null
pointer anymore.
so in conclusion, null-safe type system 1 of major advances in modern programming languages.
Comments
Post a Comment