Skip to content

Fix java.time's brittleness #108

Open
@ohbadiah

Description

@ohbadiah

Hi, I'm filing this tongue-in-cheek, but I hope it's edifying.

I did a coding test for a job today. I used clj-time. I got the right answers. Later on I was embarrassed I had used a deprecated library, and so I decided to upgrade to current best practices.

My issue boils down to: in the java time api, you can't parse a LocalDate from a formatter like "yyyy". For example:

(jt/local-date "yyyy" "2024")

will get you

java.time.DateTimeException                                                                                                                                                                                 
   Unable to obtain LocalDate from TemporalAccessor: {Year=2024},ISO of type java.time.format.Parsed 

This leads to code like this:

(defn parse-date [date-str]
  (condp = (count date-str)
    4 (-> (java.time.Year/parse date-str yyyy)
          (.atMonth 1)
          (.atDay 1))
    6 (-> (java.time.YearMonth/parse date-str yyyyMM)
          (.atDay 1))
    8 (jt/local-date "yyyyMMdd" date-str)))

instead of this clj-time code:

(def parse-date
  (partial clj-time.format/parse
           (clj-time.format/formatter clj-time.core/utc
                                      "yyyy"
                                      "yyyyMM"
                                      "yyyyMMdd")))

The problem here seems somewhat philosophical to me. Here the library is just faithfully wrapping java.time, but due to the brittle type hierarchy, that results in code which really smells like java, somewhat defeating the purpose. Maybe there's nothing that can be done here? But in the off chance anyone has thoughts about a layer that could be added to make a more clojure-like API, I'd be interested to hear.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions