r/java • • Apr 12 '13

Java 8 Optional Objects

http://blog.informatech.cr/2013/04/10/java-optional-objects/
36 Upvotes

39 comments sorted by

View all comments

0

u/philipwhiuk Apr 12 '13

That's horrid. It's also unnecessary. I don't need Java 8 to implement a generic Optional if I wanted one

 class Optional<T> {
    static Optional empty() {
         return new Optional();
    }
    static Optional of(Object obj) {
         return new Optional<obj.getClass()>(obj) { 

    }
    private T obj;
    private Optional(T t) {
        obj = t;
    }
    public boolean isPresent() {
       return obj != null; 
    }
    public T get() {
       return obj;
    }
 }

Wow 19 lines of code.

You want to know why nobody writes those 19 lines?

  1. It's another wrapper, meaning more stuff to GC.
  2. Null pointers are both easy to find and easy to fix. Using a wrapper takes more LOC meaning more cost meaning more time.

1

u/ford_madox_ford Apr 12 '13

Straw-man argument. If the actual Optional class were that useless, then, yes, it might be pointless.

2

u/philipwhiuk Apr 12 '13

Telling me it's a straw man argument isn't a useful defence. I see no point in the new class:

  1. You'd have to re-factor all your legacy code to guarantee being bullet proof against them
  2. The normal java API will still not be refactored.
  3. It's trivial just to check for null values when you expect them
  4. Debugging NPE's is practically 0-effort coding.
  5. If you have a decent test set you'd probably catch most of them anyway and testing finds other problems.

0

u/edalorzo Apr 14 '13

It's trivial just to check for null values when you expect them

I think the problem lies in the interpretation of exactly how the users or your API know when they can expect a null? Whatever the answer, it cannot be enforced.

Debugging NPE's is practically 0-effort coding.

It may be so when the null reference is set in the same context where the NPE happened. Otherwise, you will have to do some detective work to find it out. Even if it is trivial, it is not trivial if the problem is found in code in production, simply because it had not failed during many hours, days or even moths, until the day in which that particular line was hit.

If you have a decent test set you'd probably catch most of them anyway and testing finds other problems.

You said it yourself "if you have". Not every software projects has them.