Uploaded image for project: 'REEF (Retired)'
  1. REEF (Retired)
  2. REEF-1390

Make Optional's toString() and hashCode() computed on demand

    XMLWordPrintableJSON

Details

    • Improvement
    • Status: Resolved
    • Minor
    • Resolution: Fixed
    • None
    • 0.15
    • REEF

    Description

      Optional's constructor preloads valueStr and valueHash for its toString() and hashCode() methods respectively, even when those methods are never invoked during the life of the object.

        private Optional(final T value) {
          this.value = value;
          this.valueStr = "Optional:{" + value + "}";
          this.valueHash = value.hashCode();
        }
      

      It incurs unnecessary overhead, and the problem becomes worse if the size of value is huge and T's hashcode() requires heavy computation.

      They should be done in toString() and hashCode() methods on demand, respectively like below:

        private Optional(final T value) {
          this.value = value;
        }
      
        @Override
        public String toString() {
          return "Optional:{" + this.value + "}";
        }
      
        @Override
        public int hashCode() {
          return this.value.hashCode();
        }
      

      +As a related issue, when value is null, it's better to return a reference of a static variable for empty Optional, not making separate objects every time. The following is the current code.

        public static <T> Optional<T> empty() {
          return new Optional<>();
        }
      

      Attachments

        Activity

          People

            wonook Wonook
            wylee Woo-Yeon Lee
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: