Please put units in names
ruudvanasseldonk.com
ruudvanasseldonk.com
Something like:
unit type Meters = m
unit type Seconds = s
function sleep(time: Int[s]): void
val speed = 5.4 m/s // Type = Float[m/s]
val distance = parseFloat(prompt('enter time')) * 1 m // Convert unitless to meters just by multiplying
val time = distance / speed // Type = Float[s]
print("${time}") // Prints "# s"
print("${time / 1 s} seconds") // Prints "# seconds"
val complexUnit = 7 * 1 lbf/in2 // 7 lbf/in2
// != 7 psi (too hard to infer) but you can write a converter function
function toPsi<N : Numeral>(value: N[lbf/in2]): N[psi] {
return value * 1 psi*in2/lbf
}
It requires extending number parsing, type parsing (if the brackets aren't already part e.g. in TypeScript), and extending types to support units of measurement at least if they are statically known to be subtypes of `Numeral`.Naming variables with their units doesn't solve the issue of mis-casting and using units incorrectly, and newtypes are too inconvenient (and sometimes impossible without affecting performance) so nobody uses them. Even as a very software-focused programmer I encounter units like seconds, bytes, pixels, etc. all the time, they are almost never newtypes, and I get bugs from forgetting to convert or converting incorrectly.
Even though branded types prevent assignment of values with invalid units, opaque types are inferior in that the compiler doesn't know the relationship between the types (as exemplified in the parent comment) and you need a slew of helper functions & casting.
F# does if you tell it, i.e.:
[<Measure>] type kg = g
[<Measure>] type m
[<Measure>] type s
[<Measure>] type N = kg * m / s^2
Although, of course, in practice you'd probably just use whatever's defined in https://fsharp.github.io/fsharp-core-docs/reference/fsharp-d...Not for log units tho.
So you need a typescript plugin - however the typescript compiler api (which btw is not officially supported) is not flexible enough to support new type syntax (for things like m/s) so you'd a fork.
The benefits around F# units of measure that the parent talks about are primarily focused on static type checking.
If you are fine with the overhead of runtime boxing, it is relatively straightforward to have different container classes for different units and have bridge apis to convert/operate between them. A babel plugin could potentially help with operator overloading here, but this is quite far removed from F# units of measure at this point.
See std::duration/time_point specifically for times, and boost.units for generalized unit support.
It is implemented via (templated) wrappers, but they are very close to zero overhead if not completely free. User defined literals also allow for a very succinct syntax, but to be honest, I usually don't bother. I normally write:
auto delay = std::chrono::seconds{3};
instead of: auto delay = 1s;It is really nice to have a type system that checks your formulas. Saved me a couple of times.
I understand that the speed variable is automatically assigned a type of Float[m/s] based on the m/s there, but I'm confused about how the units are just placed at the end of the value assignment: val speed = {value} {unit}
Is this just a F# property that units can be added at the end of value assignment, and F# interprets them as units correctly?
Also, anyone know of methods for incorporating units as types in Python? It would be great to have an equivalent method as demonstrated here, where dividing types automatically creates a new type unit, and perhaps even associates with a related type, i.e: type(kg / (m * m * m)) == density
Unfortunately the same isn't as easily done in Python:
1. You would need to reify these units as actual constants with overridden operators to track values, and some wacky (if even possible) mypy type shenanigans.
2. The types aren't erased and so would impact the performance of any critical code. F# isn't quite used in high frequency trading, but it does target numeric heavy users like those wanting to write scientific workloads, and units help improve correctness there. But if the types are computed at runtime and not erased, it would be an enormous hit to performance.
Unless you can figure out some way to get "3.0 * m" to be a plain old datatype (float) in Python while still retaining type info in mypy/pylance/pyrite. Perhaps there's a way, but I'm not sure.
Edit: This Python library seems to be trying to solve for these issues! https://pint.readthedocs.io/en/0.10.1/
I'm not sure if they've actually solved the runtime performance problem, but I suppose as long as you're not doing unit assignment/conversion in a loop, it should be fine.
val distance = parseFloat(prompt('enter time')) * 1 m // Convert unitless to meters just by multiplyingThe documentation read "speed_kmph - This field contains the travelling speed in MILES PER HOUR - please do not be confused by the name".
Woo, great job guys.
I find it really hard to accept any excuse for something like that. It's why enterprise code is so sloppy, people doing the most expedient thing rather than what is correct.
Might be easy if you own the whole codebase and all reporting, but you are also going to break all those linked BI reports that the analysis team has written.
But that makes an assumption you didnt make any shortcuts.
If you don’t, it will assume kmph instead of mph and just present the wrong data! But sure…those graphs still look pretty…
If you can’t make a change without it potentially breaking other stuff, it goes in the “not easy” category for me. Especially if you probably won’t know if stuff is broken until the change is pushed to prod.
It's hard to know what assumptions code is making and by forcing you to change the code everywhere (which should be pretty easy in any modern IDE) you at least have a chance to evaluate any issues that unit change could cause.
I do agree that generally it's better to use something like a struct that's more flexible, but doing that for every function is also quite verbose. For some functions the time requirement may never change as well.
delay(duration = Duration.ofMinutes(minutes = 1))
which is equivalent to delay(timeMillis = 60_000)
Using the optional argument names here for clarity; you don't have to of course.Sticking with the JVM, a frequent source of confusion is the epoch. Is it in millis or in seconds? With 32 bit integers that has to be seconds (which will set you up for the year 2038 problem). However, Java always used 64 bit longs for tracking the epoch in milliseconds instead even before the year 2000 problem was still a thing. Knowing which you are dealing with is kind of relevant in a lot of places; especially when interfacing with code or APIs written in other languages with more 32 bit legacy.
Things like network timeouts are usually in milliseconds. But how do you know this for sure? Specifying, them in seconds means that there's less risk of forgetting a 0 or something like that. So, using seconds is pretty common too. You can't just blindly assume one or the other. Even if you use the Duration class above, you'd still want to put the magic number it takes as a parameter in some configuration property or constant. Those need good names too and they should include the unit.
For example, in Erlang, the sleep function could/should have been written to take named tuples: `timer:sleep({seconds, 3})`
time.Sleep(10 * time.Millisecond)
To me Durations are a zero sum gain, because in this case they hide relevant detail (int64 nanoseconds) without enforcing usage. Compare it against what Golang could easily provide -- time.SleepMilli(100), which is 40% less characters for my aging eyes to parse than time.Sleep(100 * time.Millisecond).
After all, in the very same package we have a unit in the name:
t := time.Time{}
t.UnixMilli() // 1647952024456 timeout = timedelta(seconds=300)
frobnicate(timeout)
Working with GCP or Azure's Python SDK is like navigating a jungle of types. Some calls return a `compute_engine_list_item` while others return a `compute_engine` type and these are difficult to inspect and reason about, because Python classes default to printing something along the lines of `<__main__.myclass at 0x7fa8864a1040>`, making heavily typed Python code quite difficult to work with.No paradigm is going to save you from spaghetti-code, but being able to pass a list and get an integer in return, makes it very easy to reason about what you can do with these values, whereas it can be quite difficult to reason about custom types/objects.
My point is, that knowing if `frobnicate(timeout=300)` is in seconds or minutes can be just as difficult (or even more difficult) as knowing what specific object I need to instantiate and pass to `frobnicate` (in the above case a `timedelta`)
In this specific example i disagree, timedelta is part of the standard library and should be widely known and familiar.
I disagree; to paraphrase Ian Malcolm: what you can do with these values is less important than what you should do with these values. For example, we can add a distance to a currency, if they're both int or float; that doesn't mean we should.
The most obvious example of this is "stringly-typed programming", where pretty much everything is "string". Can I append a user-input string to an SQL statement string? Sure; but I shouldn't. Can I append a UserInput to an SQLStatement? Not without conversion (i.e. escaping)!
But in your example above, typed Python would instruct your editor and tools like mypy to flag any improper use of frobnicate. You can set up your editor to offer you a tip on what type to use as soon as you type in `frobnicate(`.
In cases where typing is not really available, I prefer to put types into APIs instead of variable names (and Python makes that great: `frobnicate(duration_as_timedelta=timeout)`).
When possible, I also encourage the use of better types than simple integer values, (like TimeSpan if .NET) as these further reduce ambiguity and the potential for mistakes.
This is such a simple thing to find and fix but it definitely helps in the long term.
In a dynamic language, maybe.
In a static language, especially Haskell/Scala/Ocaml/F#, I hate duplicating the type.
Having everything work this way makes it so much easier to review code for errors. Without this means that as a reviewer you must either trust that the units and conversions are correct or you should do some spelunking to make sure that the inputs and outputs are all in the right units.
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.
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.
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.
Who knows. Maybe a billion dollar company that can't fulfill orders. Maybe a million people who suddenly can't use their bank online.
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.
>> 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?
I don't use libraries to enforce it though, we did try this but found it quite clunky: https://pint.readthedocs.io/en/stable/
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!
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.
I may be misunderstanding this.
You can't add seconds to kilometers, or to temperature, or to how blue something is.
The world is far, far from ideal.
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.
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.
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").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;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
Eg
func transferRegularly(dollars(10000), days(30))
Meaning clear. func transferRegularly(10000, 30)
Meaning obscure, error prone and potentially costlyEg. 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).
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.
Guess how I discovered this issue :)
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.
dollars(10000) is still better than this example, because: 10000 what? Pennies? USD? EUR?
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.
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.
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))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.
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.
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.
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 :)
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.
(although getDefaultTimeoutFromEnvironment was artistic license on my part)
Edit: Also, overriding a class method dynamically inside a function? I usually program python these days and even I think that's wild.
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. .setPricePerMassInCentsPerKilogramsWithTimeoutInMilliSeconds(100,2,300) .setPrice(priceInCents=100, massInKg=2, timeoutInMs=300) .setPriceInCents(100);
.setMassInKilograms(2);
.setTimeoutInMilliseconds(300);
or .calculate({
priceInCents = 100,
massInKilograms: 2,
timeoutInMilliseconds: 300,
}); 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)) 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.
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).
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.
> 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.)
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.
https://package.elm-lang.org/packages/ianmackenzie/elm-units...
Even if you don’t work in Elm take a moment to look at it.
Had one making me pull my hair put the other day in C#. C# datetimed are measured in increments of 100 nanoseconds elapsed since January 1st 1 AD or something like that. Was trying to convert Unix time in milliseconds to a C# datetime and didn't realize they were using different units. My fault for not reading the docs but having it in the name would have saved me a lot of trouble.
The factory method used to convert e.g. Unix timestamps to DateTimes, now that should indicate whether we're talking seconds or milliseconds since epoch, for example, and when the epoch really was.
.ToUnixTimeSeconds()
.ToUnixTimeMilliseconds()
DateTimeOffset.FromUnixTimeSeconds(Int64)
DateTimeOffset.FromUnixTimeMilliseconds(Int64)
https://docs.microsoft.com/en-us/dotnet/api/system.datetimeo...https://docs.microsoft.com/en-us/dotnet/api/system.datetimeo...
Much of the C# code I've seen uses names like start_date with no indication of whether it really is a date (with no timezone), a date (in one particular timezone), or a datetime where the time is significant.
I'm certainly not a C# developer, though my quick reading of the docs suggests that the DateOnly type was only introduced recently in .NET6.
It's really not any stranger than starting dates at 1 CE, or array indexes starting at 0.
Established doesn't mean it is understandable without documentation. Anyone who is not familiar with it doesn't know why it starts in 1970 and counts seconds. You need to actually open the documentation to know about that, and it's name (be it unix time, epoch, epoch time or whatever) doesn't help in understanding what it is and what unit it is using.
UNIX time is an easy international standard, everybody with computer experience knows what it is and how to work with it.
Thanks for the laugh.
The only ones who needs to know about unixtime is:
developers when they do something which takes it/produces it
*nix sysadmins
Everyone else with "computer experience" could live all their life without the need to know what unixtime is.
Bullshit.
I never needed to know what unixtime is when I wrote anything with sleep().
All I needed to know is how long in seconds I want the execution to pause for, never ever I needed to manually calculate something from/to unixtime, even when working with datetimes types.
Nobody is saying that the two things need to be connected, the point is that it can be name dropped in a type definition, and you would know what it means.
Windows uses the Gregorian Calendar as its epoch.
It is quite hard actually to disagree with the 100ns tick size that they did use. 1 microsecond may have also been reasonable as it would have provided a larger range but there are not many use cases for microsecond accurate times very far in the past or in the future. Similarly using 1 nanosecond may have increased the applicability to higher precision use cases but would have reduced the range to 100 years. Alternately, they could have used a 128 bit structure providing picosecond precision precision from big bang to solar system flame out with the resultant size/performance implications.
Many Languages
var lengthInFeet = 2;
var weightInKg = 2;
var sum = lengthInFeet + weightInKg; // Runs without issue but is an error
F# [<Measure>] type ft
[<Measure>] type kg
let lengthInFeet = 2<ft>
let weightInKg = 2<kg>
let sum = lengthInFeet + weightInKg // Compile time error
More info at https://fsharpforfunandprofit.com/posts/units-of-measure/Naming is an optimization problem: minimize identifier length while maximizing comprehension.
And you need to read the docs to know why some systems use 1970 as the reference point. Should we rename it to Unix1970datetimeepoch everywhere?
Yeah, you heard me Scala.
Why would your type system have encoded unit for kilo-pascal, but not hecto-pascal, mega-pascal, micro-pascal etc?
If you only encode base units (e.g. seconds), then we should use exact-precision arithmetic instead of f32 or f64, which is sometimes an overkill.
If encoding all the modulos (kilo/milli/mega etc) I feel like there are some units may have name clashes (e.g. "Gy" -- is it giga-years, or gray)?
Should we encode only SI units, or pounds/ounces/pints as well?
In my opinion this is not a real problem, since ideally no-one should such meaningless abbreviations in code. Just write giga_years or GigaYears or whatever your style is, problem solved, doesn't get any clearer than that.
"Stars are expected to form normally for 10^12 to 10^14 (1–100 trillion) years"
So it seems Gy and even Ty units will be a reasonable scale for events during the period of star formation.
Once we get to Gigayears, what is the size of single year? Just 365 days? Or which of Julian, Gregorian, Tropical, Sidereal? At even kilo prefix the differences do add up. Or would you need to specify it?
Days, weeks and months are also fun mess to think of.
(Calculations without associated uncertainty calculations are worse than worthless anyway - misleading due to the inherent trust we tend to put in numbers regardless of whether they are garbage.)
The appropriate system of units is context-dependent. The astronomical system, for instance, has Days of 86,400 SI seconds and Julian years of exactly 365.25 Days; if you have a general and extensible units library, then this isn't really a difficulty, you just need to make a choice based on requirements.
Does the type system do orientational analysis? If not you to assign a value of work to a value of torque and vice versa, as they both have the above unit.
There are several other similar gotchas with the SI. I think descriptive names are better than everyone attempting to implement an incomplete/broken type system.
The SI itself states[2]: "...For example, the quantity torque is the cross product of a position vector and a force vector. The SI unit is newton metre. Even though torque has the same dimension as energy (SI unit joule), the joule is never used for expressing torque."
[1]:https://docs.astropy.org/en/stable/units/index.html#module-a... [2]:https://www.bipm.org/documents/20126/41483022/SI-Brochure-9-...
from astropy import units as u
a = 3 * u.s
b = 2 * u.s
c = 1 * u.s
d = 4 * u.s
m = min([a, b, c, d])
a -= m
b -= m
c -= m
d -= m
print(a,b,c,d)
Output: 2.0 s 1.0 s 0.0 s 4.0 sNote the last 4.0, while min value is 1.0
The issue is that a, b, c, d are objects when astropy units are applied and min (or max) returns not the value but an object with the minimal value, thus m is c (in this particular case c has the smallest value) so c -= m makes m = 0, so d remains unchanged. It was very hard to spot especially when values change and occasionally either one of a, b, c or d has the smallest value.
In-place augmentation of a working code with units may be very tricky and can create unexpected bugs.
While it can sometimes be undefined behavior (a minimum of incompatible units), in cases like these it should DTRT.
You'd get the exact same behavior with numpy ndarrays (of which astropy Quantities are a subclass).
Unit-aware values as a type where assignment as mutation is an odd choice though (normal mutable types do not exhibit this behavior, it’s a whole separate behavior which has to be deliberately implemented.) It may make sense in the expected use case (and as you note reflects the behavior of the underlying type), but more generally it's not what someone wanting unit-aware values would probably expect.
https://www.boost.org/doc/libs/1_78_0/doc/html/boost_units/F...
tl;dr is uses some sort of pseudounits to make dimensionally similar but incompatible units, well, incompatible.
(Economics of floating vs fixed point chips might distort things though ?)
Also, in the case that you meant this : you might need fractions of even base units for internal calculations :
IIRC banking, which doesn't accept any level of uncertainty, and so uses exclusively fixed precision, uses tens of cents rather than cents as a base unit ?
It can convert between equivalent units (e.g., centimeters and kilometers), and will complain if you try to add quantities that aren't commensurate (e.g., grams and seconds).
The nice thing about this is that you can write functions that expect unit-ful quantities, and all the conversions will be done automatically for you. And if someone passes an incorrect unit, the system will automatically spit out an error.
But types are not just useful to specify the content of a variable, they are also useful to specify the required precision.
So, if there is a type for seconds in the type system, should it be a 32 bits int or a 64 bits float? Only the user can say.
type DurationSeconds<Value> where Value: Numeric { ... }
DurationSeconds<UInt32>
DurationSeconds<Float64>
Have none of you ever refactored code..? Or all of your writing C?
Your library should just expose an interface/protocol signature. Program to interfaces. Anything that is passed in should just implement the protocol. The sleep function should not be aware or care about the input type AT ALL. All it requires is the input to implement an "as-milliseconds()" function that returns a millisecond value. You can then change any internal representation as your requirements change
You seem to ignore the much broader context here: the article wasn't just about code. It included configuration files and HTTP requests.
It's also worth noting that depending on the language in question and the usage pattern of the function/method, using interfaces or protocols can cause considerable overhead when simply using a proper descriptive name is free.
That's an argument against languages with type-systems that make this a PITA, not against the idea itself.
A.k.a. custom type!
If you replace 'time delta' with 'strings' then the problem becomes more apparent. Each library defining its own string type would be a mess.
(extend-protocol
libA/stringable
myLib/InputThing
as-string [x] (myLib/to-string x) )
(libA/some-func (myLib/make-a-thing))
And sure it can just be doing something as simple as returning an internal value directly or calling some common stringifying method. You do have a good point that you may have redundant stringifying protocols across libraries - which sucks.> This will explode very quickly into lots of boilerplate code and is a good reason to use 'primitive types' in interfaces.
I feel you were so close and missed :) The natural conclusion would be to have primitive interfaces - not primitive types. This way libraries only need to agree to adhere to an interface (and not an implementation)
I think the practical problem stems from widespread APIs which are not communicating their units, and that's what we should be fixing instead: if APIs are clearer (and also self-documenting more), the risks you talk of rarely exist other than in badly structured code.
Basically, instead of having `sleep(wait_in_seconds)` one should have `sleep_for_seconds(wait_time)` or even `sleep(duration_in_seconds=wait_time)` if your language allows that.
But certainly use of proper semantic types would be a net win, but they usually lose out in the convenience of typing them out (and sometimes constructing them if they don't already exist in your language).
(I settled on units in variable names instead, was essential when some inputs were literally in different units of the same physical dimension.)
EDIT : more on this, and on astropy (which I was not aware of and/or didn't exist back then) :
PIXELS_PER_INCH or BITS_PER_LITER rather than SCREEN_SCALE_FACTOR and VOLUME_RESOLUTION, avoids all kinds of mistakes like inverting ratios etc.
time.Sleep(1 * time.Second)But the value of time.Second is actually a Duration with value 1000000, IIRC -- it's microseconds. It's just the type that's special, and the int handling here is general over a lot of types.
It really is nice in practice.
time.Sleep(time.Second)
but this reads nicely time.Sleep(3 * time.Minute) 2*time.Hour+1*time.second == time.Second+time.Hour*22 * 3 * time.Second is the same whether you group 2 * (3 * time.Second) or (2 * 3) * time.Second (namely, the implicit grouping under left-associativity).
You wouldn't normally write time.Sleep(time.Second * time.Second) because your units wouldn't work out. (Apparently you can write that in Golang; it's just very sketchy and results in a 30-year sleep.)
I'm just not seeing any major downsides of this, keep in mind `time.Second` isn't the only one of its kind, you have millisecond, minute, hour, etc etc.
There is a Duration::new() constructor that's more ambiguous, but it's your choice as a dev to be ambiguous in this instance, and code review should probably catch that.
sleep(5.seconds)
sleep(1.minute)
sleep(2.hours)
etc etc sleep 3.seconds
Hard to to be more concise than that (Time.now + 1.month).to_i == Time.now.to_i + 1.month.to_i
#=> falseThough it does seem pretty easy for a novice to do thinking it's the same, but what does 1.month.to_i even mean!?
Duration of a month in seconds? Before you balk at the idea, there exists a definition of a constant month duration for accounting stuff. I you hate dates - and yourself - try accounting, there's mind boggling stuff that makes the engineer mind recoil in absolute terror.
The expression on the left hand side advances time (as a domain object) by exactly a month, then converts the result to integer unix time. The expression on the right adds 2629746¹ to the current unix time.
The conversion becomes dangerously magical in the presence of shared code that accepts both object and integer representations of time & duration. A consumer from one part of a system can inadvertently obtain different results to another unless they use identical calling conventions.
[1] this is 1/12 of the mean length of a gregorian year²
[2] 365.2425 days i.e. 31,556,952 seconds
sleep 3int64 * Duration → Duration and Duration * int64 → Duration both make sense, but I gather this only works with constants. For other values, I believe Go only gives you Duration * Duration → Duration which is just wrong, wrong, wrong, requiring that one of the two “durations” actually be treated as though unitless, despite being declared as nanoseconds.
In the end, it’s probably still worth it, but it’s a case of Go trying to design in a certain way for ergonomics despite lacking the type system required to do it properly. I have found this to be a very common theme in Go. Also that it’s often still worth it, for they’ve generally chosen their compromises quite well. But I personally don’t like Go very much.
In my opinion, it is well designed. First of all, who is multiplying time.Duration against itself? I've been programming Go for a few years basically every day, and I've only ever seen the package constants used by themselves, or with untyped constant. I think it's a great syntax, better than any example in the article, as you don't have mystery numbers.
Go is currently allowing that, which makes `delaySecs * time.Second` a billion times larger than it appears to intend. I've personally run across code that has this kind of flaw in it... at least several dozen times. It's the kind of thing that's only noticed when it misbehaves visibly while someone is watching it.
(I read a lot of other-teams' code, which is in various states of quality and disarray)
What you're suggesting would be like a compiler error for multiplying two int64s
1 second * 1 second = 1 second²
1 meter * 1 meter = 1 meter²
1 meter / 1 second = 1 m/s
Those are not user errors, those are physical values. A physical value is two things: - a scalar (int64, float, ...)
- a unit (meter, second, inches, ...)
If the type system of your programming language does not allow you to define units, this should at least be a structure with a scalar and an enum, and functions to cast from one unit to another (if possible).Working with units is a common thing in science.
I would argue it is actually three things: a scalar, a unit, and an indication of error – which is at least another scalar, but there are multiple ways of expressing error, so it might require more than just a single scalar (such as an interval and the probability the actual value lies within that interval.)
> If the type system of your programming language does not allow you to define units, this should at least be a structure with a scalar and an enum
Ideally more than just an enum – Newton = kg*m*s^-2 (equivalently kg^1*m^1*s^-2) – which suggests a set of pairs (unit and exponent).
And it's especially true for time units.
For example, "how many seconds is one month?" does not make sense, but "how many seconds is january/february/march?" does make sense. The unit "month" does not really exist, each calendar month is its own unit.
And "february" is not even a "stable" unit because sometimes it's 28 days, sometimes it's 29 days. Even a minute can some rare times be 61 seconds.
This is why in physics, we use seconds multiplied by powers of 10 and nothing else.
To my knowledge, there is not a single programming language that differentiate a "scalar" and a "quantity" (scalar, unit, error).
The variables used for accepting and parsing input are the ones that should have units in them in this example. Although if you need a delay specified, it's valuable to be explicit and robust in the input and accept a string time.ParseDuration understands. Then you don't have this units problem in your variable naming at all, allows easier input of wider ranges of values by the operator, and makes input validation (if only a subset of durations are allowed) more concise and consistent.
Time was honestly our biggest source of bugs by far. Although adding time.Time ended up being more problematic than durations which were mostly only constructed like that in tests
C++ chrono::duration allows arithmetic operations with more sensible overloading. https://en.cppreference.com/w/cpp/chrono/duration
As for languages doing it better, approximately every single language that has strong static typing and uses dedicated types for times does it better. Rust is the one I’m most familiar with and comfortable with.
But Duration(1) is way different than time.Second. honestly it just sounds like you don't know the language, and aren't willing to learn it. Go is not Rust. Things are different, that doesn't mean Go sucks.
hello := 2
hello * time.Second // oh no
But people actually use code like this: hello := time.Second
hello *=2
People working with Go code (who know what they're doing), don't declare an int, only to immediately cast it to something else.This is also pretty typical of the trade-offs Go makes: it focuses on making things nice for the application writer, mostly pretty successfully, but at the regular cost of pain and with serious typing compromises for the library writer.
F#, Rust, C++?..
> First of all, who is multiplying time.Duration against itself
Physicists do, every time they have to deal with acceleration - m/s^2.
Every implementation of units is secretly trying to be Moment.js, basically.
https://docs.microsoft.com/en-us/dotnet/fsharp/language-refe...
This can also be pulled off with somewhat less pleasant syntax on top of a sufficiently flexible parametrized type system - e.g. C++ templates.
In reality most programming languages do not have units what so ever (built into the language, maybe tacked on as a library after the fact). They have int64s, a unitless value that just keeps track of whole numbers of whatever it semantically means to the developer. If we want to truly have units in values then we either need 1st class language support (including syntactical support) or a rich library that doesnt just "put units in [symbols]". One could probably make it happen with a type that keeps track of units
```
type unitedVal struct {
denomerator int64
numerator int64
denomUnits string
numerUnits string
}
func (united *unitedVal) Multiply(by unitedVal) *unitedVal {
return &unitedVal{
numerator: united.numerator*by.numerator,
denominator: united.denominator*by.denominator,
denomUnits: united.denomUnits + " * " + by.denomUnits,
numerUnits: united.numerUnits + " * " + by.numerUnits,
}
}
```
and then filling out for all the other operations you want to support. delaySecs := 1 * time.Second
time.Sleep(delaySecs * time.Second)
Now I insist on using the durationcheck lint to guard against this (https://github.com/charithe/durationcheck). It found a flaw in some exponential-backoff code I had refactored but couldn’t easily fully test that looked right but was wrong, and now I don’t think Go’s approach is reasonable anymore. time.Second * time.Second
The type of this is `time.Duration` (or int64 internally), not `time.Second` (which is a const with a value).I agree, though, that this is not quite sound, because it can be misused, as shown above with `time.Sleep(delaySecs * time.Second)`.
In Kotlin you can do `1.seconds + 1.minutes` but not `1.seconds * 1.minutes` (compilation error), which I quite like. Here is a playground link: https://pl.kotl.in/YZLu97AY8
const (
Nanosecond Duration = 1
Microsecond = 1000 * Nanosecond
Millisecond = 1000 * Microsecond
Second = 1000 * Millisecond
Minute = 60 * Second
Hour = 60 * Minute
)I know how to implement that in Haskell, and that it can be implemented in C++ and Rust. I know how to logically implement that in Java or Typescript, but usability will suck (no infix operators).
For a good example of what it looks like when somebody does bother to do it, see F# units of measure.
Which is wrong, 1s * 1s = 1s².
For example, the force of gravity is expressed in m/s² and describe an acceleration (m/s / s, aka a change of velocity per time units, where velocity is a change of distance per time units).
But assuming your comment is not a joke. You probably want to convert minutes to seconds in order to work with the same units, then add the scalar parts together.
That's how you deal with different quantities: convert to same unit, add values.
This is analog to fractions: 1/2 + 1/4 = 2/4 + 1/4 = (2+1)/4 = 3/4.
[1] - https://en.wikipedia.org/wiki/Leap_secondEDIT: Yes, you multiply the units `2m * 2s` : you first multiply the units to get: `m.s`. This is what I say: you convert everything to the same units before doing the calculations.
> Multiplying by the same unit is semantically equivalent to “x times 1 is identity(x)”
This is wrong.
1kg * 1kg = 1kg² period.
What you're saying is `2kg * 1 = 2kg`, which is right, because `1` is a scalar while `2kg` is a quantity. This is completely different than multiplying 2 quantities.
> It would not imply I’m multiplying the units, but rather the scalar value of the unit.
That's where you're wrong. When doing arithmetic on quantities, you have 2 equations:
x = 2kg * 4s
unit(x) = kg * s = kg.s
scalar(x) = 2 * 4 = 8
x = 8 kg.s
Or x = 5m / 2s
x = (5/2) m/s
x = 2.5 m/s
There is a meaning to units and the operation you do with them. `5m / 2s` is 5 meters in 2 seconds, which is the speed `2.5 m/s`.`2m + 1s` has no meaning, therefore you can't do anything with the scalar values, and the result remains `2m + 1s`, not `3 (m+s)`.
Units can be expressed in terms of other units, and you can arbitrarily pick one unit as a base and then express the rest in it. But the key word here is "arbitrarily".
If multiplying by the same unit yield the same unit, then how did you compute area or volume in school?
[1] would that be unitful?
You cannot have a unit on its own without a scalar value. It makes no sense.
- 1 is unitless
- 1 * m casts the value to a value 1 of unit m = 1m
- 1 * m * m casts the value 1 * m = 1m to 1m then casts 1m to m which = 1m
Admittedly my educational background here might be wildly unconventional but it certainly prepared me for interoperable unit types as a concept without changing values (~precision considerations).
And the syntax is `3<unit>` not `3 * unit`
- 1 is a scalar - 1m is a quantity - 2 * 1m "casts" 2 to a meter, but really this is just multiplying a quantity by a scalar - 2 * 1m * 1m "casts" 2 to meter², multiplying 2 quantities then by a scalar
I insist, `1 * m` does not make sense. This is not a valid mathematical expression, because a unit can never be on its own without a value.
> expression of a unit without a value is (or should be to my mind, based on my education) a cast
There is no casting in math. Mainly because there is no types, only objects with operations. A vector is not a scalar and you can't cast it into a scalar.
A quantity is not a scalar either, and you can't cast one into another.
A quantity is an object, you can multiply 2 quantities together, but you can't add them if they are different. You can multiply a quantity to a scalar, but you still can't add a scalar to a quantity.
Well, yeah, F# represents this at the type level. Which I’ve said elsewhere in the discussion is preferable. Not knowing Go, but knowing it only recently gained generics, I read multiplying by `time.Seconds` (which does not have a visible 1 associated with it) as perhaps performing an operator-overloaded type cast to a value/type with the Seconds unit assigned to it. I’ve since learned that Go also does not support operator overloading, so I now know that wouldn’t be the case. But had that been the case, it isn’t inconceivable that unitlessValue * valuelessUnit * valuelessUnit = unitlessValue * valuelessUnit. Because…
> I insist, `1 * m` does not make sense. This is not a valid mathematical expression, because a unit can never be on its own without a value.
Well, if you insist! But you seem to be imposing “mathematical expression” on an expression space where that’s already not the case? Whatever you may think of operator overloading, it is a thing that exists and it is a thing that “makes sense” to people using it idiomatically.
Even in languages without overloading, expressions which look like maths don’t necessarily have a corresponding mathematical representation. An equals infix operator in maths is a statement, establishing an immutable fact. Some languages like Erlang honor this, many (most? I strongly suspect most) don’t! I couldn’t guess without researching it also treat infix = statements as an expression which evaluated to a value.
The syntax of infix operators is generally inspired by mathematical notation, but it’s hardly beholden to that. The syntax of programming languages generally is not beholden to mathematical notation. Reacting as if it’s impossibly absurd that someone might read 1 * time.Seconds * time.Seconds as anything other than 1 * 1s * 1s is just snobbery.
Not knowing Go, I focused on the syntax and the explicit values, and tried to build a syntax tree on top of it. I’m not a fan of infix operators, and I am a fan of lisps, so my mental syntax model was (* (* 1 time.Seconds) time.Seconds)), which still doesn’t “make sense” mathematically, but it can make sense if `*` is a polymorphic function which accepts unquantified units.
This sums up your incomprehension. `time.Seconds` is just a constant. An integer with the value `1_000_000` meaning 1 million of nanoseconds.
In an expression of the form `a * b` you should always read `a` and `b` as constants. This is true for EVERY programming language.
> it isn’t inconceivable that unitlessValue * valuelessUnit * valuelessUnit = unitlessValue * valuelessUnit.
It is. For example, what would be the meaning of this:
struct Foo {
// ...
}
2 * Foo
Valueless unit (or any type) is just not a thing, not in math, not in any programming language.> But you seem to be imposing “mathematical expression” on an expression space where that’s already not the case? Whatever you may think of operator overloading, it is a thing that exists and it is a thing that “makes sense” to people using it idiomatically.
Operator overloading works on typed values, not "valueless" types. In some programming languages (like Python), class are values too, but why implement `a * MyClass` when you can write `MyClass(a)` which is 100% clearer on the intent?
Using operator overloading for types to implement casting is just black magic.
> expressions which look like maths don’t necessarily have a corresponding mathematical representation
Programming languages and the whole field of Computer Science is a branch of mathematics. They are not a natural language like english or german. They are an extension of maths.
> An equals infix operator in maths is a statement, establishing an immutable fact.
An operator only has meaning within the theory you use it.
For example:
`Matrix_A * Matrix_B` is not the same `*` as `Number_A * Number_B`
`1 + 2` is not the same `+` as `1 + 2 + 3 + ...`
`a = 3` in a math theorem is ont the same `=` as `a = 3` in a programming language (and that depends on the programming language)
As long as the theory defines the operators and the rules on how to use them, it does not matter which symbol you use. I can write a language where you have `<-` instead of `=`, and the mathematical rules (precedence, associativity, commutativity, ...) will be the same.> Reacting as if it’s impossibly absurd that someone might read 1 * time.Seconds * time.Seconds as anything other than 1 * 1s * 1s is just snobbery.
First, that's not what I said. You should read that as `scalar * constant * constant` because reading that as `scalar * unit * unit` does not make sense nor in math, nor in any programming language.
If caring about readability and consistency is snobbery, then so be it.
> Not knowing Go, I focused on the syntax and the explicit values, and tried to build a syntax tree on top of it.
And the syntax is pretty explicit, because it's the same as math or any programming language: `scalar * constant * constant`. This is why using math as a point of reference is useful, you can easily make sense of what you're reading, no matter the syntax.
> I am a fan of lisps, so my mental syntax model was (* (* 1 time.Seconds) time.Seconds))
I still read this as `(* (* scalar constant) constant))`. And I expect your compiler/interpreter to throw an error if `time.Seconds` is anything without a clear value to evaluate the expression properly.
And I would expect to read `(* (* 1 (seconds 1) (seconds 1)))` as `scalar * quantity * quantity`, and I would expect to get square seconds as an output.
Anything else would not be correct and have little to no use.
Let's say that you want to convert `2 min` into seconds. You know that `1 min = 60 s` is true. Dividing this equation by `1 min` on both sides is allowed and brings `1 = (60 s) / (1 min)`. This shows that if we multiply any value in minutes by `(60 s) / (1 min)`, we are not actually changing the value, because this is equivalent to multiplying it by 1. Therefore, `2 min = 2 min * 1 = 2 min * (60 s) / (1 min) = 2 * 60 s * (1 min) / (1 min) = 120 s`. We didn't change the value because we multiplied it by 1, and we didn't change its dimensionality ("type") because we multiplied it by a dimensionless number. We just moved around a dimensionless factor of 60, from the unit to the numerical value.
I think that you misremember, or didn't realize that to convert minutes into seconds, you were not multiplying by `60 s` but by `(60 s) / (1 min)` which is nothing else than 1.
def sleep(num : Time::Span)
# do something here
end
I would call it like: sleep 300.seconds Future.delayed(const Duration(seconds: 2)
Future.delayed(const Duration(milliseconds: 2000)https://pkg.go.dev/time#hdr-Monotonic_Clocks
> RRDNS is written in Go and uses Go’s time.Now() function to get the time. Unfortunately, this function does not guarantee monotonicity. Go currently doesn’t offer a monotonic time source (see issue 12914 for discussion).
https://blog.cloudflare.com/how-and-why-the-leap-second-affe...
> time: use monotonic clock to measure elapsed time
# Session inactivity, in seconds
time.sleep(300)
# Prevent pileup of unprocessable requests, in seconds
request_timeout = 10 # Sleeps before continuing
time.sleep(…)
# Time before request timeout
timeout = …time.sleep(300)
Put your units in the method name:
time.sleep_seconds(300)
Likewise, if you're making a .length() method where the units are at all ambiguous (like the length of a string), name your units. Bad: str.len(). Good: str.len_chars() / str.len_utf8_bytes(). (I'm looking at you, Rust!)
typedef int seconds;
and time.sleep(seconds duration);When programmers get answers to these questions wrong, the code that they write ends up being broken for someone out there. And they do get it wrong if their native culture instills a wrong kind of "common sense" about scripts. Which is precisely why we need more stuff like str.len_utf8_bytes() - because it forces the person writing it to consider their assumptions.
I’ve spent the last decade writing javascript and I’ve never once actually cared to know what half the UTF16 byte length of a string is.
The only legitimate uses are internal in javascript (since other parts of JS make that quantity meaningful). Like using it in slice() or iterating - though for the latter we now have Unicode string iteration anyway.
I don't know these, someone who does could properly tell you.
The implementation could fallback to "glyph" or "codepoint" (don't know what those are exactly) if it is unsure. Mostly right is better than nearly always wrong (= returning number of bytes) IMHO.
> How about "ß"?
That's one character.
> When programmers get answers to these questions wrong, the code that they write ends up being broken for someone out there.
So? Returning the number of bytes would also be wrong.
Renaming len to len_glyphs will just result in most programmers typing more and some accidentally using len_utf8_bytes (returns the number of bytes?) where len_glyphs would be less wrong.
poll_file_descriptors(read_descriptors, write_desciptors, timeout_in_seconds)
it would be awkward to change the name of the function just because on of the arguments happens to refer to time.The point the article is making is not about making it easier to write a line of code, but about making it easier to read a line of code. Given that most lines of code are read many more times than they are written, this is a good thing to focus on.
"Programs must be written for people to read, and only incidentally for machines to execute."
― Abel and Sussman, Structure and Interpretation of Computer Programs, 1984
Putting the units in the method name (when you can) fixes all of this. Sleep_milliseconds(5) is impossible to misuse or leave undocumented.
The operator's requested speed was input in Feet Per Minute. The output to a Variable Frequency Drive was in tenths of Hertz. The tachometer feedback was in RPM, and to top it off all the internal calculations were done in Radians-Per-Second.
The first thing I did to get the project back on track was to adopt a standardized variable naming convention that included the units. For example the Operator Request became operator_request_fpm_u16. You then knew immediately you were dealing with Feet Per Minutes, and that it was a 16 bit unsigned variable.
After the variable name cleanup many of the bugs became self documented, when you saw something like "operator_request_fpm_u16 / vfd_hz_s32" in the code, you knew there was a problem that needed to be fixed...
My take is that Hungarian notation exists to work around a deficiency in tooling. I think this is clearer when encoding e.g. u16 into the identifier, since that information is redundant (the declaration or schema already encodes that it is u16).
> Frink is a practical calculating tool and programming language designed to make physical calculations simple, to help ensure that answers come out right, and to make a tool that's really useful in the real world. It tracks units of measure (feet, meters, kilograms, watts, etc.) through all calculations..
I use Frink very regularly as a calculator. I've got a keybinding in emacs to bring it up in comint-mode, which works very well.
It's also a general-purpose programming language, at least in theory. I actually tried using it for that purpose once, with I think a few thousand lines of Frink code in total. It was not a pleasant experience. It's fine if you want to write a short script that's dimensionally aware, but for modelling of a complex physical system there are much better tools, such as Modelica.
Then, somebody asks me to code in the temperature of a system. And I have to think: "Is now really the time that I want to teach people the difference a kelvins and celsius?"
So my rule becomes, SI "except" temperature. Sigh...
I assume you always just use the base units? kg, m, s, etc.? (I always think it odd that kilogram is the base.) I feel like could get weighty for some applications of a different scales when milligrams, millimeters, kilometers, days, etc. could be clearer. And even if you use "standard" units, if you aren't clear about what standard you use and what that makes that units, people won't always guess the correct option.
The other issue is when you get to Candelas!
Not blaming anyone who does not know it, but I would argue for more and better science education ..
Haven't come across temperature however we would probably stick with kelvin.
We use a strict set of units in databases and while processing, conversions are localized if necessary only at the view layer.
We also only use UTC for date/times.
We only use E164 format (without spaces etc) for phone numbers: e.g. +12345678901 for an example number in OH, US. see National format https://libphonenumber.appspot.com/phonenumberparser?number=...
We only use iso3166-1 country codes and iso3166-2 region codes and translate on view.
From a hardware perspective it makes sense to use K because you can encode the image directly using unsigned numbers plus some gain to allow for fractional measurements.
If you do, be explicit about it either in parameter or function name. I'm not going to put you on my shitlist if you're naming your function `microsleep`, but if I have to go look into implementation to see that you count timeout on your database in microseconds (looking at you, couchbase, like you ever could return something from a larger dataset in microseconds, lol) or, even worse, cache expiry time in minutes (hello unknown developer), I am going to go on the internet and complain about you.
- avoiding naming things if you can help it
- using tooling to autogenerate names
- avoiding too short, likely overloaded names like `id`, `name`, and `url`
- don't choose lazy pluralization - eg instead of `names/name`, use `nameList/nameItem`
- encoding types to make Wrong Code Look Wrong, a famous Spolsky opinion (lite hungarian notation)
- coming up with grammars for naming, eg React had an exercise to name its lifecycles combinations of THING-VERB-ACTION, like `componentDidMount`, before open sourcing, which helped learnability
pulled from my collection of Naming Opinions here: https://www.swyx.io/how-to-name-things
Isn't this just extra noise? If the type of the variable is an Array wouldn't `nameArray` be superfluous? Worse still is if the type changes but the name stays the same.
I get the advice is probably Javascript specific, but even in a Typescript world it doesn't make much sense to me to do this kind of type-in-name encoding.
But this has bitten me in Ruby, JavaScript and PHP several times. Runtime errors and downtime. Most recent: autocompled some updatedCartsItems when it had to be UpdatedCartItems. Both were used in the same class. Had they be named sensible, like CartListWithUpdatedItems and UpdatedItemList or something better, I'd have saved myself hours of WTFing through CI logs.
In a small enough context, no way :)
> don't choose lazy pluralization - eg instead of `names/name`, use `nameList/nameItem`
This just seems redundant and is a personal annoyance. Is plural meaning list or sequence not widely understood enough?
Unfortunately "Theory of Mind" is weak in people on the spectrum.
That said, "percent" is a common and precise word, and I haven't come up with anything quite as good for variables in range [0,1]. I generally use "ratio," but I don't love the word. Is there anything better?
(Another name for the "normalized" unit is sometimes the "unit" unit. ProgressUnit sounds dumb, but is an available option in English and shorter than ProgressNormalized.)
Documentation should always be secondary to an obvious, descriptive interface. We've evolved beyond register positions and phonebook-style paper documentation. Use the tools available to you.
void addPadding(int height) {
}
Types are useful, and even as a Python programmer I gravitate towards type hints for all new code, but any application where a programmatic type maps to a real-world type with common conversions (like, say, pixels, em, en, millimetres, centimetres, or inches in the above example) tends to be a victim of the same issue, where the type system isn't expressive enough to clearly describe the real-world type being assumed by the function.I also haven't come across a thorough implementation of unit conversions to do stuff like this (not that it's not a pattern that works -- I personally like this); it might be common in domains where dealing with real units is central to the business, but in industries where that's done incidentally, convenience classes like this just aren't around (in my experience).
setSpeedInKilometersPerSecond vs. setSpeed
I'd rather have it baked into the language ala CSS ("100ms").
In addition: it's the wrong solution to the problem. The units shouldn't be baked in to the function definition, just the type of quantity. You should be able to do both:
setSpeed(10 m/s)
and setSpeed(45 km/h)
Which you can do in many languages. In fact, time functions in C++ work exactly like this. If you want to suspend a thread for 10 seconds you do std::this_thread::sleep_for(10s);
but if you want to suspend it for 5 milliseconds, you do std::this_thread::sleep_for(5ms);
And if you just supply a unitless number, it's a compiler error.A prominent example is PEP8 in Python, which suggests a line length limit of 79 characters (though 80-100 chars are considered to be "OK" as well). Long variable or function names can lead to distracting "forced" line breaks in such scenarios.
But more important: there's middleground. What about setSpeedMmps() if setSpeedInMillimeterPerSecond is too noisy.
My ROT is that the unit or type designation schould not overshout the most important info. Which, in case of setSpeedInMillimeterPerSecond is arguably, indeed the case. But the solution is almost never binary, but a more succint version. Everyone understands km, mm, sec, hr (though the win with such is silly) px and so on.
Mmps would be confusing and frustrating the first time I think.
https://www.boost.org/doc/libs/1_78_0/doc/html/boost_units.h...
FWIW, in "TimeSpan for the .NET crowd", you would write "00:00:50" for (zero hours, zero minutes and) fifty seconds. Hours, minutes and seconds cases are easy now that we know the format.
Yes, you can omit some of the zeros, but your comment above makes the case that for clarity, you should not.
But in that case, and especially in that case, in any system that might interact with, say, a UI where a field is in decimal USD, Stripe needs to be careful about which things are price_decimal and price_zerodecimal. Unless you have a near-religious fervor that all variables not annotated with _decimal are assumed to be _zerodecimal, in such a situation one might go so far as to auto-reject any PR that does not suffix all variables explicitly. Because the alternative is hard-to-detect 100x-off bugs that occur when battle-tested systems/libraries are reused in different contexts.
Most currencies do not have "Cent" as a base unit. And there are currencies without a smaller base unit, most notably japanese Yen.
The problem is, that there exists no established currency neutral name to distinguish between the two possible units that coincide in such cases as Yen.
I was thinking about the following:
class AmountOfMoney
property int FinerAmount
property decimal CoarserAmount
In the case of Yen (FinerAmount == CoarserAmount) is always true.Any suggestions for better wordings?
class AmountOfMoney
int mantissa
int exponent # base 10If we have for example USD 10.42, the values in my implementation are:
FinerAmount = 1042
CoarserAmount = 10.42
The profile of the class was abbreviated. Of course, we also need a currency property for the general case: Currency = USDollar
The definition of the class for the currency in pseudo-code: class Iso4217CurrencyCode
int NumericCode
string AlphabeticCode
int DecimalPlaces
static USDollar = new Iso4217CurrencyCode(840, "USD", 2);
static Yen = new Iso4217CurrencyCode(392, "JPY", 0);
The constructor for the amount of money only uses FinerAmount, and CoarserAmount is calculated: CoarserAmount => Convert.ToDecimal(FinerAmount / Math.Pow(10, Currency.DecimalPlaces));
So foo = AmountOfMoney(FinerAmount: 1042, Currency: USDollar);
sets foo.CoarserAmount automatically to 10.42.But
bar = AmountOfMoney(FinerAmount: 1042, Currency: Yen);
sets bar.CoarserAmount automatically to 1042. def my_sleep(*, seconds: int):
pass
my_sleep(seconds=3)
This will force those who use your function to use the parameter name. A sort of documentation I suppose. std::thread::sleep(Duration::from_millis(300)); delay 0.3;
Or with package Ada.Real_Time: delay To_Duration (Milliseconds (300));
Or use `delay until`: delay until Clock + Milliseconds (300);
`delay until` is useful in loops because `delay` sleeps at least the given duration, so you get drift. (You call Clock only once and store it in a variable before the loop and then update it adding the time span each iteration) std::this_thread::sleep_until(std::chrono::system_clock::now() + 300ms)
That's true for all functions that take timeouts (At least since C++11).edit: s/thread/this_thread/
However, in C++ std::thread is a class and it does not have a static member function sleep_until. (However, std::this_thread, which is a namespace, does have such a function).
* https://docs.oracle.com/javase/8/docs/api/java/time/Duration... * https://docs.microsoft.com/en-us/dotnet/api/system.timespan?... * https://en.cppreference.com/w/cpp/chrono/duration
If you're putting something in a config file, as the blog says - always put the unit in the key name.
You can set ones to ignore, a minimum value for the rule to apply, or require the variable to be a const.
int length = 5
Is quite different than:
int lenght_in_meters = 5
For instance 7, 24, 60, 1000 allowed in defining units of time, and any other intervals are defined as 5 minutes = 5 x 60 x 1000.
Still, I've had plenty of experiences with 'is this unit in seconds or milliseconds'. As I recall, Gilad Bracha at one point looked at attaching units to numbers but I think he got wrapped around the axle on automatic conversions - if you divide meters by seconds, this is a meters/second unit. But do you convert to newtons or joules automatically too?
http://catb.org/jargon/html/M/magic-number.html
https://en.wikipedia.org/wiki/Magic_number_(programming)
delay_ms = 300;
[...]
Thread.sleep(delay_ms);
Works in any programming language. delay_seconds = 300;
[...]
Thread.sleep(delay_seconds);
This kind of bug can easily surface if you need the constant for calls taking different units and can be hard to spot. using namespace std::chrono_literals;
auto lesson = 45min;
auto day = 24h;
std::cout << "one lesson is " << lesson.count() << " minutes\n"
<< "one day is " << day.count() << " hours\n";
and you can compare durations specified with different units etc. There mpusz/units library, which may go into the standard at some point, lets you do this: using namespace units::isq::si::references;
// simple numeric operations
static_assert(10 * km / 2 == 5 * km);
// unit conversions
static_assert(1 * h == 3600 * s);
static_assert(1 * km + 1 * m == 1001 * m);
and also write conceptified functions which "do the right thing", e.g.: constexpr Speed auto avg_speed(Length auto d, Time auto t)
{
return d / t;
}
this will normalize appropriately. But - the specific units used will need to be known at compile-time. Choosing units at run-time is a different kettle of fish.Some people complain that it involves too much typing or takes up too much space. In reality, we spend much more time reading code than we do writing it, so names that provide context, direction, and fore-shadowing are really useful.
I still tend to write method names and important variable names like that to this day in pretty much any language I use. IMHO, its a great hack.
An extreme example is in the NSBitmapImageRep class [1]
[0]: https://www.cocoawithlove.com/2009/06/method-names-in-object...
[1]: https://developer.apple.com/documentation/appkit/nsbitmapima...
> request_timeout = 10
> Accept one of these instead:
> request_timeout = 10s
> request_timeout_seconds = 10
What does ”s” imply? Can I write “10m” for 10 minutes, or is that 10 months? Non-standardized syntax is dangerous.
For config files, I use RFC 3339 duration syntax; i.e. “PT5M” for five minutes. It was the most standardized syntax for semi-human readable time periods which I could find.
`s` is actually one of the SI base units: https://en.wikipedia.org/wiki/International_System_of_Units#...
edit: actually, month should never be used for the case described anyway... 28-31 days?
Funny, I would interpret a month as 30 days (since the lunar cycle is slightly over 29.5 days).
On JSON, I always do { unit:XXXX, value:XXXX }, it is quite verbose but it does help a lot when you least expect it.
I also wrote a small utility that transforms between values like { unit:'m', value:5 } to { unit:'km', value:0.005 } so that makes it super easy for me to pipe stuff from one context to another when is needed.
As I now realize, it could be quite useful for others.
The java.time API goes in the same direction, but is obviously limited to things around time.
I think units should be really expressed with the type system, because types give meaning _and_ safety. If used APIs require typed units you wouldn't even need a coding convention to put the unit in a variable name.
Types like e.g. Duration (for e.g. sleep), Instance (for calculating time passed based on monotonic timestamps), Distance etc.
Through at the same time in static typed languages being generic over the unit is often unnecessarily and hinders productivity (e.g. Duration<TimeUnit> with types Duration<Seconds>, Duration<Hours>) similar having unit types (e.g. passing instances of Seconds, Hours to sleep) is also often not necessary and more harmful then good. (Exceptions exists, where you e.g. need to have where high precision and range while at the same time need to keep storage constraints as small as possible while also juggling units, like some scientific or embedded applications).
It also doesn't make a unit error stick out, as you have to take the time to specifically hover to check. What I mean by this is consider you've opened a mature code base and are browsing around, and scroll past:
timeout = 60000;
I'd assume this is milliseconds, and whether I check would depend on what I'm doing and probably also my mood.Whereas if I see:
timeoutSeconds = 60000;
It'll draw my attention and no matter what I'm doing I'll either open a bug or just fix it.Without this small info, you have to grep the docs or worse, grep the source code itself. There's nothing wrong with looking at the source code but you shouldn't have to if you just want to use the public interface.
Pass around types encoding certain quantities. You do not want a Thread to "sleep for x units", but rather "sleep for this specific Duration", therefore pass around Durations and implement appropriate utilities `.toSeconds(Duration d)`, `.fromTime(Time t1, Time t2)`. The very moment your `.frobnicate(int time_in_seconds)` gets wrapped in `foobar(int duration)` all meaning is lost and you have no control over it.
Type systems are there to encode meaning (sometimes including possible values) behind a value - use it. And if you use highly dynamic prototyping language in production... Well, inability to encode and enforce meaning behind a value is part of the compromise.
> Option 2: use strong types, An alternative to putting the unit in the name, is to use stronger types than integers or floats. For example, we might use a duration type
What are you doing in this case?(in case you worked with database logs), export to csv and then do it with unix tools?
For one: those standard Unix tools can convert from date/time values to timestamps just as easy. Arguably easier.
And a timestamp is merely an Int, so many languages, databases, APIs and so on, lack ergonomic methods to convert timestamps to datetimes. But have easy ways to do the reverse. It's almost always easier to convert dates, times or datetimes to timestamp ints (or floats) than to convert an int or float to a date, datetime or time.
A timestamp.toString() is unfamiliar to humans, a datetime.toString() is not. The list of small benefits in favor of actual date or time types just goes on.
That way you can merge them from different sources and sort them to help figure out interactions and causality. There might be clock drift from different sources but that's a much smaller problem than trying to eyeball multiple different logs concurrently, or write ad-hoc scripts to enable merging.
When people try to apply this to other time related info, it's always a disaster.
If you can’t go that far and still need local time zones in some specific part, just embrace your fate and keep and display timezones everywhere, even when it’s UTC.
TBH, I’ve never seen an organization that could 100% move everything to UTC. Especially with countries following DST and other shenanigans, and you want to quickly be able to compare events at the same local time.
If you're going to do it in storage, keep it outside the ISO/8601 string. Chronology is the most important thing to get right. Locality comes after
Unless the whole world agrees to communicate times in UTC, at some point, you will share a screenshot or a log message with someone outside of your company, and they cannot assume what time zone it's in.
using namespace std::chrono;
std::this_thread::sleep_for(30s);
Boost units add all sorts of dimensional analysis.
When the input box is a function the only unit you need to know is 'distance'. So I don't completely agree with the article. A sleep function does not need the unit in it's name but should accept a domain unit: duration. The function itself can convert it to something the function can handle.
`sleep(2s+5ms)` should just sleep 2 seconds and 5 milliseconds.
[0] https://github.com/mpusz/units
[1] "Daniel Withopf - Physical Units for Matrices. How hard can it be? - Meeting C++ 2021" https://m.youtube.com/watch?v=4LmMwhM8ODI
Contrarian opinion: You don't. You make people look up and internalise such information; that way they'll actually learn, as otherwise they'll forever stay within the realm of "beginner". Perhaps that's a goal for those who want to make programmers fungible (and I suspect a lot of the "readability" movement is merely an extension of that), but I don't think that's something we should encourage.
I would rather have my team spend time internalizing good design rather than the trivia of what units are associated with every numeric argument in every codebase.
If time.sleep took a timedelta it becomes impossible to use incorrectly with a type checker since the caller specifies their own units. There is no merit to worshiping ambiguous design.
What you say works at a small startup. Absolutely.
My reality and lots of other people at companies with larger code bases: you need to constantly look at code you have never seen before in one of many languages used at your company using one framework or another that is out of date by years or just came around the corner and you just heard the name of for the first time.
This is the reality of many an architect or team lead or principal engineer. Of course you will say: why make everything better for them, works fine for me who I only ever work in language X with framework Y? I agree that makes sense for the you of now. Why care?
Think about the future you. The principal engineer you. The architect you. Heck even just the 9 months from now you when you have moved on to the next framework. Never mind any other changes.
Or for that matter, the spelling of words and their meaning in your choice of (human) language.
We call those who can't do the latter "illiterate".
Imagine if you had to look up almost every word you speak or write in a dictionary.
Task.sleep(nanoseconds: 3e11) Date().advanced(by: .hours(2) + .seconds(10))
I'm honestly not sure why TimeInterval doesn't include this representation by default.1. https://developer.apple.com/documentation/dispatch/dispatcht...
julia> using Dates
julia> Millisecond(10)
10 milliseconds
julia> sleep(Microsecond(100))
julia> sleep(Millisecond(10)) def frobnicate(timeout: timedelta) -> None:
...
timeout = timedelta(seconds=300)
frobnicate(timeout)
Now instead of remembering that frobnicate takes an argument of seconds, one now needs to remember it takes a completely different type, the constructor for which now also needs to be memorized. When the main problem presented is one of memorization, this seems obviously worse?This seems less like a memorisation problem and more of an IDE one. If I'm presented with a type in my IDE, I can just look through its constructors and methods to find the one I require; no need for memorisation.
Making implicit units explicit is a great example of that. Look at Martin Fowler's writings on Money types, for example. Or look at the $125 million failure of a space probe because people used implicit units: https://www.simscale.com/blog/2017/12/nasa-mars-climate-orbi...
1. https://www.php.net/manual/en/function.sleep.php
2. https://www.php.net/manual/en/function.usleep.php
3. https://www.php.net/manual/en/function.time-nanosleep.php
An example of use is in the FHIR (Fast Healthcare Interoperability Resources (hl7.org/fhir)) standard as a valueset.
https://www.hl7.org/fhir/valueset-ucum-units.html
[edit to remove dupe linke]
Would love HN’s recommendations for blogs/writing on how to do better programming.
A lot of writing that I am exposed to is about the business of software, or engineering leadership, or architecture/tech stacks — which, to be clear, I really like reading, and find value in!
But I would love to read more thoughts on how to actually write good code on a regular basis.
Also, I love F#'s units of measure.
https://overcoddicted.com/domain-specific-types-for-primitiv...
@lru_cache(maxsize=None) # memoize
def seconds(time_code):
"""number of seconds defined in DNS format: '2m30s' = 2 min 30 sec = 150s. h = hour, d = day, w = week"""
result = 0
number = ""
for char in time_code:
if char.isdigit():
number += char
else:
secs = {"s": 1, "m": 60, "h": 3600, "d": 24 * 3600, "w": 7 * 24 * 3600}[char]
result += int(number) * secs
number = ""
return result void foo(Duration duration);
var result = foo(Duration.ofHours(2));
You can also do simple calculations easily var bar = Duration.ofHours(2).plusMinutes(30);It's funny how the article talks about using the type system, but the title does not.
Instead always use "TimeSpan dataCacheTime" as this is more flexible: can hold values from sub-millisecond up to multiple days, and is easier to use with framework methods that will also expect this type.
In other words, use the appropriate type instead of putting the duration unit name in the var.
Lemme tell you, every single organization that respect itself, it will tell you, during code review, that you do not use magic numbers in code. It's a red flag, so his "Do this: frobnicate(timeout_seconds=300)" will actually fail the code review.
Here is what you would do instead. Declare a constant in some constants only unit, with explanation what it does and then use that constant, like this:
//constant unit
const TIMEOUT_SECONDS = 300;//bla bla why this is 300 seconds, usually from client requirement
//code unit
frobnicate(TIMEOUT_SECONDS);
const TIMEOUT_SECONDS = ONE * HUNDREDS;
The definition of ONE and HUNDREDS is left as an exercise.Snark aside, the rule zero of all coding conventions is that they should not be applied if they do not make sense in a specific case.
frobnicate(300) // Duration in seconds to do X
Sure, change the variable names or whatever as well, but ... kinda seems we already have a way to make less obvious things obvious?
If it’s in the parameter name it’s impossible to use it without doing it correct, which is almost always preferable.
But one better than documenting comments is no documenting comments. Selfdocumenting code is certainly not always feasible. But in this case it's both possible and easy.
Process.sleep(_milliseconds = 300)
I started using it more and more because it makes the code more readable.https://www.joelonsoftware.com/2005/05/11/making-wrong-code-...
It also makes the distinction between "apps hungarian" (good, unit-types, eg: meters, seconds) and "system hungarian" (bad, storage-types: float, int)
Sadly I've never worked on a codebase that follows this.
This did the job really well, but it was incomplete. Being able to create new types dynamically, when multiplying/dividing was something that was always missing. I guess now you could probably do this with macro programming, but back then I don’t think my language had it.
https://geant4.web.cern.ch/sites/default/files/geant4/collab...
The SI unit is seconds. So unless you have some weird aversion to using decimals to represent smaller units, any kind of delay function should take input in seconds.
Not sure if this should be a cautionary tale about using units so much as using the correct units in the first place.
Apparently there's a Java function that lets you specify time units as secondary input. Use that to make in unambiguous.
The foundation of web, javascript is one of them. Send seconds in api to a frond-end without documenting is just confusing and hugely ambiguous.
And it makes more sense from the GUI's perspective. What did you mean paint next frame after 0.016s? Isn't it much easier to read when write it as 16ms?
pause for 3 seconds
With some other options for units. https://github.com/rzimmerman/kal#asynchronous-pauseIt seems types are useful piece of information. Who would expect?
This is fine but relying on an IDE for code reviews really sucks. I'd much prefer to be able to do it on github. And it sucks for any language which infers types :( Scala is in particular awful for reviewing on github
I wish code review tool could provide this hover functionality too.
sleep 5.seconds
or temperature = 0.17.kelvin
Not sure that last abuse actually works, but one may try. :-PSame thing with explicit memory allocation. If for whatever weird reason I need to explicitly allocate RAM I first write deallocation.
For example, when I create a static value to hold a constant, I usually do it like so:
static private let _maximumButtonHeightInDisplayUnits = CGFloat(30)Depending on your language, and how much type safety you want, you could use something Haskell's units library [3].
I believe F# also has units [4], possibly built in to the language? (I've never used F#.)
[1] https://en.wikipedia.org/wiki/ISO_8601#Durations
[2] https://docs.oracle.com/en/java/javase/11/docs/api/java.base...
[3] https://hackage.haskell.org/package/units
[4] https://docs.microsoft.com/en-us/dotnet/fsharp/language-refe...
Take heed young adventurer: This balm will not solve all your ills. It will be your hard work, compassion, and perseverance that will bring the new golden age and sustain it.
TLDR: We've done this before, it solves some problems and causes other.
time.Sleep(42 * time.Millisecond)
time.Sleep(42 * time.Second)
time.Sleep(42 * time.Nanosecond)
time.Sleep(42 * time.Hour)The fact you can go from int to duration without specifying the unit does not give you the strong benefits. It's better than nothing though
The unit that is converted in, is in the first sentence of the two-sentence documentation of time.Duration():
A Duration represents the elapsed time between two instants as an int64 nanosecond count.
https://pkg.go.dev/time@go1.18#Duration time.Sleep(time.Second * time.Second) def foo(x):
print(x)
accept `foo(x='I accept keyword arguments!')`Somewhat relevant.
Thread.sleep(millis: 300)It was a pretty safe guess, though, the number of bugs related to this is pretty epic.
Thread.Sleep(TimeSpan.FromSeconds(3));
or with its int overloaded method: Thread.Sleep(millisecondsTimeout: 3000);let time: float<s> = 0.1<s>
let length: float<m> = 10.0<m>
let speed: float<m/s> = length / time
```
time.sleep(timedelta(minutes=5).total_seconds)
```
Or
```
time_to_sleep = timedelta(minutes=5) time.sleep(time_to_sleep.total_seconds())
```
For example...
time.sleep(timedelta(minutes=5).total_milliseconds)
...looks just as plausible. So what does this solve?I'm not saying time.sleep can't be improved but my method makes it easier to find any mistakes I've made in the future.
As a demonstration, reading your code makes it more obvious that you've passed the wrong unit into time.sleep.
Seems reasonable! :)
When I encounter these sorts of methods (which is surprisingly rare these days) I tend to double-check what units the method takes and additionally add a comment above my call saying "`sleep` takes duration in seconds", just to give future readers more ways to check whether I screwed up.
Why would you want to enter a percentage of a minute?
[0] https://en.wikipedia.org/wiki/International_System_of_Units
When I hover over time.sleep(delay) in my Python IDE the detailed pop up shows me that this sleeps for delay seconds and that delay is an int.
When I hover over time.Sleep(wait) in my Go IDE, the popup shows me that time.Sleep takes a time.Duration.
Please get better tools and stay the heck away from both my languages and coding style guidelines.
"why isn't my code doing anything?!"
This should've been Option One
I'd argue that it's fine if the accounting app is never going to handle multiple currencies.
Length object = Length.Parse(string);
or
Temperature object = Temperature.Parse(string);
this would but much simpler!
await sleep(5 * MINUTES)
Where MINUTE and MINUTES is a constant for 60 * SECOND.
...
time.sleep(three_seconds)
When it's already too hard knowing the units of the function you're supposed to know, then why does he think he's supposed to code in the first place?
Bat-shit ridiculous. Of course people with low skills will be all over this, happily embracing it, but it's still absolutely ridiculous.
If you can't even remember this, then you should not be programming in the first place!
Do you label your variables a, b, c,...?
It's a function. You're supposed to know what the function is doing and the parameter it is accepting. Someone who can't even do that and instead requires it to be fully laid out in front of him should consider looking for a different profession.
This just replaces knowledge with looking at things. It's not helpful at all. Imagine every variable in every function ever would be written down based on its type. Insanity!
... and yes. My main variables are q,w,e,r,t (DWords) ... qq,ww,ee,rr,ss (QWords) ... etc ... all sitting neatly in a cacheline. Those I use for loops and whatever else I need them. Variables that really need naming I actually name appropriately. Variables that do not need naming I simply don't.
You'd be amazed how easy it is to read my code. It's important to understand that, just because someone can do something, doesn't mean he's good at it. This problem gets even worse when everyone just keeps trying to make it easier for people who would be better off doing something else.
No, this isn't an "elitist" perspective, it's the perspective of someone who understands that constantly "lowering the bar of entry" aka "making everything more and more accessible" makes everyone dumber in the long run, because with each and every step one removes any need to actually think and understand what he's doing.
Do you understand that?