30 ms·
Please put units in names
- sclangdon 5y agoI have a similar nitpick with boolean arguments. How many times have you seen something like: DoSomething(true, false, false)? It's much more readable if you use enums (in a language that doesn't let you specify the argument name at the call site). E.G. DoSomething(ENABLE_REPORTING, USE_UTC, OUTPUT_VERBOSE).
- zcombynator 5y agoUnconventional take: just take the SI base unit any time. For time it's 1 second.
- rbanffy 5y agoOn a related, but not quite the same, it'd be quite cool to be able to express number literals as: 2K (for 2000), or 2K4 (for 2400), or 1Ki for 1024.
- skyde 5y agowhat about having measure class instead. Ex: Length object = Length.Parse(string); or Temperature object = Temperature.Parse(string); this would but much simpler!
- ad-astra 5y agoAgreed, always one of my peeves.
- josephg 5y agoOne more tip: If you're ever designing an API like this, instead of: 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!)
- xyzzy_plugh 5y agoThe solution to this is as old as salt: typedef int seconds; and time.sleep(seconds duration);
- ameliaquining 5y agoThat doesn't really seem better, because the fact that the unit is seconds is only obvious if you happen to be looking at the function signature in the header or somesuch. This is because C typedefs are type aliases, not newtypes. If seconds were instead a struct with a single int field, or something like that, then that would help a little. To really solve this problem, you need information hiding, which C doesn't have except through questionable hacks.
- adtac 5y agoI'm sorry, but if a language forced me to write str.len_utf8_bytes() every time I wanted the length of a string, I'd just stop using that language.
- mgdlbp 5y agoThough it might encourage some to consider str.len_extended_grapheme_clusters()
- jeffparsons 5y agoOut of interest, which length did you want?
- jhasse 5y agoNumber of characters
- int_19h 5y agoWhat's a "character"? A codepoint? A glyph? Is "fi" a single character? How about "ß"? "Ȣ"? "IJ"? 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.
- throwaway81523 5y agoI've heard of some Ada coding standards that require this in all variable names. It must have made the code awfully clumsy, but as the examples in OP show, it can be made nice. So the general advice is good. I'm slightly disappointed that the Haskell library didn't use a newtype, e.g. threadDelay (Microseconds 300).
- wyager 5y agoHaskell has a couple libraries that would be great here; either the excellent time library, or the very powerful dimensional library with full statically typed SI units. Of course for something as core as threadDelay, a newtype is more appropriate as you say.
- throwaway81523 5y agoAnother approach (used somewhat by Python, at least for time units) is use SI units or some other standard or convention, and be willing to use floating point numbers for measurements. That was considered bloat in the old days, but reasonable general purpose computers these days almost always have FPU hardware.
- p_l 5y ago"Native" Ada way would be to declare units in types and require explicit casts (also, you can prevent casting to unsupported types, so no retrieving Int64 from hypothetical Duration_Nanoseconds
- ahelwer 5y agoI prefer using timedelta (or TimeSpan for the .NET crowd) but I’ve run into a somewhat funny resulting problem: often these time values are read in from a config file, so now people need to know/remember the serialized time span format. Like what is “00:50”? Is it fifty minutes? Seconds?
- marcosdumay 5y agoThat's why you use a constructor with the unity names, not the conversion from a unityless string.
- ruuda 5y agoYou don't have to use the default serialization format. You can have `timeout_seconds = «int»` or `timeout = «int»s` in your config file, store it internally as timedelta, and convert when you read the file.
- ahelwer 5y agoSeems to negate the motivation for using a timespan datatype in the first place.
- SideburnsOfDoom 5y agoSure, we got used to the format. I have a gist that among other things lists all of the cases, including the harder ones such as "10ms", or "3 days". 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.
- fastball 5y agoThough you don't actually need to enforce keyword arguments, any good IDE will give you the (positional) arg names if you mouseover or w/e, so as long as the positional arg is named `timeout_ms` instead of `timeout` it should still be fine.
- anko 5y agoI think the problem is a bit more nuanced, but i don't have a perfect answer. 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
- rahimiali 5y agoIDE hints like this are useful when you're writing the code, but not so useful when you're reviewing it in online code review tools. I wish code review tool could provide this hover functionality too.
- knowledge-clay 5y agoI think Go has a reasonable approach: time.Sleep(1 * time.Second)
- jamestimmins 5y agoI'm not sure why but I have a visceral, negative response to this. It might be the best solution, but it definitely /feels/ like the worst of all the worlds.
- sk0g 5y agoIs it? In most languages you do something like `time.Sleep(1 * 1e6)` instead at which point it could be a second, a few minutes, a day, who really knows? 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.
- syntaxfree 5y agoOverloading the asterisk is always weird because multiplication is expected to be associative etc etc.
- ts4z 5y agotime.Second*1 gets the same value; it's not overloaded. Well, ok, so what actually happens is that time.Second is a time.Duration, and Duration*int yields Duration (and int*Duration yields Duration). 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.
- ts4z 5y ago(As noted elsewhere it's nanoseconds.)
- xyzzy_plugh 5y agoIt's not overloaded. It's a unit. You can just type time.Sleep(time.Second) but this reads nicely time.Sleep(3 * time.Minute)
- windpower 5y agoSwift is pretty good at this. e.g.: Task.sleep(nanoseconds: 3e11)
- gh123man 5y agoIn swift I quite like DispatchTimeInterval's approach [1] (see Enumeration Cases). In most of my projects I end up adding a simple extension to TimeInterval to get the same behavior. Which makes reasoning about time very simple eg: 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/dispatchtimeinterval https://developer.apple.com/documentation/dispatch/dispatcht...
- oatmeal_croc 5y agoIs there a standard for Durations, like we have for Time? (Like RFC3339)
- rotifer 5y agoISO 8601 specifies durations [1]. For example, Java's Duration type [2] is based upon it. 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 https://en.wikipedia.org/wiki/ISO_8601#Durations [2] https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/Duration.html https://docs.oracle.com/en/java/javase/11/docs/api/java.base... [3] https://hackage.haskell.org/package/units https://hackage.haskell.org/package/units [4] https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/units-of-measure https://docs.microsoft.com/en-us/dotnet/fsharp/language-refe...
- xyzzy_plugh 5y agoOr join the ranks of your peers who have seen the light and use types. 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.
- justinhj 5y agoThat would be the second paragraph in the article
- fouc 5y agothe article mentions strong types
- verandaguy 5y agoThe article addresses this somewhat using Python's type hints. If I give you his signature, can you intuitively tell me what unit is being taken in by the function? 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.
- matsemann 5y agoThat's because your not using the type system at all in your example. Change it to "addSomething(Length height)", and have constructors for Length.ofCm(2), Length.ofMeters(5) etc.
- verandaguy 5y agoSure, but this isn't a solution that's unique to statically-typed languages, and the syntax can get more awkward if you use a language without good OO support. 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).
- Jamie9912 5y agoDiscord API is guilty of one of these very examples, they send a retry-after header on 429 responses, but the thing is.. is it in Bananas? Apples? Elephants?
- timando 5y agoThe retry-after header is documented as being in seconds (or a date). https://httpwg.org/specs/rfc7231.html#header.retry-after https://httpwg.org/specs/rfc7231.html#header.retry-after
- deleted 5y ago[deleted]
- Jamie9912 5y agoFunny because Discord implements it as milliseconds
- ruuda 5y agoUnfortunately it's part of http. One thing you can do is to send both the standard Retry-After header for tools that rely on it, and a nonstandard but unambiguous Retry-After-Seconds. That makes responses self-documenting. (One downside is that you now have two numbers, and if you introduce a bug that makes them different, it will be more confusing.)
- justinhj 5y agoPassing the time unit as a second parameter is used a lot in Java APIs and seems to work well
- qw 5y agoJava's Duration is also useful for time units void foo(Duration duration); var result = foo(Duration.ofHours(2)); You can also do simple calculations easily var bar = Duration.ofHours(2).plusMinutes(30);
- nraynaud 5y agoI recently worked on some disk file formats (.vmdk, .vhd), and I always put the units in the name, because I'm always switching byte, sectors, blocks. Same for addresses, is it a LBA on the virtual disk, or an offset in the disk image file.
- WatchDog 5y agoOr use an IDE? Here[0] is a screenshot of the Java example in idea, not only does it show an inlayed parameter name hint, but simply mousing over the method will show you the documentation. [0]: https://i.imgur.com/8UcEO5N.png https://i.imgur.com/8UcEO5N.png
- wyager 5y agoPrograms should be comprehensible as text, without machine assistance.
- gregmac 5y agoThis doesn't work looking at a PR. 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.
- swyx 5y agoin the genre of naming things, some related things to explore: - 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 https://www.swyx.io/how-to-name-things
- tcbasche 5y ago>- don't choose lazy pluralization - eg instead of `names/name`, use `nameList/nameItem` 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.
- lifthrasiir 5y agoEven in typed languages `names` and `name` are too similar to slow code reading down.
- berkes 5y agoExactly this. In many languages the compiler will help you. 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.
- ParetoOptimal 5y agoDisagree, but in that case wouldn't `nameList` and `name` be best?
- amingilani 5y agoMy preferred way in Python is: ``` time.sleep(timedelta(minutes=5).total_seconds) ``` Or ``` time_to_sleep = timedelta(minutes=5) time.sleep(time_to_sleep.total_seconds()) ```
- jeffparsons 5y agoUnless I'm confident that I remember `time.sleep` wants a number of seconds, then I could miss an obvious error there. For example... time.sleep(timedelta(minutes=5).total_milliseconds) ...looks just as plausible. So what does this solve?
- amingilani 5y agoIt communicates my intent to the reviewer and future readers of the code that: 1) I mean to set the duration to 5 minutes, which is easier parsed by humans than 300 seconds. 2) I'm passing seconds into time.sleep, which makes any mistakes I make more obvious. 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.
- jeffparsons 5y agoGot it — so it's more about mitigating the badness when it's somebody else's API. 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.
- macinjosh 5y agoWhen I learned Objective-C I remember being flabbergasted at all the method and argument names that were exceedingly wordy. At some point I read a blog post[0] that said while this is out of the ordinary when it comes to most code having long, descriptive names helps when reading code. 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-objective-c.html https://www.cocoawithlove.com/2009/06/method-names-in-object... [1]: https://developer.apple.com/documentation/appkit/nsbitmapimagerep/1395538-init https://developer.apple.com/documentation/appkit/nsbitmapima...
- wnoise 5y agoAutocomplete handles the "too much typing" case.
- wyldfire 5y agoI would go one step further and suggest that all physical quantities should either have the units in the identifier name or encoded in the type system. Meters, seconds, milliamps, bytes, blocks, sectors, pages, rpm, kPa, etc. Also it's often useful to explicitly distinguish between different unit qualifications or references. Seconds (duration) versus seconds-since-epoch, for example. Bytes versus page-aligned bytes, for another. 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.
- jeffparsons 5y ago100%. This is a baseline requirement where I work. If you don't either include the units in the identifier name, or use the type system where possible, your code is not getting merged. The only people I've ever met that think this is unnecessary are also the same people that ship a lot of bugs for other people to fix.
- Aeolun 5y agoWhat does a type for ‘seconds’ do that an ‘integer’ doesn’t? I may be misunderstanding this.
- hmaarrfk 5y agoI typically stick to "SI" units. 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...
- jeffparsons 5y agoBut you're still including the units in your identifier names (or encoded in type system), right?
- hmaarrfk 5y agoNo. Typically SI is implicit. Everything else is explicit.
- mminer237 5y agoSI doesn't prescribe that you have to use a single unit for all measurements. Are distance in meters or kilometers? Weights in kilograms or grams? 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.
- nvader 5y agoI'm confused, because one delta degree Celsius is exactly the same as one delta degree Kelvin. And you can convert with an offset.
- nine_k 5y agoIn thermodynamic calculations you likely need absolute (Kelvin) values. But in many calculations where only temperature difference is used, either unit works equally well.
- cynik_ 5y agoI wrote about this a long time ago too: https://explog.in/notes/units.html https://explog.in/notes/units.html. Units are critical, particularly when crossing language/engineer boundaries.
- emmelaich 5y agoWorth mentioning Frink. > 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.. https://frinklang.org/ https://frinklang.org/
- dkbrk 5y agoFrink's units definition file is a great read: https://futureboy.us/frinkdata/units.txt https://futureboy.us/frinkdata/units.txt 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.
- SkeuomorphicBee 5y agoA really great read. I found particularly interesting the long comment about the Hertz inconsistency, I had no idea the S.I. Hertz, when applied to circular motion, was not a full circle per second.
- sleepydog 5y agoThis is not exactly the same thing, but for the love of god, if you have a monitoring or logging product, make the date and time zone visible wherever time is displayed. I cannot tell you how many times I've been sent screenshots of graphs, showing some catastrophic scenario at, say, 08:43, with no idea of what time zone the graphs are using, or what day the graph is showing.
- 10000truths 5y agoI prefer the use of Unix timestamps. Easier to filter with standard Unix tools, and if I really need formatted date+time in my output, I can always use awk.
- simion314 5y agoI don like it, say I open a database table and search for some events , then look at the created_at column and see a timestamp, so now I need to copy paste timestamps into a webpage and convert it to human readable time to then notice is 5 years old and not what i am looking for. What are you doing in this case?(in case you worked with database logs), export to csv and then do it with unix tools?
- 8n4vidtmkvmk 5y agodepending on the sql dialect, you can convert it in sql. or even add a virtual column with the conversion for your convenience
- berkes 5y agoI used to prefer unix timestamps too. But I Saw The Light. 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.
- dragonwriter 5y agoUnits in values > units in names.
- animsriv 5y agoI remember as a kid, my Physics teacher used to penalize us for not writing the unit in the calculations. It seemed absurdly archaic at that time, but it makes so much sense now.
- rolobio 5y agoIn Python you can force the use of a parameter’s name with * 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.
- Biganon 5y agoThat's in the article...?
- deanCommie 5y agoIf you're passing around parameters, use a Duration class. Most languages have one: * https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html https://docs.oracle.com/javase/8/docs/api/java/time/Duration... * https://docs.microsoft.com/en-us/dotnet/api/system.timespan?view=net-6.0 https://docs.microsoft.com/en-us/dotnet/api/system.timespan?... * https://en.cppreference.com/w/cpp/chrono/duration 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.
- FpUser 5y agoHa. I've learned it decades ago. It is handled on a level of my spinal chord. Same thing with explicit memory allocation. If for whatever weird reason I need to explicitly allocate RAM I first write deallocation.
- moralestapia 5y agoAgree with the post. 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.
- linkdd 5y agoDo you have a link to this utility?
- moralestapia 5y agoOh sorry, I haven't open sourced it, I never thought of it actually until now. As I now realize, it could be quite useful for others.
- userbinator 5y agobut how can we keep the code readable even for people who haven’t encountered time.sleep before? 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.
- rhinoceraptor 5y agoHow is rote memorization of the arguments the stdlib of a language the difference between a beginner and an expert? I forget those kinds of things all the time, even for the language I use 99% of the time.
- userbinator 5y agoHow is rote memorization of the positions of the keys on a keyboard the difference between a beginner and an expert? 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.
- rhinoceraptor 5y agoBeing able to touch type makes you a good typist, and being good at spelling makes you good at spelling. Those two don't make you a good programmer or writer.
- jitl 5y agoPerhaps sleep in $YOURLANG is essential/trivial so there’s an argument that you should memorize it. OF course! It’s just one bit of info. But there are more APIs than sleep that take a number. Are they guaranteed to be consistent? No. What about `someVendorApi.setTTL(ttl: number)`? Is this also another thing to be looked up and internalized? What if there are hundreds of APIs that take numbers? 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.
- gumby 5y agoC++ gets this right for time durations, and has packages that do it for other units as well.
- omoikane 5y agoPerhaps you mean one of these? https://en.cppreference.com/w/cpp/chrono/duration https://en.cppreference.com/w/cpp/chrono/duration https://abseil.io/docs/cpp/guides/time#time-durations https://abseil.io/docs/cpp/guides/time#time-durations
- hoten 5y agojust today I wasted some debugging cycles when my problem was using "sleep(500)" vs "usleep(500 * 1000)" (500 seconds vs 500 ms). "why isn't my code doing anything?!"
- btown 5y agoAlong these lines: if you are designing an API for pricing data or fintech and think “let’s send things in integer cents of the currency so there aren’t any rounding errors” - setting aside that there are many situations where this is not appropriate, if you do still want to do this, for the love of Pete please name your variables and attributes with `_cents` in the names. No exceptions. It is the biggest unit-related footgun imaginable, and since it’s not a “unit” technically, it’s easy to overlook.
- arpa 5y agoAssuming all currencies have 2 decimal units and subunits have 1:100 ratio is another major footgun: https://en.m.wikipedia.org/wiki/ISO_4217 https://en.m.wikipedia.org/wiki/ISO_4217
- btown 5y agoAbsolutely agreed! And a more nuanced approach is what Stripe does, which is to take the "zero-decimal-currency" as the unit of record, be that USD cents or the non-subdivisible JPY. https://stripe.com/docs/currencies#zero-decimal https://stripe.com/docs/currencies#zero-decimal 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.
- Archelaos 5y agoAs we all know, naming things is so difficult. 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?
- connicpu 5y agoSometimes the verbosity annoys me a little while writing it, but I do think Rust made the right decision making you write code like the following to use the standard sleep function. std::thread::sleep(Duration::from_millis(300));
- onox 5y agoIn Ada you can do something similar: 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)
- gpderetta 5y agoIn fact std::thread::sleep doesn't exist. There's sleep_for and sleep_until. Time deltas and time points are incompatible at the type level, so you have to do: 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/
- eMSF 5y agoGP's snippet was in Rust (not that I know if it's valid Rust code). 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).
- egberts1 5y agoHaven’t had a mistype or a case of confusion with using Ada language to date.
- bmitc 5y agoForever and always. :) If I see a numerical value that has units but doesn't in the name, I add it. Also, I love F#'s units of measure.
- eyelidlessness 5y agoI prefer to do this with types versus variable/parameter names where possible, but yep runtime names otherwise. It annoys some people but the thing is almost always either autosuggested or showing up in your editor as you type as docs, so… to quote Mitch Hedberg, “we apologize for the convenience”.
- didip 5y agoPreach! This is a big issue across all projects written in any programming languages. 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.
- nailer 5y agoIn JS/TS I’d do: await sleep(5 * MINUTES) Where MINUTE and MINUTES is a constant for 60 * SECOND.
- asimpletune 5y agoA while back I made a units and dimensions library where I worked. Everything was built into the type system, with a required SI conversion for each unit of a certain dimension. 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.
- armchairhacker 5y agoBuilt-in unit types are underrated. F# has them. Other languages should seriously consider adding them, despite the fact that feature bloat is a serious language problem and they're relatively niche: they are that useful, and I honestly don't think they would interfere much with other features. 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.
- lf-non 5y agoYup, I have been using branded types in TS to avoid similar issues, and I still do miss F# units of measure. 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.
- eyelidlessness 5y agoI use a variant of branding in TS for this too, but it’s very much shoving semantics into the language that aren’t meant to be there. Subclasses of primitive types would be semantically closer to F#, but at the expense of being able to ever treat the values as values
- moelf 5y agoor just have multi-dispatch, Julia: julia> using Dates julia> Millisecond(10) 10 milliseconds julia> sleep(Microsecond(100)) julia> sleep(Millisecond(10))
- unnouinceput 5y agoEh, it seems the author never worked for a big organization and when it finally did, it has a pet peeve. 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);
- aembleton 5y agoIn this case, the units are in the variable name. I think that was what the author was arguing for.
- gpderetta 5y agoBut that still using a magic number, so obviously you should do something like this: 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.
- unnouinceput 5y agoThe "bla bla" explanation will suffice. Usually will include a link to documentation, no need to further split the hair
- charcircuit 5y agoMeanwhile in Java this is handled by the IDE. The IDE will insert the variable name since you are passing in just a number. Thread.sleep(millis: 300)
- xigoi 5y agoI don't think a language should require an IDE to be usable.
- timando 5y ago> And don’t design your CLI accounting app like this: > show-transactions --minimum-amount 32 I'd argue that it's fine if the accounting app is never going to handle multiple currencies.
- antisthenes 5y agoWell, the only correct way to do it then is the way Python does it. 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.
- mmis1000 5y agoWell, no. There are language's default unit is milliseconds. 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?
- scottmcdot 5y agoDoes anyone else like to put data types in their variable names? Sometimes in finance I come across dollars and cents presented as an int and sometimes as decimal(18,2). So I don't confuse them I do something like payment_amt_d1802 or payment_amt_int.
- lowbloodsugar 5y agoNaming the method sleepMillis or sleepSeconds would help too.
- nerdwaller 5y agoIn my opinion that's too specific as you'd need a dozen methods just to accomplish the common needs. Why not use a type as the argument that's explicit and meets even more use cases? Meaning instead of accepting an int just accept a `timedelta` in python or a `time.Duration` in go, or `2.seconds` (I don't recall the type) in rails?
- logbiscuitswave 5y agoFully agree with everything in this article. This is definitely a code smell to me to see unitless sizes and intervals specified. I know that whenever I’m doing a code review and I see some property or variable name like “timeout” or “size” I will ask the developer to change the name to make it clear what the unit is trying to portray. 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.
- bentcorner 5y agoI also agree but would offer a third suggestion - add the type to the function name as well, so you see this line in code: `timeoutSec(timeout)`. You can't enforce people to name the parameter correctly, this means that anyone reading doesn't have to go digging to know the parameter type. Also stuff like `timeoutSec(timeoutMs)` stands out like a sore thumb.
- ParetoOptimal 5y ago> I know that whenever I’m doing a code review and I see some property or variable name like “timeout” or “size” I will ask the developer to change the name to make it clear what the unit is trying to portray. In a dynamic language, maybe. In a static language, especially Haskell/Scala/Ocaml/F#, I hate duplicating the type.
- ketzo 5y agoTangentially related: 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.
- jeffreygoesto 5y agoGood C++ library for that topic is [0]. You can even go further and combine with something like [1] which is super helpful for kalman filters and other stuff where you have heterogeneous units in one vector. [0] https://github.com/mpusz/units 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 https://m.youtube.com/watch?v=4LmMwhM8ODI
- usrbinbash 5y ago*cough* Golang *cough* time.Sleep(42 * time.Millisecond) time.Sleep(42 * time.Second) time.Sleep(42 * time.Nanosecond) time.Sleep(42 * time.Hour)
- conradludgate 5y agoThe trouble with Go is that you can't multiple ints by Durations, leading to people doing `time.Sleep(time.Duration(x) * time.Second)` which is fine by itself, but then I see often people refactor and accidentally remove the second part. 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
- usrbinbash 5y ago> The fact you can go from int to duration without specifying the unit 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 https://pkg.go.dev/time@go1.18#Duration
- conradludgate 5y agoYes, in the documentation. But if I'm reading the original code and refactoring, having the docs open might not be my top priority
- int_19h 5y agotime.Sleep(time.Second * time.Second)
- usrbinbash 5y agoSo? Non Canonical code can be written in any language. The important thing is: There is a canonical way in the stdlib to specify durations that is easy to read for the programmer.
- rubenbe 5y agoFor C++ you can use boost units. It is basically built up of template magic which only compiles when your units are correct. The disadvantage: when it doesn't, it explodes in a huge template error. But when it does, you can be pretty certain (depending on the actual calculation) that your code is correct. It is also fully verified at compile time, so there is no runtime overhead. https://www.boost.org/doc/libs/1_78_0/doc/html/boost_units.html https://www.boost.org/doc/libs/1_78_0/doc/html/boost_units.h...
- wackro 5y agoSomewhat unrelated, the typography and use of color on this article are sublime. No cookie popup either. What a joy.
- yummybear 5y agoI can understand the reasoning, in this specific case. But having every function designating their unit is a new hungarian notation. Imagine working with: setSpeedInKilometersPerSecond vs. setSpeed I'd rather have it baked into the language ala CSS ("100ms").
- kuu 5y agoDo they charge you by written bytes? I really don't see the problem with larger function names...
- OskarS 5y ago"It's annoying" is a pretty good reason. If you don't mind function names like that, go become a Java Enterprise programmer, see how you like it after a few years. 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.
- deleted 5y ago[deleted]
- tirpen 5y agoAre you coding without any form of auto completion?
- qayxc 5y agoAs silly as this may sound, you may run into issues with certain linters or formatting tools in some languages. 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.
- cbsmith 5y ago...and so the tradition of loading up variable names with meta information that should really be in the type system is passed down from Hungarian notation to present day... It's funny how the article talks about using the type system, but the title does not.
- rzimmerman 5y agoWhen I put together Kal (a compile to JavaScript language, now defunct), I was particular about this and used the sleep syntax: pause for 3 seconds With some other options for units. https://github.com/rzimmerman/kal#asynchronous-pause https://github.com/rzimmerman/kal#asynchronous-pause
- Leherenn 5y agoMost people are talking about time here, but the one I've seen that has caused the most issues in my experience is deg/rad. UI are pretty much always going to be in degrees, and trigonometric functions in radians, but if you forget to convert it's not always going to be obvious.
- teddyh 5y ago> Don’t design your config file like this: > 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.
- pikzel 5y agoHad I seen PT5M I would have never guessed it meant five minutes, so you would need to refer to the RFC then.
- hkolk 5y ago`m` is not a legal value, should be either `min` or `mo` for minutes or months respectively. `s` is actually one of the SI base units: https://en.wikipedia.org/wiki/International_System_of_Units#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?
- teddyh 5y agoIf the syntax isn’t obvious without looking at the manual, you might as well use an actual standardized syntax. For months (without context, and where you need an absolute interval), I just interpret it as 4 weeks.
- int_19h 5y agoIf the syntax isn't obvious, you should use however much verbosity it takes to make it obvious, because people will still ignore the standard and make mistakes.
- tremon 5y agoI just interpret it as 4 weeks Funny, I would interpret a month as 30 days (since the lunar cycle is slightly over 29.5 days).
- Karliss 5y agoOne more related problem is coordinate systems for positions in any kind of robotics software or even 2d UI applications.
- suhlig 5y agodimensioned[1] got me interested in Rust. I’m not far enough to recommend it, but the concept seems right. [1] https://github.com/paholg/dimensioned https://github.com/paholg/dimensioned
- blenderdt 5y agoIn a lot of software you can enter units into input fields. For example in Blender I can move an object in a direction by entering something like: `(1m+5inch)/2`. Or I can set the max render time to `20sec` or `2min`. 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.
- MrYellowP 5y agoRidiculous. You're supposed to know what you're doing. He should stop coding instead and do something that fits his skills. 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!
- aembleton 5y agoWouldn't it help other to learn though if it's clearer? As you have to label variables, why not include units? How does that hinder you? Do you label your variables a, b, c,...?
- gpderetta 5y agoVariables? Point-free programming is the name of the game!
- MrYellowP 5y agoDon't be ridiculous. You can't take my complain about this and generalize it. 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?
- sleepyfran 5y agoThis is one of the reasons why I love F#, baked in support for units of measures. So instead of having to rename the function to include the unit I can just declare it to take the type `int<second>` and the compiler will complain if you try to pass an `int` or an `int<minute>` unless you declare an explicit conversion between the units.
- jakuboboza 5y agoThis is a very valid argument. Go has this time.Second duration type that is used often and it helps a lot understand things. But things like Js/Pure Ruby have just raw numbers where you have to either check docs or just remember that sleep takes miliseconds or seconds etc. It seems types are useful piece of information. Who would expect?
- wodenokoto 5y agotimeout = 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`)
- Aeolun 5y agoI do not think the fact that Google API’s have terrible types is a good argument against typing in general.
- dharmab 5y agoWhen I dealt with the Azure SDk for Python I frequently wrote small scripts that created the types in question and then called breakpoint() so that I could examine the types interactively.
- akdor1154 5y agoIn general you're right.. strong typing needs good tooling and thourough language support to be fun. Python is a bit lacking in both of these. In this specific example i disagree, timedelta is part of the standard library and should be widely known and familiar.
- chriswarbo 5y ago> 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 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)!
- TeeWEE 5y agoI love the Duration class that Dart has: https://api.flutter.dev/flutter/dart-core/Duration-class.html https://api.flutter.dev/flutter/dart-core/Duration-class.htm...
- bennyp101 5y agoIs this not what comments are for? 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?
- berkes 5y agoIt helps. Even more so if documented with the function signature so documentation (in your editor or ide) can communicate it. 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.
- Aeolun 5y agoProblem with this is that you now need to ensure everyone adds that comment everywhere the function is used. If it’s in the parameter name it’s impossible to use it without doing it correct, which is almost always preferable.
- cryptos 5y agoJava has a good library that supports a variety of measurement units: javax.measure https://docs.google.com/document/d/12KhosAFriGCczBs6gwtJJDfg_QlANT92_lhxUWO2gCY/edit https://docs.google.com/document/d/12KhosAFriGCczBs6gwtJJDfg... http://unitsofmeasurement.github.io/unit-api/site/apidocs/javax/measure/package-summary.html http://unitsofmeasurement.github.io/unit-api/site/apidocs/ja... 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.
- thom 5y agoIf you’re old you call this the Whole Value pattern. http://fit.c2.com/wiki.cgi?WholeValue http://fit.c2.com/wiki.cgi?WholeValue
- tempodox 5y agoAnd, please, also attach units to numeric input fields in the UI so users know what they're entering.
- cute_boi 5y agoRust got it correct imo.
- Closi 5y agoI used to work at a company with two database fields, speed_kmph. The 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.
- quickthrower2 5y agoDB field names can be really hard to change. All those crystal reports to update, and the sales managers pet access DB that the hero set up for him that you don’t know about.
- tonyedgecombe 5y ago>DB field names can be really hard to change. 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.
- cle 5y agoWhat is "correct" is up for debate, and often depends on cost tradeoffs. Sometimes this is the "correct" thing to do, no matter how gross we think it is.
- tonyedgecombe 5y agoNot often, what has always surprised me is how regularly these sort of problems are self inflicted. A lot of people will just do what is expedient regardless of what the management position is.
- Closi 5y agoHow do you write code so that it can accommodate DB field name changes without breaking SQL reports / BI? 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.
- zeristor 5y agoI thought this was in reference to the HNews post from WashingtonPost about the Eastern Antarctic being “70 degrees” warmer. https://news.ycombinator.com/item?id=30733387 https://news.ycombinator.com/item?id=30733387
- Karellen 5y agoYes, don't use Magic Numbers, but use named constants instead. http://catb.org/jargon/html/M/magic-number.html http://catb.org/jargon/html/M/magic-number.html https://en.wikipedia.org/wiki/Magic_number_(programming) https://en.wikipedia.org/wiki/Magic_number_(programming) delay_ms = 300; [...] Thread.sleep(delay_ms); Works in any programming language.
- Someone 5y agoFails in any programming language, too. 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.
- gpderetta 5y agoYes; still parent solution is better than nothing if you have to deal with an existing API. At least if you make a mistake there is a chance someone else might spot it instead of wondering what the original intent was.
- meadsteve 5y agoI ended up building a library for elixir a few years back for this kind of thing: https://github.com/meadsteve/unit_fun https://github.com/meadsteve/unit_fun.
- jillesvangurp 5y agoJava and Kotlin have a nice Duration class. So in Kotlin you can do 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.
- zzbzq 5y agoThe Duration.ofMinutes thing doesn't address the exact same problem. Anyone can put the units on the "right side". You don't even need a fancy "Duration.ofMinutes" helper function. Clarity-wise that's not different than just putting a comment saying how long it is and what units. The problem in the article is getting the units on the "left side," which, yes, you have to put the units in the name of the function.
- macintux 5y agoYou have to enforce the units within the function, but that’s not the same as putting them in the name of the function. For example, in Erlang, the sleep function could/should have been written to take named tuples: `timer:sleep({seconds, 3})`
- renewiltord 5y agoAh no. The function accepts a `Duration` type which could be precisely 1 m 23 s 14 ms 10 us 8 ns. And so you don't need `delay_ms` vs. `delay_ns` or anything because the type encodes the precise duration. If you passed a nanosecond `Duration` into `delay` it will delay ns, if you pass a millisecond `Duration` it will delay ms.
- mellowagain 5y ago
- wiz21c 5y agoJulia seems to have some unit support (via package): http://painterqubits.github.io/Unitful.jl/stable/ http://painterqubits.github.io/Unitful.jl/stable/
- dmurray 5y agoNext step, please don't call your variables ..._percent but interpret 0.5 as meaning 50% of the reference value.
- Mazzen 5y agoHow do you mean?
- stilley2 5y agoNot GP, but 0.5% == 0.005, not 0.5.
- dmurray 5y agoSuppose our application deals with classifying cheese, and has a field for how much fat a given sample has, maybe it needs 20% to be classified as Grade A Ste-Madeleine-de-la-Foo. Some developers like to call this field MinimumFatContentPercent and set it to 0.2.
- BurningFrog 5y agoBad naming is a universe of programming flaws, much of which boils down to not thinking about how a different person might read your code the first time. Unfortunately "Theory of Mind" is weak in people on the spectrum.
- ______-_-______ 5y agoI 100% agree. 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?
- FreeFull 5y agoMaybe "fraction" would be suitable.
- munch117 5y agoI use "andel", but if you don't write your variable names in Danish, then it might look a little strange. "Share" would be the direct translation, but that word usually means something else in programming. In English, I use "ratio" also; in context the meaning is always clear enough.
- numlock86 5y agohttps://web.mit.edu/jemorris/humor/500-miles https://web.mit.edu/jemorris/humor/500-miles Somewhat relevant.
- hosembafer 5y agoSimilar topic, instead of var names, in typed languages you can use domain-specific types for primitives. https://overcoddicted.com/domain-specific-types-for-primitives/ https://overcoddicted.com/domain-specific-types-for-primitiv...
- SideburnsOfDoom 5y agoMy strong recommendation at work is: _do not_ use configuration values such as "int dataCacheTimeMins" as these are prone to error, inflexible (cannot represent 2 mins 30 seconds) and not used consistently (will be mixed in with "int dataRequestTimeoutSeconds" and "int someOtherTimeMillis" and values named _without_ explicit units). 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.
- spixy 5y agoC#: Thread.Sleep(TimeSpan.FromSeconds(3)); or with its int overloaded method: Thread.Sleep(millisecondsTimeout: 3000);
- ChrisMarshallNY 5y agoThis is something that I've done forever. For example, when I create a static value to hold a constant, I usually do it like so: static private let _maximumButtonHeightInDisplayUnits = CGFloat(30)
- pdimitar 5y agoIn Elixir you can use an unused variable pattern matching: Process.sleep(_milliseconds = 300) I started using it more and more because it makes the code more readable.
- deleted 5y ago[deleted]
- foobarthrow2 5y agoI disagree with this, you should infer the units from context. I don't want this hungarian notation in my codes
- einpoklum 5y agoC++ has, in recent years, improved support for this. The best state of affairs is with time units: 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.
- JaggerJo 5y agoF# has units of measure built into the language. let time: float<s> = 0.1<s> let length: float<m> = 10.0<m> let speed: float<m/s> = length / time
- Ensorceled 5y agoI regularly program in Go and Python. 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.
- Lochleg 5y agoIn Golang, I've seen time.Sleep(2 * time.Second). That's pretty explicit, so, it seems someone carried the whole concept forward.
- phkahler 5y agoIt would be much better to (also) put the units int the function name. Don't just have sleep() but sleepSeconds(). This prevents the person writing code from having to look up or guess what units the parameter has, as well as a person reading it later. This is more an API design issue than an API user issue, although both approaches can be used together.
- hutzlibu 5y agoBut I this is not really necessary, if you use a IDE with integrated docs, where you see the parameters of a function on a mouseover.
- gjvc 5y agoin the same vein, please name associative structures (hashes, maps, dictionaries, etc) as value-type-by-key-type (for example "username_by_id", rather than "username_lookup" or such. Conventions like these don't have an impact one-by-one, but rather when applied to a body of code as a whole. In this case when one has to do one lookup by the result of another the explicit "x-by-y" naming really helps reassure me the right values are being looked up!
- friendzis 5y agoPlease do not, unless you are actually implementing unit conversion logic. 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.
- gwright 5y agoFrom the article: > 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
- athenot 5y agoAnd if you're working with an existing system that doesn't accomodate the suggested options, a well placed comment can go a long way. Provide the unit as well as WHY that value exists. # Session inactivity, in seconds time.sleep(300) # Prevent pileup of unprocessable requests, in seconds request_timeout = 10
- refactor_master 5y agoComments are misunderstood far too often as some sort of accompanying inner monologue. Instead, I see a lot of noise like # Sleeps before continuing time.sleep(…) # Time before request timeout timeout = …
- drej 5y agoClicking on the link I though "I wonder it it starts with time.sleep" It was a pretty safe guess, though, the number of bugs related to this is pretty epic.
- shikoba 5y agoOr, except if you need absolute precision, you wrap all those primitives in a function that uses SI. So seconds for your sleep wrapper.
- rzwitserloot 5y agoThread.sleep (the java example) is ancient, but java is at least consistent and uses millis for everything. Almost all other timing functions in java have a 2-arg setup: `.foo(5, TimeUnit.HOURS)`. Where TimeUnit is an enum that has the usual options (HOURS, MILLIS, SECONDS, etc). It doesn't go beyond 'days' (once you get to months in particular, is that 28 days, 30 days, 31 days, 30.437 days (which is the actual average)....).
- DubiousPusher 5y agoProbably already suggested but I'm a big fan of .Net attributes or other such decorators. A system level Units decorator which was respected in argument passing and maybe even automatically printed would be dope.
- MadVikingGod 5y agoAhh the cycle continues. We have lost touch with the lore of ages past, and only the old crones know of the Hungarian notation [1]. As we discover the ruins of old we glean their knowledge, and take up their practices because they were from a more civil time. What we don't recognize is that the creators of old didn't solve these problems and they were always in competition with themselves over which path is righteous. This ultimately led to their downfall, and the ruins you have discovered. 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. 1: https://en.wikipedia.org/wiki/Hungarian_notation https://en.wikipedia.org/wiki/Hungarian_notation
- BurningFrog 5y agoI end up writing this function in most projects I work on. Python version: @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
- runald 5y agoThis usually bites me when it see a function that takes a parameter named angle. I usually have to read the docs or inline comment to know if it's in radians or degrees. At worst case, I have to go to read the implementation to figure it out.
- mannykannot 5y agoWhen dealing with vectors, it is also important to establish your frame of reference. Sometimes, though by no means always, there is a well-established convention. When it is not, however, it can get verbose to encode into identifiers. It can also be tedious, as no-one needs to be reminded of it every time they read an expression. In these cases, documentation is the best choice.
- amai 5y agoIs there a programming language that supports units (and calculation with units) out of the box?
- jonnycomputer 5y agoOk, I'll bite. Why does time.sleep(secs) not accept keyword arguments, but def foo(x): print(x) accept `foo(x='I accept keyword arguments!')`
- falcolas 5y agotime.sleep is implemented in C. For Python, adding keyword arguments to functions implemented in C takes a not-insignificant amount of additional boilerplate, so its often not done.
- jonnycomputer 5y agoAh, of course. Posting before my morning coffee. (:
- rbanffy 5y agoRuby has a very neat syntax that can solve that. For instance, you'd just: sleep 5.seconds or temperature = 0.17.kelvin Not sure that last abuse actually works, but one may try. :-P
- deleted 5y ago[deleted]
- deleted 5y ago[deleted]
- pacifika 5y ago300 * TIME_IN_SECONDS
- dathinab 5y agoAn often better solution is to have a type which is not an integer/string as input and have various ways to convert from/to integers in a unit showing way. 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).
- some_random 5y agoMaybe this is just me, but this suggestion seems worse than the problems 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?
- belval 5y agoI suppose that it varies depending on the project/person, but I agree that using timedelta is less intuitive than just using seconds (as is done everywhere in Python).
- tehwebguy 5y agoYour editor will just tell you the type you need, no?
- AllegedAlec 5y ago> the constructor for which now also needs to be memorized 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.
- wpietri 5y agoThe problem is one of readability, not memorization. A lot of readability amounts to taking what the initial author already knows and expressing it so that it's easy for everybody who comes after to know too. 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-orbiter-metric/ https://www.simscale.com/blog/2017/12/nasa-mars-climate-orbi...
- stjohnswarts 5y agoOr just document it. And the programmer should read documentation for the method. time.sleep() docs tells you exactly what units it uses.
- hwc 5y agoAlso, when using Go, use the time.Duration type in your API. It makes things unambiguous but adds no overhead.
- yummypaint 5y agoFor an example of physical units done right check out the GEANT4 monte-carlo system. It pretty much "just works" https://geant4.web.cern.ch/sites/default/files/geant4/collaboration/working_groups/electromagnetic/gallery/units/SystemOfUnits.html https://geant4.web.cern.ch/sites/default/files/geant4/collab...
- adolph 5y agoThe Unified Code for Units of Measure (UCUM) is a code system intended to include all units of measures being contemporarily used in international science, engineering, and business. The purpose is to facilitate unambiguous electronic communication of quantities together with their units. The focus is on electronic communication, as opposed to communication between humans. A typical application of The Unified Code for Units of Measure are electronic data interchange (EDI) protocols, but there is nothing that prevents it from being used in other types of machine communication. http://unitsofmeasure.org http://unitsofmeasure.org 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 https://www.hl7.org/fhir/valueset-ucum-units.html [edit to remove dupe linke]
- lkxijlewlf 5y agothree_seconds=3000 ... time.sleep(three_seconds)
- snicker7 5y agoJulia supports zero-overhead units: https://github.com/PainterQubits/Unitful.jl https://github.com/PainterQubits/Unitful.jl
- james2doyle 5y agoIf you're using Javascript or Typescript, there is an Eslint rule called "no-magic-numbers" which enforces a rule where numbers are required to be assigned to a variable: https://eslint.org/docs/rules/no-magic-numbers https://eslint.org/docs/rules/no-magic-numbers You can set ones to ignore, a minimum value for the rule to apply, or require the variable to be a const.
- pojzon 5y agoThis is more about units. int length = 5 Is quite different than: int lenght_in_meters = 5
- hinkley 5y agoI'm a fan of the middle ground here where you limit magic numbers to known constants and arithmetic. This means some constants don't have magic numbers, but also some inline uses don't necessarily have constants. 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?
- ttymck 5y ago60 minutes or 60 seconds?
- james2doyle 5y agoPHP mess detector has a rule for this called "Magic Number Detector" (https://github.com/povils/phpmnd https://github.com/povils/phpmnd) which will cause an error when it encounters numbers that violate the parameters you set.
- munk-a 5y agoPHP offers sleep[1] and usleep[2] which sleep for a period in either seconds or microseconds respectively. I don't know why every other programming language ever hasn't adopted this habit. (There's also time_nanosleep[3] which definitely could be better defined, but it's PHP, sleeping for some amount of time between a nanosecond and a microsecond is pretty hilarious when you're running on an interpreter). 1. https://www.php.net/manual/en/function.sleep.php https://www.php.net/manual/en/function.sleep.php 2. https://www.php.net/manual/en/function.usleep.php https://www.php.net/manual/en/function.usleep.php 3. https://www.php.net/manual/en/function.time-nanosleep.php https://www.php.net/manual/en/function.time-nanosleep.php
- asiachick 5y agoThere's a good old article about this from Joel Spolsky https://www.joelonsoftware.com/2005/05/11/making-wrong-code-look-wrong/ 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.
- AtNightWeCode 5y agoThis is good scouting. In Java there is a naming convention. In<metric>, like TTLInMillis. In C# you often use TimeSpans, like TimeSpan.FromSeconds(123). However, I see this problem more and more often for some reason.
- rpaddock 5y agoI once went in to clean up a project that was designed by a committee of people spread all over the world. The unit was large moving equipment that if something went wrong, people might die. The unit was composed of several different CPU modules communicating on a property bus. Each module's software was written by a different group in a different part of the world. 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...
- gugagore 5y agoThis is Hungarian notation. A combination of both flavors into one. https://en.wikipedia.org/wiki/Hungarian_notation https://en.wikipedia.org/wiki/Hungarian_notation. 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).
- valbaca 5y ago> Option 2: use strong types This should've been Option One
- sexy_panda 5y agoimho it's bad practise to not use SI units [0] by default. Why would you want to enter a percentage of a minute? [0] https://en.wikipedia.org/wiki/International_System_of_Units https://en.wikipedia.org/wiki/International_System_of_Units
- deleted 5y ago[deleted]
- andrewgilmartin 5y agoAlways missed Pascal’s typed scalar ranges.