9 ms·
Making Wrong Code Look Wrong (2005)
- josephcsible 4y ago> my example above where we decided that us meant “unsafe string” and s meant “safe string.” They’re both of type string. The compiler won’t help you if you assign one to the other and Intellisense won’t tell you bupkis. But they are semantically different; they need to be interpreted differently and treated differently and some kind of conversion function will need to be called if you assign one to the other or you will have a runtime bug. If you’re lucky. This is a big advantage of Rust with repr(transparent) and Haskell with newtype. With them, you can make safe and unsafe string types so that the compiler will make sure you don't mix them up, with no effect on the generated code.
- maccard 4y agoYou can do this in any language, even C
- tialaramex 4y agoC isn't very good at type correctness. In a lot of languages if I call F(some_array) it passes the array, in C it passes... A pointer to the first element in the array. C programmers, like a dog whose master kicks it when he's drink, are used to this, but it's not actually good. For this behaviour to be ergonomic you need consistent type correctness. A language which thinks 5 is true is already shaky about types, let alone one which thinks arrays are pointers.
- adrian_b 4y agoWhile I completely agree that the implicit conversions between arrays and pointers are very bad, in decades of using C and many other programming languages I have seen neither any case when 5 being true is undesirable nor any case when a distinct "Boolean" type is useful.
- samatman 4y agoI've seen plenty of cases of it being undesirable for 0 to be false, in languages which aren't C. In C, and any other language where the memory model is based on bits and bytes, it's well defined, there's no meaningful way for a value to be 'falsey', so I'd agree that a distinct boolean type doesn't do a lot. I could make a case that it lets the compiler choose the width of a boolean, but that's not necessarily good.
- Jtsummers 4y agoHaving a distinct boolean type prevents this error (fortunately detectable with linters, so pay attention to your linter output): if(n = 5) { ... } When the author probably meant: if(n == 5) { ... } In languages where the assignment statement can also be used in expressions (as it evaluates to the value being assigned) the above can create very subtle errors in a program. Having a distinct boolean means that the type system will reject that. Of course, it wouldn't reject this: if(b = true) { ... } But that's something you generally shouldn't write anyways (and, again, your linter will probably catch).
- eMSF 4y agoMany languages with distinct boolean types do not require that the condition expression in an if statement evaluates to that type, and hence do nothing to prevent that error.
- tialaramex 4y agoModern C actually has a boolean type, named _Bool (aliased bool if you ask for it explicitly) and yet sure enough despite this it figures '0', 100 and 0.1 are all truthy. Yes, what's critical here is that the only type that should be boolean true is the boolean value true, and your language is letting you down when it insists strings, or integers or some other type entirely should be "truthy" because it was easier than writing what you meant - soon or later this type laziness will bite you. I think this is more obvious in languages with pattern matching where the boolean if condition is just the world's least interesting pattern match, clearly (69, "Nice", true) doesn't match (true, true, true) as a pattern and is instead a type error.
- qsort 4y agoI don't disagree with what you're saying, but whatever (little) type safety C has can still be put to good use for the purposes of the article. The problem he's outlining is that you have two kinds of strings: "clean" strings and "tainted" strings, and you can only get a "clean" string from some kind of escaping function that returns "clean" strings. That's the typical problem you solve with types, and it's been true forever, even in old versions of C.
- DonaldFisk 4y agoThe idea in the article is to make wrong code look wrong, so it's even more important to make it easier for programmers to check code visually for errors in weakly typed languages such as C, where wrong code can easily get past the compiler. Even in strongly typed languages such as Haskell or Ada, it's still a good idea as it's useful self-documentation, and it also means you're less likely to get compilation errors.
- maccard 4y agoI didnt suggest passong pointers. C's type system is strong enough to let me do typedef struct { char* buf; int sz; } safe_string; typedef struct { char* buf; int sz; } unsafe_string; And differentiate between the two.
- karmakaze 4y agoYou don't need to reach for Haskell or Rust, you can wrap any unsafe string in an UnsafeString type that can't be mistaken for a plain string. I was hoping the post would get to saying 'make wrong code into errors'.
- MauranKilom 4y agoYou can't always encode every semantic mismatch in the type system (or be checked by the compiler in general). Although with a sufficiently powerful type system, at least the ones that are reflected in variable naming should be catchable. For example, the convention of naming your 4x4 matrix transforms AfromB leads to the following kind of composition: vecInD = DfromC * CfromB * BfromA * vecInA Here, you can very clearly spot any mismatch (e.g. if someone put BfromC in the middle instead). With the right language, you could also have each matrix source and destination reference frames encoded in the type system if you so desired. Where it gets harder to produce errors is higher-level patterns that transcend adjacent names: if (atomicVariable.read()) { /* something that assumes atomicVariable is true */ } This should invite suspicion - it is clearly concurrent code, so what prevents atomicVariable from changing right after entering the if?
- spockz 4y agoReading ad-hoc is fine if you just want to observe the value at some point in time. That is why there is room for both a “peek” function, maybe should be called “unsafeRead”, and a “withValue” method that takes a function with the actual value as argument and locks the atomic variable while executing the closure. This prevents the user from ever forgetting to write the lock.
- MauranKilom 4y ago> Reading ad-hoc is fine if you just want to observe the value at some point in time. There are such cases, indeed. Double-checked locking comes to mind. But if the code inside the if does assume the atomic to have a given value, it is almost surely wrong (absent of other synchronization mechanisms, such as in double-checked locking).
- marginalia_nu 4y agoI think this feels like the wrong place to solve the problem. I don't think you should be building HTML by concatenating strings like this. If you build a model and render it separately using a template, whether a string gets entity-encoded or not is a concern for the template, and a sane template system entity-encodes by default unless explicitly told not to do so.
- ncmncm 4y agoStrong type support is not unique to niche languages. Some very mainstream languages support strong types, too. Notably, C++. As in Haskell or Rust, you are not obliged to use them. But you don't need to wait until you get to use Rust or Haskell at work before you start. We used to say you can code FORTRAN in any language. C, too. Coding Rust does not force you to sane types. You have to choose to use them. So, choose them now.
- deleted 4y ago[deleted]
- ape4 4y agogcc's -Wmisleading-indentation will gives warning for: if (some_condition ()) foo (); bar (); /\* Gotcha: this is not guarded by the "if". \*/
- bena 4y agoI've always liked this article and 17 years later it's still really relevant. It's just good advice. It also gave me an appreciation of proper Hungarian notation. Because what Joel describes makes sense. It's kind of like embedding comments in the code. And it's type agnostic. If you want to switch from integers to floats, it can still be the difference between the the horizontal distance or dx.
- ncmncm 4y agoAs in most Joel essays, it's good advice until it's bad advice. But it usually gets there.
- dqpb 4y ago> Clean did not mean no grease. No, that’s “seasoning”
- nemo1618 4y agoThis post had a big influence on me back in the day. When I first read it, I think it was discussed here in the context of Go, which was relatively new -- people were complaining about its use of capitalization to indicate visibility, its lack of operator overloading, and the tedium of its error handling compared to exceptions. Joel makes a good case for all three of those design choices here.
- hinkley 4y agoI’ve done this a few times. Boy do some people get mad. In one particular case we had two implementations of some complex code with security implications. It wasn’t working with a new feature, and the author gave up and put me on the case. One implementation took an array, the other a single instance, a couple blocks were in different order and some variable names were different. So I diff them against each other, got them identical except an outer loop, then fixed his bug. His lead found me the next day, “why did you put this duplicate code here?” I didn’t. I just revealed it. “Oh” Three hours later, “I removed that duplicate code.” I did not temple my fingers and say “excellent” except inside my own head. And that is how I learned to use nerd sniping for good, not evil.
- rzimmerman 4y agoFor Python specifically, I'd add: Type checking with mypy is a good way to accomplish the "unsafe/safe" string case without having to pollute the variable names. It's a really good use of types in a language that will let you blast through them if you want. There's something to be said for writing code that is "obviously correct". List/dict/set comprehensions are super underrated for this. x = [str(y) for y in my_list if y > 5 and y not in other_list] You can look at that and know it's correct. Versus: x = [] for y in my_list: if y not in other_list and y > 5: x.append(y) Easy enough to check in this case but it requires checking 4-5 different common mistakes (is x initialized, append vs. extend). Also I got so caught up writing the loop I forgot the point was to cast y to a str.
- mattgreenrocks 4y agoI'd hope the article would present something that scaled better than users needing to remember what to do with u/s-prefixed variables. Response handlers needing to worry about unsafe/safe strings lowers their cohesion and hurts readability. Newtypes are an obvious solution, or a DSL that sits above the actual Response API would also be good. Luckily, since this was written, most web frameworks use some sort of templating system which probably eliminates 99% of the ad-hoc HTML from response handlers. On Hungarian notation: > Somebody, somewhere, read Simonyi’s paper, where he used the word “type,” and thought he meant type, like class, like in a type system, like the type checking that the compiler does. He did not. He explained very carefully exactly what he meant by the word “type,” but it didn’t help. The damage was done. This is the pop culture of programming: insightful advice stripped of nuance, elevated to Best Practice, and blindly repeated with the source material completely forgotten about. Said practice eventually rots away because it isn't as universal as once touted.
- goto11 4y agoNote the context. Joel is writing his examples in VBScript. VBScript was a dynamically typed offshot of Visual Basic, but did not originally give you the ability to define your own types. In any modern language you would just use a HtmlString type to wrap html, and let the compiler take care of ensuring you don't mix up encoded and unencoded strings. But absent any kind of custom types (and no HtmlString in the standard library), you had to rely on something like Hungarian notation and very carefully eyeball to code. Making wrong code look wrong is better than nothing, but making wrong code impossible is far better.
- Banana699 4y agoYes exactly, any language with zero\low cost type definitions and natural use of custom types (they don't look second class in e.g operators) would automate what Joel calls Apps Hungarian (the original Hungarian notation). In fact, good custom types would make Apps Hungarian, the useful Hungarian notation, as useless as the Systems Hungarian. This is a natural direction is programming language research, to make as much of program constraints and custom logic automatically checkable and enforced.
- avg_dev 4y agoI definitely thought, "man this is out-of-date" when I looked at this article. I'm a big fan of analysis and linting tools to catch what the language cannot, as well. You can always disable that stuff with a magic comment when the circumstances call for it.
- ncmncm 4y agoAlmost all Joel postings are exercises in "Spot the Howler". Joel's a very smart guy, but as for most very smart guys who know they're very smart, they are better at fooling themselves than anybody else could be. His justifications for fooling himself are always very, very good. It can be hard to identify the exact spot where his argument veers into the weeds. The road bends a bit, and he doesn't, and things get very bouncy and scrapy. In Joel's case, it usually is right at the point where he mentions How We Did It at Microsoft. Anything he used to do when he was at Microsoft gets a free pass against re-examination to consider whether it was totally bonkers, and repeating it would leave you with, well, Microsoft code. So when you read a Joel posting, pay attention. Usually, between lots of very reasonable stuff at the beginning, and a totally bonkers end, there is just one spot where he says something that reads a lot like the reasonable stuff before it, but fatally taints everything after. Sometimes there is more than one, but by that point it is too late anyway.
- Banana699 4y agoWhere the Howler here?
- goto11 4y agoThere is certainly some faulty reasoning in: > I don’t like exceptions because they are, effectively, an invisible goto This is supposes to invoke dread because everyone knows goto's are evil right? But if any jump to a different place in the code is a goto, then if/else/while are also goto's, and so are functions and returns.
- kazinator 4y agoMy main take-away is that I'm still convinced that exceptions are the best invention since the chocolate milkshake and don’t even want to hear any other opinions.
- ncmncm 4y agoYes. The universal complaint, among exception complainers, is "I don't know if an exception might happen here." Easy: yes, it might; code accordingly. Cleanup code goes in destructors, where it gets well exercised on every run, exception or no. If you need a type to have the destructor for, make the type.
- Groxx 4y agoIf you want even better escaping safety: use different types for safe vs unsafe strings. You should not ever be crossing the streams. So make it a compile-time failure. And anywhere you truly do know better, you can just use a transformation func like `safe = iKnowWhatImDoingCompilerSTFU(unsafe)` And keep in mind that "escaping" is not a binary. Something that works in an HTML node's body may not work in an attribute or a request header or a URL. This is the primary reason that most things suggest escaping at output time: you cannot safely escape something without knowing where it will be used.
- jffhn 4y ago>Look for coding conventions that make wrong code look wrong. Or code more readable, and more obviously right or wrong. A few I use : - always suffix with the unit, for quantities for which we are likely to not always use SI units (ex.: time ("double timeS" for physics, "long timeNs" for low level scheduling, etc.), angles (latRad, latDeg, etc.)) - lists/sets of Foo named fooList/fooSet by default (or xxxFooList, etc) - Map<Foo,Bar> : barByFoo - Foo[] : fooArr - return value : ret (some use "result", but it's longer to type/read, "ret" is more obviously related to "return", and a result can just be intermediate and not something to return)
- ncmncm 4y agobarByFoo is a very good convention when there is, as often, only one. The others, not so much. It might be a set today, but not tomorrow. Degrees is a good type for variables you keep degrees in.
- jffhn 4y agoWe don't want to be too abstract, to get a feel for what we are doing, especially for collections and their different and possibly touchy algorithmic complexities, but if it makes sense we can use fooColl to reference a set as a general collection, for parts of the code that work well with any collection.
- ncmncm 4y agoI have seen "fooz" used for that, the "z" to disambiguate from "foos" that might be a numeric count of foo.
- cpeterso 4y ago> return value : ret Fun fact: Rust's return keyword was originally spelled "ret" (because, IIUC, Rust designer Graydon wanted all keywords to be <= 5 characters). Enough people complained that "ret" was too ugly and unnecessarily breaking precedent from other languages, so it was changed to "return". I don't like "ret" because makes me think of "retch" :) but you make a good argument for using it for return values. Mozilla's coding style typically uses "rv".
- astrobe_ 4y agoI only read TFA around the code examples, so please ignore if this point is addressed. The problem I see with this strategy is that it relies on the programmer or the reviewer paying attention. If I learned something about writing programs in C, assembly or Forth is that is not enough. Code reviews are great but part of a "defense in depth" strategy, meaning that it has a good cost/benefit ratio at the cost of reliability (the ideal solution being formal proofs but not every shop can afford that). Before relying on naming conventions, and when the language won't help you, there's another strategy to be tried: to not let the mistake happen. There's no general solution, though. In this case I would mostly prohibit the use of "dangerous" functions, like this Request(). With C, sometimes teams make it so that dangerous functions such as strcpy will throw an error at compile-time. Same idea; there's most certainly tools for that. Request() would appear in a few places, so that it would trigger the attention of the reviewer. So I would have e.g. a GetField() function that would do Encode(Request(param)) and that would be one of the few functions in the program where Request() is used. Next, there are cases where you need both the "safe" (encoded) and "unsafe" (raw) version of the data. In this case, I would try my best to "jail" the unsafe version in a lexical scope, most certainly a function. This way you don't let the "poison" (the unsafe string) circulate in your system, just like you perform parameter validations at the top of the function, rather that at each use; that would be the equivalent of relying on hungarian notation, in my eyes.
- goto11 4y ago> Simonyi mistakenly used the word type in his paper, and generations of programmers misunderstood what he meant. Simony actually distinguish between two meanings of "type": (1) A set of valid operations for a value (2) The storage representation of a value For example he suggest the "sz" prefix for a pointer to a zero-terminated string and "st" for a pointer to a length-prefixed string. Both are represented as the same storage type (a pointer), but obviously different operations are valid on them. Hungarian notations is a way to represent types-1 in a language which only support types-2. It is obviously bad to mix up the two kinds of string-pointers, but since the type system cannot represent the distinction we have to use Hungarian notation and then very carefully review the code to make sure the operations conform to the type-1 type. But the types which Simonyi encoded in the variable names is clearly what would be represented as types in modern languages.
- n4jm4 4y agoClean code in management's eyes is anything at all delivered COB whose customer-deleting latent bugs trigger six months after the author left to work elsewhere. But with 100% code coverage!