Kotlin / api-guidelines

Best practices to consider when writing an API for your library

Home Page:https://kotl.in/api-guide

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[To discuss] Explain the difference between arithmetic- and storage- primitive types

qwwdfsad opened this issue · comments

It would be nice to explain and provide recommendations regarding usages of various types in public API.

The overall recommendations should make a clear distinction between arithmetic types (e.g. Int, Long and Double, ones that folks do arithmetics around) and storage types (e.g. Short, Byte, Float, ones that are rather a memory layout optimization), as well as provide a recommendation what should be used in public's API and why
Also let's deprecate Char while we are here

An interesting case is things that are denoted with numbers, but are primarily used as symbols.

  • Is the numeric ID of a document storage data or arithmetic data?
    • What if the IDs are assigned sequentially?
  • Is the string 20230424 (a single-number representation of today's date) storage data?
  • What about things that permit some arithmetic on them but only partially? Whereas a human can get away with fuzzy arithmetic, a computer may not have that privilege.
    • For example, clock readings: sure, typically, there are ten hours between 10:32 and 20:32, but on some days, in some timezones, with DST transitions, it may not be universally so.
    • Even just days of the month: sure, there are exactly seven days between Nov. 2nd and Nov. 9th, but the number of days between the 24th of February and the 10th of March is undefined.

@dkhalanskyjb I believe that timestamps are API types (for example, LocalDateTime), while their storage counterparts could be very different (for example, most probably DBs will store them as Longs).

I would go with API, not arithmetic types if we're talking naming.

I have a different question: if our API type is Integer, while storage is in, say Shorts, don't we make our application more fragile?

@asm0dey, you can find things like 20240102L flying across API endpoints, which are not LocalDateTime instances but also aren't arithmetic numbers.

This is definitely something I would not recommend to in the guide :)