3 ms·
A systems programming language that expose pointers will not be able to shed NULL. But a higher-level language can and a "pure" OOP language should - because nu
by vmathew 16y ago
A systems programming language that expose pointers will not be able to shed NULL. But a higher-level language can and a "pure" OOP language should - because null make objects unable to respond to messages. Something that claims to belong to the type system and cannot respond to messages just don't fit in there.
- cperciva 16y agoOk, I'll bite: In your idea of a perfect object-oriented language, how do you encode "we might or might not have a left child"?
- vmathew 16y agoThis is one possible way of doing it: class Node { static const Node EMPTY_NODE = Node(); String key; String value; Node left = EMPTY_NODE; Node right = EMPTY_NODE; Node(String key, String value) { this.key = key; this.value = value; } static void traverseInorder(Node n, Visitor v) { if (n.left != EMPTY_NODE) { traverseInorder(left, v); } v.visit (n); if (n.right != EMPTY_NODE) { traverseInorder(right, v); } } }
- cperciva 16y agoOk, and how exactly is that different from using NULL, aside from being more complicated?
- vmathew 16y agoclass Node { // May not be a real situation for a Node class, // but makes a point. Node getLeft() { return left; } } // No more checks against NULL. In fact code becomes simpler for // the user of the library. node.getLeft().getLeft().getValue(); I don't think the class definition is much too complicated, except for the declaration of the EMPTY field. What we need is a non-mutable, class-wide, default object, not null. We don't need to explicitly declare this object, if the language does that for us and make it accessible through a keyword - say 'default': if (n.left != default) { traverse(n.left); }
- cheald 16y agoRuby uses a nil type, but due to its flexibility, nil can also respond to messages! Its presence is greatly appreciated, and it's not a NULL in the "This is a pointer to 0x0" sense, but in terms of how you use it, it's functionally equivalent. By means of example: irb(main):003:0> nil.class => NilClass irb(main):004:0> nil.nil? => true irb(main):005:0> nil.methods => ["inspect", "method", "tap", "&", "clone", "public_methods", "__send__", ...] irb(main):006:0> nil.is_a? String => false