News for hackers. Stuff that matters.
Re:Please put units in names by jeffparsons on Sunday March 20, 2022 @11:51PM (#30750018)
100%. This is a baseline requirement where I work. If you don't either include the units in the identifier name, or use the type system where possible, your code is not getting merged.

The only people I've ever met that think this is unnecessary are also the same people that ship a lot of bugs for other people to fix.

Re:Please put units in names by michaelt on Monday March 21, 2022 @06:48AM (#30752482)
> The only people I've ever met that think this is unnecessary are also the same people that ship a lot of bugs for other people to fix.

I find feelings about this depend a lot on how much ceremony the type system involves; and just how many units and references to them there are in the system.

Asking bash coders to write "sleep 5s" instead of "sleep 5" - I doubt you'd get any objections at all.

But if you're putting a foo.bar.Duration on a getDefaultTimeoutFromEnvironment on a setConnectTimeout on a HttpRequest on a HttpRequestInitializer on a NetHttpTransport on a ProviderCredential to make a simple get request? People who've come from less ceremony-heavy languages might feel less productive, despite producing 10x the lines of code.

Re:Please put units in names by contravariant on Monday March 21, 2022 @07:02AM (#30752568)
Well ignoring the silly stuff this would just boil down to something like:

    request = NetHttpTransport.Request()
    request.setConnectTimeout(getDefaultTimeoutFromEnvironment().seconds)
which is verbose, but at least it's fairly clear.

And yes I'm calling a class named HttpRequestInitializer silly, I don't care if some language decided it should exist.

Re:Please put units in names by gregmac on Monday March 21, 2022 @10:49AM (#30754757)

    request.setConnectTimeout(getDefaultTimeoutFromEnvironment().seconds)
This is actually a very good example of what not to do, with the mistake being in whoever implemented setConnectTimeout()

I actually don't know this particular API, but I'm used to timeouts being in milliseconds, so that code looks wrong to me.

Much better API, and what the article is talking about, is to change this to:

    .setConnectTimeoutMilliseconds(getDefaultTimeoutFromEnvironment().seconds)
Now the mistake is obvious, and even if the original developer doesn't notice it will stick out in a PR or even a causal glance.
Re:Please put units in names by LgWoodenBadger on Monday March 21, 2022 @11:28AM (#30755191)
That's one of the benefits of having it exposed as a type-enforced parameter. setConnectTimeout() could take a Duration, which contains the amount and the unit, and therefore wouldn't care if consumer A provided a timeout in seconds, and consumer B provided a timeout in milliseconds.
Re:Please put units in names by gregmac on Monday March 21, 2022 @01:17PM (#30756887)
Totally agree, but then I would expect the code would be:

    request.setConnectTimeout(getDefaultTimeoutFromEnvironment())
with getDefaultTimeoutFromEnvironment() returning a Duration.

Ideally this is consistent throughout the codebase, so that anything that uses a primitive type for time is explicitly labelled, and anything using a Duration can just be called "Timeout" or whatever.

Re:Please put units in names by makapuf on Monday March 21, 2022 @11:22AM (#30755113)
This example is nice but if you put arguments metadata in the function name, you have to have one main argument, the function name can prove cumbersome if you have 3 or 4 arguments with units like

    .setPricePerMassInCentsPerKilogramsWithTimeoutInMilliSeconds(100,2,300)
Re:Please put units in names by elcomet on Monday March 21, 2022 @12:04PM (#30755672)
I think you should rather do

  .setPrice(priceInCents=100, massInKg=2, timeoutInMs=300)
Re:Please put units in names by gregmac on Monday March 21, 2022 @01:21PM (#30756958)
I'd argue there are better API patterns for this though -- keeping in mind this values code readability (and correctness) over micro-optimization:

    .setPriceInCents(100);
    .setMassInKilograms(2);
    .setTimeoutInMilliseconds(300);
or

    .calculate({
        priceInCents = 100,
        massInKilograms: 2,
        timeoutInMilliseconds: 300,
    });
Re:Please put units in names by HelloNurse on Tuesday March 22, 2022 @06:52AM (#30764625)
Values with an intrinsic unit scale up to many units and values. If you declare the parameters of a "calculate" function as USACurrency, Weight and Duration you can write

    calculate(100cent, 2Kg, 300s)   
    calculate(0.1dollar,4.7lb/*approximate*/,5min)
    calculate(something.price(),whatever.weight(),options.getDuration("exampleTimeout"))
    calculate(USD(0.1),Kg(2),Minute(5))
Re:Please put units in names by contravariant on Monday March 21, 2022 @01:44PM (#30757313)
All fair points. In this example I was suggesting what this might look like at the border of the application where you need to talk to some (standard) library which doesn't use the same convention.
Re:Please put units in names by michaelt on Monday March 21, 2022 @08:13AM (#30753148)
A class named 'HttpRequestInitializer' and taking 10 lines to set a timeout on a HTTP request isn't merely hypothetical: https://developers.google.com/api-client-library/java/google... - and that's not counting any import statements.

(although getDefaultTimeoutFromEnvironment was artistic license on my part)

Re:Please put units in names by contravariant on Monday March 21, 2022 @08:28AM (#30753266)
True, but like I said that doesn't make it not silly. Just harder to fix.

Edit: Also, overriding a class method dynamically inside a function? I usually program python these days and even I think that's wild.

Re:Please put units in names by jsight on Monday March 21, 2022 @09:21AM (#30753807)
Its an interface with only method. I suspect that most of us would just us a lambda now.
Re:Please put units in names by contravariant on Monday March 21, 2022 @09:26AM (#30753842)
I'll never quite understand why it wasn't simply a function in the first place.
Re:Please put units in names by dtech on Monday March 21, 2022 @10:26AM (#30754502)
Java pre-8 only had anonymous classes, there were no lambdas
Re:Please put units in names by fiddlerwoaroof on Monday March 21, 2022 @11:39AM (#30755308)
And Java lambdas are still syntax sugar for one-method anonymous classes.
Re:Please put units in names by sethammons on Monday March 21, 2022 @07:40AM (#30752874)
This is where I divert. You just hard coded seconds into your test. Now your tests that cover this must take seconds to finish; thankfully you were not testing hours or days!

My last shop was a Go shop and one test I think shows this off was an SMTP server and we needed to test the timeouts at different states. The test spun up half a dozen instances of the server, got each into the right smtp state and verified timeouts in under 10ms.

The environment that set the timeout would either be "timeout_ms=500" or "timeout=500ms" (or whatever). This is where you handle that :)

Re:Please put units in names by contravariant on Monday March 21, 2022 @07:51AM (#30752970)
Not sure I fully understood your objection, but the reason I specified seconds is because I presumed the setConnectTimeout to be part of the default HTTP library, which likely doesn't adhere to the same conventions, and that it expected seconds (which seem to be the usual for http libraries as far as I can tell).

Of course if the setConnectTimeout method was part of the same application you could just pass the timeout directly, but at the boundary of your application you're still going to have to specify at some point which unit you want.

Re:Please put units in names by hansvm on Monday March 21, 2022 @10:00AM (#30754207)
If you're testing things with timeouts it's often a good practice to mock out the system clock anyway. That allows testing your timeouts to be nearly instantaneous and also catches edge cases like the clock not moving forward, having a low resolution, moving backward, ... deterministically.
Re:Please put units in names by dnadler on Monday March 21, 2022 @08:07AM (#30753092)
The test could simply mock the default value to something reasonable like '.1 seconds' and test that duration instead, so I don't think this is a real problem.
Re:Please put units in names by catlifeonmars on Monday March 21, 2022 @10:55AM (#30754832)
This is actually revealing a different problem: the system clock as an implicit dependency. YMMV depending on support of underlying libraries, but I will typically make the clock an explicit dependency of a struct/function. In Go, usually it’s a struct field `now func() time.Time` with a default value of `time.Now`.
Re:Please put units in names by dahfizz on Monday March 21, 2022 @07:49AM (#30752951)
Many timeout functions take seconds as a floating point. So you could time out on 0.05 seconds (5 milis). But now the code is clear and less prone to bugs.
Re:Please put units in names by sethammons on Monday March 21, 2022 @07:56AM (#30753003)
In Go, you don't pass a float, you pass a duration
Re:Please put units in names by catlifeonmars on Monday March 21, 2022 @10:57AM (#30754848)
Which is unitless, hence there is no problem. `time.Duration.Seconds()` returns a floating point.
Re:Please put units in names by vvillena on Monday March 21, 2022 @07:41AM (#30752885)
The 80/20 approach of renaming "timeout" to "timeoutSeconds" or "timeoutMillis" is also valid. They key takeaway is to not make assumptions.
Re:Please put units in names by rowanajmarshall on Monday March 21, 2022 @10:10AM (#30754315)
> I find feelings about this depend a lot on how much ceremony the type system involves; and just how many units and references to them there are in the system.

Ideally it'd be as simple as:

typealias Dollars = BigDecimal

typealias Cents = Long

that's valid Kotlin, but the equivalent is doable in most languages nowadays (Java being a big exception).

Re:Please put units in names by dtech on Monday March 21, 2022 @10:29AM (#30754525)
I recommend against that, and use proper (wrapper) types.

I don't know Kotlin, but in most languages if you alias 2 types to the same base type, for example Seconds and Minutes to Long, the compiler will happily allow you to mix all 3 of them, defeating the protection full types would bring.

Re:Please put units in names by stefs on Monday March 21, 2022 @02:56PM (#30758205)
that's correct. typealiases are the wrong solution here. the better solution would be value classes, but of course, the unit shouldn't be the type.
Re:Please put units in names by dragonwriter on Monday March 21, 2022 @11:29AM (#30755193)
> typealias Dollars = BigDecimal

> typealias Cents = Long

If I ever have to deal with monetary values in a program where someone thought this was a good idea, ... well, it really won't be the worst thing I’ve ever dealt with, but, still.

(If you have dollars and cents as types in the same program, they darn well better work properly together, which is unlikely to work if they are both just aliases for basic numeric types.)

Re:Please put units in names by stefs on Monday March 21, 2022 @03:18PM (#30758501)
don't do this!

    typealias Cents = Long
    typealias Meters = Long
    
    Cents(3) + Meters(4) = 7L
that's exactly the thing we want to prevent.

the classes shouldn't be for units at all, the type should represent the type of unit.

so instead of a class Seconds you should have a class Duration, instead of class Meters you should have a type Distance. that's because the unit of the different types can be converted between each other.

Dollars and Cents are a bit of a bad example because currencies can't be easily converted between each other, as conversion is dependent on many factors that change over time. meters, yards, feet, lightyears, miles, chain, furlongs, whatever describe a multiple of the same thing though, so a different type for each unit isn't necessary, as the input that was used to create the instance isn' usually needed. the counter example would be datetime with timezones - a datetime with a timezone convers a lot more information than the datetime converted to UTC.

Re:Please put units in names by nightfly on Monday March 21, 2022 @03:50AM (#30751385)
What type of industry/product do you work in/on? And what sort of languages do you work in?
Re:Please put units in names by physicsguy on Monday March 21, 2022 @04:15AM (#30751561)
Not the commenter, but I work in scientific software development and it's just a minefield of different units, so being explicit is generally very useful. Even if you can assume you can stick to metric (you can't), what different users want varies across countries. For e.g. here in the UK we often want to represent data as millilitres, but in France the same measurements are often centilitres.

I don't use libraries to enforce it though, we did try this but found it quite clunky: https://pint.readthedocs.io/en/stable/

Re:Please put units in names by LeifCarrotson on Monday March 21, 2022 @07:45AM (#30752920)
It varies across different users from the same city! The same family, even!

One piece of equipment I just finished working on measured and displayed vacuum at different sensors in PSIg, kPa, Pa, mmHg, and inHg. The same machine, the same measurement at different stages in the process, five different units!

Re:Please put units in names by DocTomoe on Monday March 21, 2022 @04:11AM (#30751537)
Not OP, but I see that a lot in the aerospace and heavy industry sectors.

We keep laughing about "if we engineered bridges as we engineer software" ... the truth is that the areas where correct software matters tend to write very robust code, and the rest of the industry would be well advised to take notice and copy what they see.

Of course, writing robust code is a skill, and it takes extra time.

Re:Please put units in names by regularfry on Monday March 21, 2022 @07:18AM (#30752675)
It takes time to learn, and to learn the value, and time to agree with the team that it's sensible. With this sort of thing - proper naming of variables - I disagree that it takes longer at point of use.
Re:Please put units in names by mhaberl on Monday March 21, 2022 @06:30AM (#30752368)
> and the rest of the industry would be well advised to take notice and copy what they see

I don't agree.

There is a good reason that aerospace industry writes robust code - in invests time (money) to avoid disasters that could cause, among other things, loss of human life.

On the other hand if for example some webform validation fails because the code was written as fast (as cheap) as possible, who cares really.

That is just a tradeoff, in aerospace industry you spend more to lower the risk, somewhere else you don't.

Re:Please put units in names by thfuran on Monday March 21, 2022 @07:33AM (#30752820)
>On the other hand if for example some webform validation fails because the code was written as fast (as cheap) as possible, who cares really.

Who knows. Maybe a billion dollar company that can't fulfill orders. Maybe a million people who suddenly can't use their bank online.

Re:Please put units in names by mhaberl on Monday March 21, 2022 @03:29PM (#30758615)
Yes, sure, but a "billion dollar company" in this case does not represent the whole industry.

You can probabbly find a some specific non-critical case in aerospace industry, but surely based on that example one would not suggest that the whole aerospace industry should just copy what they see in frontend dev.

Context matters, there are exceptions, but the standard practices are based on average scenario, not on extremes.

Re:Please put units in names by thfuran on Tuesday March 22, 2022 @11:56AM (#30767631)
I'm not saying that all code should be developed under standards designed for embedded control system software. I'm just saying that "oh, it's just web stuff so it can't be important" is ridiculous.
Re:Please put units in names by mhaberl on Tuesday March 22, 2022 @07:39PM (#30773056)
>>> and the rest of the industry would be well advised to take notice and copy what they see

>> I don't agree.

>> [web form validation example]

>> That is just a tradeoff, in aerospace industry you spend more to lower the risk, somewhere else you don't.

> I'm just saying that "oh, it's just web stuff so it can't be important" is ridiculous.

This feels like a straw man.

The original argument is that the rest of the industry (that includes web, but a lot of other parts also) should copy what they see in aerospace industry.

I believe that would not be appropriate for the rest of the industry to just copy practices from any other part because each segment has its own risk factors and expected development costs and with that in mind developed their own standard practices. Nowhere did I state that the "web stuff can't be important" nor that there is no example of web development (form validation) where the errors are insignificant.

That said, I will go back to the "billion dollar company that can't fulfill orders" / "million people who suddenly can't use their bank online" catastrophe; this happens all the time. Billion dollar company doesn't fulfill orders, error is fixed, orders are fulfilled again, 0.0..01% of revenue is (maybe) lost.

In aerospace industry a bug is deployed, people are dead. No bugfixing will matter after that moment.

How can this two industries have the same standards of development?

Re:Please put units in names by a9h74j on Monday March 21, 2022 @07:51AM (#30752973)
Yes, as a comparison, let's just take all the units (em, px, %) out of writing CSS and see how fun that becomes to review and troubleshoot.
Re:Please put units in names by dotancohen on Monday March 21, 2022 @07:33AM (#30752814)
I'm certain that the Mars Climate Orbiter had a lot to do with this practice.
Re:Please put units in names by wffurr on Monday March 21, 2022 @07:28AM (#30752760)
Also not OP, but I work on graphics software and we frequently deal with different units and use strict naming systems and occasionally types to differentiate them.

Even more fun is that sometimes units alone aren't sufficient. We need to know which coordinate system the units are being used in: screen, world, document, object-local, etc. It's amazing how many different coordinate systems you can come up with...

Or which time stream a timestamp comes from, input times, draw times (both of which are usually uptime values from CLOCK_MONOTONIC) or wall times.

Re:Please put units in names by ReleaseCandidat on Monday March 21, 2022 @07:39AM (#30752867)
As a bonus, coordinate systems can be left-handed or right-handed, and the axes point in different directions (relevant when loading models for example).
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?