Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Consider removing String.toLocalDate(), String.toInstant(), etc. #339

Closed
dkhalanskyjb opened this issue Jan 23, 2024 · 1 comment
Closed
Labels
formatters Related to parsing and formatting

Comments

@dkhalanskyjb
Copy link
Collaborator

Right now, we have two ways to parse something:

LocalDate.parse("2024-01-23")
"2024-01-23".toLocalDate()

With the introduction of datetime formatting (#251), we'll get other ways to do exactly the same:

LocalDate.Formats.ISO.parse("2024-01-23")
LocalDate.parse("2024-01-24", LocalDate.Formats.ISO)

and some others.

The form "2024-01-23".toLocalDate() looks a bit out-of-place. Parsing a string into a LocalDate is a way to construct a LocalDate (and so fits well into the companion object of LocalDate), not a property of String. We do have "123".toInt(), "123".toDouble(), and other primitive types already. We don't have "1m".toDuration() for kotlin.time.Duration.

In terms of separation of responsibilities, String.toLocalDate() looks strange, but it can be practical when chaining calls. Of the three options below, using toLocalDate looks the least busy:

getUser(id).await().birthDate.toLocalDate()
LocalDate.parse(getUser(id).await().birthDate)
getUser(id).await().birthDate.let { LocalDate.parse(it) }

The problem is that it's tough to think of cases when such code would be written. Typically, when you accept some unstructured data, it should be parsed and validated first and only then used, so birthDate should probably already be a LocalDate and not need any conversion. For String.toInt(), it's clear when it could be useful: for example, when just a single number is being parsed, which is fairly common. It's more difficult to think of dates that are not part of some larger data structure.

@dkhalanskyjb dkhalanskyjb added the formatters Related to parsing and formatting label Jan 23, 2024
@hrach
Copy link

hrach commented Jan 23, 2024

We usually use the reference feature - it is not that different from the string extension.

getUser(id).await().birthDate.toLocalDate()
getUser(id).await().birthDate.let(LocalDate::parse)

dkhalanskyjb added a commit that referenced this issue Jan 26, 2024
dkhalanskyjb added a commit that referenced this issue Feb 15, 2024
dkhalanskyjb added a commit that referenced this issue Feb 19, 2024
dkhalanskyjb added a commit that referenced this issue Feb 20, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
formatters Related to parsing and formatting
Projects
None yet
Development

No branches or pull requests

2 participants