Search code examples
javaclassjava-timemethod-chainingperiod

Periods class implementation in java 8


If I code like this:

Period wrong = Period.ofYears(1).ofWeeks(1);

It gives output of P7D.

By the implementation of Period class we know that all of____() methods are static.

But if you to do same chaining with DateTime class:

LocalDate date = LocalDate.of(2020, Month.JANUARY, 20);
LocalTime time = LocalTime.of(5, 15);
LocalDateTime dateTime = LocalDateTime.of(date, time)
  .minusDays(1).minusHours(10).minusSeconds(30);

All minus___() and plus___() methods are instance methods in LocalDateTime class.

Question: why is method chaining not allowed for the Period class?

Why the Period class isn't supporting that?

How the internal assignment is going on ?


Solution

  • You are not chaining calls in your first example.

    Period wrong = Period.ofYears(1).ofWeeks(1);
    

    is the same as:

    Period wrong = Period.ofWeeks(1);
    

    In other words: the object returned by ofYears() does not affect the result of ofWeeks() and it's year value will be discarded. You are invoking the static method ofWeeks(). What you are doing there is not a fluent call chain.

    And any decent IDE should warn you about doing so. The reason is simple: this "chaining" simply doesn't make sense!

    The ofXyz() calls create a new Period object for you. That object is done and created. What should be the semenatics of chaining another ofXyz() call onto the existing period?

    In other words: you can't chain ofXyz() calls because there is no clear way to express the semantics that such a chain should have!