4 ms·
I sometimes wonder if the problem is that we don't have enough nulls. null is typically used as a flag value, but the meaning can be ambiguous: maybe it's the
by recursivedoubts 6y ago
I sometimes wonder if the problem is that we don't have enough nulls.
null is typically used as a flag value, but the meaning can be ambiguous: maybe it's the absence of a value, maybe an error occured, etc. Sometimes it has more than one meaning for the same type.
Maybe types should be allowed to declare multiple nulls (effectively like an Enum in java) for different flag values. Operations on the different nulls would throw specialized exceptions indicating why that particular null value exists. Equality... hmmm.
- sabellito 6y agoI'm not 100% sure if you're being serious, but in case you are, Algebraic Data Types exist to accommodate those ideas.
- reificator 6y ago> null is typically used as a flag value, but the meaning can be ambiguous Languages like Haskell or Rust handle this in a straightforward way by removing the null and using sum types to replace them. > maybe it's the absence of a value Option<T> contains a possible value, or nothing. https://doc.rust-lang.org/std/option/ https://doc.rust-lang.org/std/option/ > maybe an error occured Result<T, E> contains either a value or an error. https://doc.rust-lang.org/std/result/index.html https://doc.rust-lang.org/std/result/index.html > Sometimes it has more than one meaning for the same type. Result<Option<T>, E> is a result that might have a value.
- kerblang 6y agoCompletely reasonable request, easy to implement along the lines of: public class Name { private Name(String name, int flag){...} public static Name asMissing(){new Name(null, -1);} public static Name asNotApplicable(){new Name(null, -2);} public static Name asNotAvailableYet(){new Name(null, -3);} public static Name asForbidden(){new Name(null, -4);} public static Name create(String name){new Name(name, 0)} public boolean isMissing(){flag==-1} public boolean isNotApplicable(){flag==-2} public boolean isNotAvailableYet(){flag==-3} public boolean isForbidden(){flag==-4} public String get() {if (flag!=0) throw new Exception(flag) else name} }
- recursivedoubts 6y agoYep. I'd prefer enum-like syntactic sugar, something like: public class Name { private Name(String name){...} flags { MISSING, NOT_APPLICABLE, NOT_AVAILABLE_YET, FORBIDDEN } ... } In particular, you shouldn't have to specify a constructor, since these are flag values that don't necessary have any state associated with them.
- int_19h 6y agoMost of those meanings don't make sense for the type itself to define, because it's the context where the type is used that determines whether something can be missing, or there can be an error etc. ADTs solve that.