News for hackers. Stuff that matters.
Re:Please put units in names by Aeolun on Monday March 21, 2022 @04:05AM (#30751498)
What does a type for ‘seconds’ do that an ‘integer’ doesn’t?

I may be misunderstanding this.

Re:Please put units in names by GuB-42 on Monday March 21, 2022 @08:44AM (#30753423)
The type is "duration", not "seconds". "seconds" is the unit. You can think of the unit as an operator that converts an integer to a duration.

The advantages are:

- An integer doesn't tell you if you are talking about seconds, milliseconds or anything like that. What does sleep(500) means? Sleep 500s or 500ms? sleep(500_ms) is explicit

- It provides an abstraction. The internal representation may be a 64-bit number of nanoseconds, or a 32-bit number of milliseconds, the code will be the same.

- Conversions can be done for you, no more "*24*60*60" littered around your code if you want to convert from seconds to days, do fun(1_day) instead.

- Safety, prevents adding seconds to meters for instance. Ideally, it should also handle dividing a distance by a duration and give you a speed and things like that.

Under the hood, it is all integers of course (or floats), which is all machine code, but handling units is one of the things a high level language can do to make life easier on the human writing the code.

Re:Please put units in names by kitd on Monday March 21, 2022 @04:21AM (#30751607)
A function might take multiple integer arguments, each in different units. Separate types for each unit guarantees you won't pass the wrong integer into the wrong argument.

Eg

  func transferRegularly(dollars(10000), days(30)) 
Meaning clear.

  func transferRegularly(10000, 30)
Meaning obscure, error prone and potentially costly
Re:Please put units in names by necovek on Monday March 21, 2022 @07:02AM (#30752571)
With some languages like Python, you can use keyword arguments too (even out of order).

Eg. you could simply do

  transferRegularly(amount=10000, period_in_days=30)
I am always amazed how new languages never pick up this most amazing feature of Python.

Though obviously, this code smells anyway because 1. repetitive transfers are usually in calendar units (eg. monthly, weekly, yearly — not all of which can be represented with an exact number of days), so in Python you'd probably pass in a timedelta and thus a distinct type anyway, and 2. amounts are usually done in decimal notation to keep adequate precision and currency rounding rules (or simply `amount_in_cents`).

Still, I am in favour of higher order types (eg. "timedelta" from Python), and use of them should be equally obligatory for unit-based stuff (eg. volume, so following the traditional rule of doing conversions only at the edges — when reading input, and ultimately printing it out).

Re:Please put units in names by kitd on Monday March 21, 2022 @09:39AM (#30753975)
I see keyword arguments as slightly different though. The keyword is like the parameter name. The value is still a plain integer and (theoretically) susceptible to being given the wrong integer. In contrast, unit types allow for hard checking by the compiler.

In practice, with good naming it won't make much difference and only shows up when comparing the docs (or intellisense) for an API with how it is actually used.

Re:Please put units in names by steelframe on Monday March 21, 2022 @11:02AM (#30754898)
> transferRegularly(amount=10000, period_in_days=30)

dollars(10000) is still better than this example, because: 10000 what? Pennies? USD? EUR?

Re:Please put units in names by necovek on Monday March 21, 2022 @12:55PM (#30756504)
Someone else caught me out on that too by suggesting making it `amount_in_dollars` elsewhere in the thread ;)

Now you can say how there are also AUD, CAD...

The point was simply that if units are needed due to lack of specific type being used, it's nicer to have that in the API when language allows it.

Re:Please put units in names by dotancohen on Monday March 21, 2022 @07:37AM (#30752857)
PHP got this property in PHP 8.

One problem with this approach is refactoring. If you wanted to refactor your example with the parameter "amount_in_dollars" then you would either have to continue maintaining the legacy "amount" argument, or break existing code.

Re:Please put units in names by necovek on Monday March 21, 2022 @10:48AM (#30754751)
So you mean just like with, eg. renaming a function? I agree it's an issue compared to not doing it, but a very, very minor one IMHO, and legibility improvements far outweight it.
Re:Please put units in names by dotancohen on Monday March 21, 2022 @11:18AM (#30755064)
Renaming a function comes with the explicit implication that the API has changed. But it might not be clear to someone maintaining a Python application that changing a parameter name might change an argument - that is not the case in any other language (until PHP 8).

Guess how I discovered this issue :)

Re:Please put units in names by necovek on Monday March 21, 2022 @12:56PM (#30756531)
Well, if the approach was more pervasive, you'd be used to it just like seasoned Python developers are. :)
Re:Please put units in names by davisoneee on Monday March 21, 2022 @04:17AM (#30751573)
if you type check, then it ensures that only a 'second' can be passed to the function. This requires you to either create a second, or explicitly cast to one, making it clear what unit a function requires.

As per the article, if you dont have proper names and just an 'int', that int can represent any scale of time...seconds, days, whatever.

In python youd need something like mypy, but in rust you could have the compiler ensure you are passing the right types.

Re:Please put units in names by huynhhacnguyen on Monday March 21, 2022 @04:39AM (#30751710)
Having a type system to figure this out for us would be great, but there are languages where this may not be possible. As far as I know, Typescript is one such example, isn't it?
Re:Please put units in names by kaoD on Monday March 21, 2022 @04:47AM (#30751762)
Depends. Yes, newtyping is pretty awful in TS due to its structural typing (instead of nominal like Rust for example).

You could perhaps newtype using a class (so you can instanceof) or tag via { unit: 'seconds', value: 30 } but that feels awful and seems to be against the ecosystem established practices.

This is indeed one of my gripes with TS typing. I'm spoiled by other languages, but I understand the design choice.

Re:Please put units in names by hurflmurfl on Monday March 21, 2022 @06:15AM (#30752288)
I was recently dealing with some React components at work, where the components would accept as an input the width or the height of the element.

Originally, the type signature was

    type Props = {height: number}
This naturally raises the question - number of what? Does "50" mean `50px`, `50vw`, `50em`, `50rem`, `50%`?

I've ended up changing the component to only accept pixels and changed the argument to be a string like this:

    type Props = {height: `${number}px`}
Of course, if passing a "0" makes sense, you could also allow that. If you want to also accept, say, `50em`, you could use a union-type for that.

I think this could actually work for other units as well. Instead of having `delay(200)`, you could instead have `delay("200ms")`, and have the "ms" validated by type system.

Maybe the future will see this getting more popular:

    type WeightUnit = 'g' | 'grams' | 'kg' | ...;
    type WeightString = `${number}${WeightUnit}`;
    function registerPackage(weight: WeightString): void;
Re:Please put units in names by Izkata on Monday March 21, 2022 @11:52AM (#30755511)
> This naturally raises the question - number of what? Does "50" mean `50px`, `50vw`, `50em`, `50rem`, `50%`?

Because it's React, the expectation is "px", using a string with a suffix to override it: https://reactjs.org/docs/dom-elements.html#style

Re:Please put units in names by dbrgn on Monday March 21, 2022 @05:23AM (#30751968)
You can do something like this:

    export interface OpaqueTag<UID> {
        readonly __TAG__: UID;
    }
    export type WeakOpaque<T, UID> = T & OpaqueTag<UID>;
And then use it like this to create a newtype:

    export type PublicKey = WeakOpaque<Uint8Array, {readonly PublicKey: unique symbol}>;
To create this newtype, you need to use unsafe casting (`as PublicKey`), but you can use a PublicKey directly in APIs where a Uint8Array is needed (thus "weak opaque").
Re:Please put units in names by spion on Monday March 21, 2022 @06:03AM (#30752216)
I tried to solve this problem in a way that's reasonably pleasant here https://github.com/spion/branded-types
Re:Please put units in names by smichel17 on Monday March 21, 2022 @07:30AM (#30752781)
The pattern you want here is branding.
Re:Please put units in names by mirekrusin on Monday March 21, 2022 @06:51AM (#30752496)
You can simulate type opaqueness/nominal typing with unique tag/branded types in ts. We’re using it on high stake trading platform and it works very well.
Re:Please put units in names by jsnell on Monday March 21, 2022 @07:26AM (#30752743)
Most answers here are answering your question literally, and explaining why you'd add a type for "seconds". But in reality you shouldn't create a type for seconds, the whole premise of the question is wrong.

Instead of a type for seconds, you'd want a type for all kinds of duration regardless of the time unit, and with easy conversion to integers of a specific time unit. So your foo() function would be taking a Duration as an input rather than seconds, and work correctly no matter what unit you created that duration from:

    foo(Duration.seconds(3600))
    foo(Duration.hours(1))
    foo(Duration.hours(1) + Duration.seconds(5))
Re:Please put units in names by lrem on Monday March 21, 2022 @04:12AM (#30751542)
You can construct a linter that will prevent you from trying to add seconds to dollars.
Re:Please put units in names by akdor1154 on Monday March 21, 2022 @04:18AM (#30751585)
A better example would be seconds to minutes. I think i recall a jwt related cve related to timestamps being misinterpreted between sec/ms for example.
Re:Please put units in names by taneq on Monday March 21, 2022 @05:53AM (#30752154)
Adding seconds to minutes can actually make sense. A minute plus 30 seconds is 90 seconds, or 1.5 minutes. Whether your type system allows this, though, is up to the project.

You can't add seconds to kilometers, or to temperature, or to how blue something is.

Re:Please put units in names by OtomotO on Monday March 21, 2022 @04:21AM (#30751604)
Ideally you have a compiler that simply refuses to compile ambiguous code
Re:Please put units in names by eurasiantiger on Monday March 21, 2022 @05:16AM (#30751915)
Ideally, there is no compiler.
Re:Please put units in names by _flux on Monday March 21, 2022 @05:46AM (#30752107)
Ideally, you would detect all errors before runtime. Usually the compiler is the last gate to make that happen.
Re:Please put units in names by eurasiantiger on Monday March 21, 2022 @12:11PM (#30755776)
Ideally, hardware execution would happen on a language that can be proven correct and does not allow the programmer to make syntactic or semantic errors.

The world is far, far from ideal.

Re:Please put units in names by CamperBob2 on Monday March 21, 2022 @05:37AM (#30752059)
Isn't there an implicit conversion?
Re:Please put units in names by atoav on Monday March 21, 2022 @06:05AM (#30752233)
Well your function could then accept multiple types (Miliseconds, Seconds, Minutes, Hours) and do the conversion between those implicitly.

The units are also extremely clear when they are carried by the type instead of the variable name, where a developer could e.g. change some functionality and end up with a variable called `timeout_in_ms` while the function that eats this variable might expect seconds for some reason.

If it is typed out you can just check if the function performs the right action when passed a value of each time unit type and then you only ever have to worry about mistakingly declaring the wrong type somewhere.

But wether you should really do all that typing depends on how central units are for what you are doing. If you have one delay somewhere, who cares if it is typed or not. If you are building a CNC system where a unit conversion error could result in death and destruction, maybe it would be worth thinking about.

Re:Please put units in names by indymike on Monday March 21, 2022 @07:48AM (#30752948)
Tells you what the integer represents, so you aren't off by several orders of magnitude.
Re:Please put units in names by Cthulhu_ on Monday March 21, 2022 @06:36AM (#30752406)
What does the integer represent? Nano, milli, microseconds, seconds, minutes, hours, days?