87 points · by ingve · 4y ago · 99 comments
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.
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.
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?If I read that I'd assume the block cares not that atomicVariable is true but only that it was, at least briefly, true.
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.
A much better idea would be to give that information to the compiler, so the developer can get a useful error if they try to do something unsafe. We should try to turn these onto compiler errors as much as possible so if a developer does something bad, it wont even compile. This seems like a much more fool proof way to accomplish what the author is trying to do.
(And the kind of technique described here still matters because you should understand why the guardrails are where they are.)
That results in a cultural difference (new type idiom) that makes UnsafeString viable while in some languages you could do it but you wouldn't
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.
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.
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.
typedef struct {
char* buf;
int sz;
} safe_string;
typedef struct {
char* buf;
int sz;
} unsafe_string;
And differentiate between the two.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)
always suffix with the unit
Heck yeah. One of the few things in this godforsaken industry/craft that I consider to be unambiguously true. for quantities for which we are likely to not always use SI units
Do you mean "likely to not always use SI base units?" Second and millisecond are, for example, both SI units.Regardless, I think it's worth suffixing all variables with unit type regardless of SI base units or not. This is particularly true for large and/or long lived projects with multiple developers.
Developers are almost always the limiting factor in any development effort.
Therefore, always prioritize reduction of developers' cognitive load unless there is some specific reason not to (ie unrolling a loop for performance reasons, etc)
The only arguments against longer identifier names are non-issues:
1. "They're harder to type." If you're using a code editor without autocomplete in 2022, that's on you.
2. "If I use long identifier names I can't fit as much code on a line." Bit of a coding style smell if this is an issue, IMO.
Autocomplete is nice but in my IDE it requires hitting ctrl+space and then you might have a choice to make.
Degrees is a good type for variables you keep degrees in.
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".
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.
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.
This is a natural direction is programming language research, to make as much of program constraints and custom logic automatically checkable and enforced.
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.
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.
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.
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.
if (some_condition ())
foo ();
bar (); /\* Gotcha: this is not guarded by the "if". \*/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.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.
make_html("<p>Hello, %1</p>", userName)
The % interpolating notation can support an operator for the rarer situation when you want to opt out of HTML escaping.This is still textual: get the string wrong and you get wrong HTML. You really want structural templating. It could use HTML syntax, but as a HTML quasiquote that is parsed.
Other people posting here have noted that using our language's type system intelligently is how we make trouble fail to compile. Counting on our and our colleagues' finely-tuned sense of rightness to keep out bad code is a recipe for having Bad Code. It suffices to explain Microsoft.
> 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.
Control structures and function calls are a very statically-well-behaved control flow: unlike gotos, when you see a jump you know exactly where its destination is (runtime polymorphism for functions\methods is... an exception, and that's why some people don't like it.), unlike a goto where that might be a dynamic address. The Return is the only modern goto with a dynamic destination, but even then the destination is not completely arbitary (stack discipline), and actually the destination is irrelevant if the function is a well-named non-leaky abstraction, the function simply returns to its "caller", wherever it may be.
Furthermore, traditional control flow is Structured, it "owns" its jump labels. Nobody can jump to an else clause of a conditional except that conditional, nobody can jump to a loop start except the code immediately before it or the loop end (breaks and continues are, again, limited exceptions to this, and that's why some people don't like them), only the Returns of a function can jump back to the callsite of that function. As utterly trivial and basic as that sounds, it's a marvel. Gotos are nothing like this, they jump to public labels, anybody can jump to the label, it's a communism of control flow.
Exceptions break all of that. You don't statically know what's the destination of a Throw is, and unlike a Return, the destination is not irrelevant, the program is disrupted, you really need to know where that Throw is going to end up. Throws don't own their catches as well, any Throw can jump to the same Catch.
In a very real sense, Exceptions are more dangerous gotos than ifs and whiles.
No, that’s “seasoning”