9 ms·
Making Wrong Code Look Wrong
- CJefferson 15y agoI agree with all of this, except the operator overloading rant. Unless of course we extend it to forbiding overloading of any function name for more than one type. I have done a bunch of mathematical programming in java, and you end up writing ".add()" a lot. Maybe .add is on a finite field. Maybe it is some matrices. Maybe complex numbers. I don't see what I am saving over operator overloading. Of course, if I used .addFiniteField, .addMatrix, .addComplex, then I can see the (possible) benefit, of knowing how "heavy" the operation is at a glance. However, I don't think it is worth the cost, given I lose genericness.
- robfig 15y agoIt sounds like you would use operator overloading for exactly what it was meant for (and good at)! I think the usual complaint is that people use operator overloading for non-mathematical operations. For example, a guy doing a webapp might overload the "+" operator for Group and User as a clever way to add a User to a Group. This turns out to be a terrible idea. In fact, my eyes glaze over as I read Scala code for this very reason, because everyone and their mother defines a method with some random array of symbols because it makes sense to them and they prefer shorthand. It makes the code totally unreadable.
- CJefferson 15y agoYes, that aspect of operator overloading is nasty. I think one thing that makes operator overloading worse is that there are few reasons to use 'add()' rather than 'addUser()', but once you decide to use operator overloading, there are limited options. C++ libraries which do abuse operator overloading (see the boost::spirit parser library as the best example) have this problem. For example, spirit wants to define the standard '' and '+' parsing operators. However 'a+' and 'a' aren't valid C++, while '+a' (unary +) and '*a' (dereference) are, so those are used.
- scott_s 15y agoSpirit doesn't bother me, although it's a glaring exception I did not think of to my above response. Its use of operator overloading doesn't bother me because that's the whole point of the library; you know what you're getting into ahead of time. It let me write EBNF code directly in C++: https://github.com/scotts/cellgen/blob/master/src/cellgen_grammar.cpp#L336 https://github.com/scotts/cellgen/blob/master/src/cellgen_gr... The Spirit code is unlikely to be mixed in with other code. Or, put another way, I was never bothered by your complaint, because I always read it as EBNF notation first. My real problem with Spirit was performance. It took three minutes to compile a 7000 line C++ program - more with optimizations turned on. The binary with debugging information turned on was 24 MB. And the enormous amount of copying it performed at runtime meant parsing 300 line files took a few seconds. (Luckily the runtime performance of my compiler was never important.) The new version may have fixed these problems.
- scott_s 15y agoThat's the perennial complaint and worry, but in my experience, people use operator overloading in C++ for mainly two things: function objects by overloading operator(), and iterators by overloading the dereferencing operators and increment operators.
- xyzzyz 15y agoAt any given place, people use at most 30% of C++ features -- the bad thing is that these 30% subsets usually overlap only a little. People use operator overloading in C++ for all the crazy reasons, like I/O, for instance -- for even better (or maybe worse) examples, see boost, boost::lambda will be a good starting point. Good abstractions are good, but operator overloading combined with templates and implicit casting is not one of them.
- scott_s 15y agoshrug People always talk about it what can happen, but I've never seen instances of operator overloading in C++ that I objected to in a fundamental way.
- xyzzyz 15y agoiostream, for one. It's a real pain to deal simultaneously with this fancy bit-shift I/O syntax on the one hand, and i18n on the other -- fancy syntax is way inferior to format strings when you want to support multiple languages. Also, please, take a look at the boost::lambda or other boost libraries -- they have large DSLs written on top of operator overloading which look nice when you look at them, but are terribly complicated to use and ridiculously hard to debug, thanks to the completely unintelligible messages that the compilers produce. Most probable reason you've never seen it, is that most sane, experienced people know the danger and avoid it. When there's more than one person working on a project, it's way more important for the code to be easy to follow and debug than to look fancy.
- scott_s 15y ago
- eru 15y agoOcaml and especially Haskell have more sane policies towards operators. You can make up your own operators. That's not always readable, but at least if you see some funny symbols, you know that you have to look it up. With Haskell's typeclasses (and I guess Ocaml's Functors should allow the same) you can have the functions of the same name that work differently for different types. E.g. there's a Show-typeclass, whose instances have to provide a `show :: a -> String' function. The Num-typeclass includes operators such as `(+) :: a -> a -> a', which means that + always takes to arguments of the same type and returns the same. So you wouldn't be able to overload + to add a user to a group. You might come across somebody writing (+!) :: User -> Group -> IO () for adding a user to a group (in an un-idiomatic way). But at least there's a funny symbol to alert you, instead of a re-used normal one.
- kolektiv 15y agoMmmm, but there's more than one way to skin a cat. To take just the point about safe and unsafe strings - well, you could do that with naming conventions, sure. But then you've got a peer review issue. It helps, but it's not great. So the next thing (in a language which lets you use types in this way) is to create a type of UnsafeString, or SafeString etc. And your language doesn't even have to be that great to let you do this - just having a simple type system. And now you change your write method so it doesn't take a String anymore, it takes a SafeString, and only a SafeString. And you make it so that constructing a SafeString can only be done by Encoding at some point. Now you have something which can still look clean (how clean may depend on your language, type inference, etc.) without bringing in messy pseudo-Hungarian-ness, which stops me doing the most important thing with my code - reading it easily. Obviously it's only a silly and trivial example, but I'm not sure this article has dated that well in some regards (or perhaps only really applies to certain types of languages - Visual Basic, for example, pretty much forces you to do something like Hungarian to maintain any semblance of sanity long term).
- eftpotrm 15y agoThe downside of that approach though is that you end up wrapping the bulk of the API functions you're using to make them conformant. You've got a huge amount of extra work creating and maintaining these components, and a major training workload for any new hires so they know why they can't use the standard options they're used to and what the internal replacements are. Personally, I'd rather go Hungarian. Edit - well, yes, you may well be able to do this sort of thing nice and easily in Haskell, but I'm not sure that going with Haskell to avoid the training and maintenance overhead of complicating your Java (or whatever) is a net reduction in workload and hiring difficulty...
- yummyfajitas 15y agoThis is a Java/Python/etc problem, not a fundamental one. In Haskell, the wrapping process is merely an application of liftM: type UnsafeUserGenerated = UserGenerated a instance Monad UnsafeUserGenerated where ... (monadic boilerplate skipped)... apiFunction :: String -> String funcOfUnsafe :: U -> UnsafeString funcOfUnsafe unsafe = (liftM apiFunction) unsafe
- jws 15y agoMy combinatorial explosion detector is going off. Encoding a 'u' into variable names for "unsafe" strings and omitting it for ones that have been encoded safely for HTML bodies is nice. If this is the only problem to solve and you can universally apply this technique then it solves the "NUL terminated string of the 2010s", and I may use it but… What about encoded safely for URLs? What about encoded safely for use as a Unix file name? What about encoded safely for SQL? (yes, don't do that, I know). How about encoded safely for 7 bit ASCII only applications? How about the output of base64? It isn't unsafe for HTML, but it is for URLs. What about that bit of HTML that the user entered using their WYSIWYG field that needs to be sanitized but not encoded? 'u' seems right, but Encode(uVar) isn't the proper handling. How about that library that doesn't know the convention, so its function calls all look like they are encoded safely for HTML since they don't start 'Us'? What about the library that used 'u' for UTF-8? (Oh, and… dosomething() cleanup() … is broken. Requiring a caller of dosomething() to remember to cleanup() is about as polite as leaving set bear traps in your living room furniture and reminding guests to check under the cushions before they sit. Programmers are used to that sort of abuse (Remember to fclose() what you successfully fopen()), but the future should really provide use with better constructs, and it not being 1980 anymore, we are the future.)
- al_james 15y agoYes, exactly, the meaning of 'safe string' depends on its context. I personally believe that all code that is sensitive to escaping issues, should be escaped on output (or storage / sending to the database / whatever) by default unless you explicitly opt it out. In our framework, we maintain 'already escaped' strings as a separate class, forcing the developer to acknowledge this fact. The HTML output layer escapes all strings unless they are instances of this safe class. Similarly for the SQL layer, all code gets quoted unless it was explicitly marked as 'safe'.
- eru 15y agoDo you treat SQL queries as strings in your code, or do you build something like an abstract syntax tree?
- blakeperdue 15y agoOff the topic of unclean code, but there are some great Spolsky articles that are more business-oriented on Inc's site: http://www.inc.com/author/joel-spolsky http://www.inc.com/author/joel-spolsky
- ori_b 15y agoAlso know as "How to put a second type system into your language". Personally, I prefer to have the language type system handle it.
- perlgeek 15y agoNonono, the real solution for the HTML escaping problem is to use a template system which defaults to escaping all variables. Using a naming convention is much less robust. If you need to pass in something that doesn't need to be escaped, you switch off the escaping explicitly (`<% var name ESCAPE=NONE %>`), and/or you put HTML strings into a separate type which doesn't get escaped upon substitution. For example the template engine would return a `HTMLString` instead of a `String` object, so that it never accidentally encodes twice (as could happen in the case of includes).
- rlpb 15y agoTaking this even further, an HTML templating system that involves supplying syntactic HTML as strings is fundamentally broken. Ideally you'd never provide a string that ends up as syntactic HTML. You'd build up a data structure that represents your output and a serializer would do the rest, escaping everything correctly since there would be a type-based distinction between HTML structure and element content. Genshi is an example of a templating system that works on data rather than syntactic string snippets.
- perlgeek 15y agoLive isn't always that simple. For example sometimes you get a piece of HTML that you have to include verbatimely for policital reasons (ad banners come to mind that need to be included character by character because of the Terms of Service - see AdSense for example). In that case you really need an option for direct, unescaped HTML inclusion. Or you might need to hilight the a syntax that's hard to parse, and the only available hilighter spits out HTML pieces instead of parse trees. My point is that a template system should be able to deal with such realities, and it doesn't make it "fundamentally broken".
- nasmorn 15y agoAlso while you can build a company on the motto "People feeling uncomfortable with a HTML generation library have no business adding a list tag somewhere" there are certainly cases where it makes sense for them to do so.
- raganwald 15y agoFolks, please do not fall into the simple error of arguing whether Haskell’s typing beats Hungarian notation. This would be bikeshedding. The safe/unsafe strings are given as an example, the larger point he is making is about using coding conventions to highlight potential semantic errors. Every program is going to have some kind of semantic problem that cannot easily be fixed with compile-time analysis. Unsafe strings in web applications are merely one example for one class of programs written in one class of languages. If you grasp what he’s saying about coding conventions, ignore the example. So to his actual point: Do you agree with my contention that there are always going to be some semantically wrong bits of code that cannot be automatically detected by the compiler, or that it is awkward to do so? If so, do you think coding conventions help more than they hinder? In other words, do they increase code safety without imposing too much of a burden on readability?
- kolektiv 15y agoOK, reasonable point, I had only mentioned that example in another reply because that was the one he used. Do I agree that there will always be semantically wrong bits of code that can't be detected by a compiler (whether as part of a type system or otherwise)? I'm not sure I do. OK, sure, it's probably possible to come up with some contrived examples that fit the case, but generally? No, I think that most problems are more tractable if looked at as a language design issue (be that literal language design, some form of internal DSL, or other) than as a convention issue. And surely bringing up something like Haskell is germane? The article implies that this is the best/only/right way of dealing with issues like this, when that definitely isn't true for languages with a different/stronger type system, as one case. Of course, this is pure opinion and supposition on my part - I suspect a proof either way is NP-BloodyImpossible. I do feel like coding conventions such as those he suggests make code harder to read, even if only a little bit. And that's ignoring IDE support as well - I feel the same if I'm in Emacs. If there are enough things in scope that I can't hold in my head the relevant [meta] information about them for that usage, that's a problem for me, probably of quite a different kind.
- raganwald 15y agoIf there are enough things in scope that I can't hold in my head the relevant [meta] information about them for that usage, that's a problem for me, probably of quite a different kind. This is a brilliant observation, thanks. Reminds me of Yegge’s observations about large codebases being like dirt, and the more dirt you have, the more machinery you need for pushing dirt around, and the more people, and the more systems for managing people and dirt-moving machines, ... And the better way forward might simply be to have less dirt. http://steve-yegge.blogspot.com/2007/12/codes-worst-enemy.html http://steve-yegge.blogspot.com/2007/12/codes-worst-enemy.ht...
- Cushman 15y agoI've been doing something a little like this in CoffeeScript for a while. For those who don't know, CS adopts Ruby's style of string interpolation ("formatted #{string}"), and like Ruby, only applies it for double-quoted strings. My policy is to only ever compose strings using interpolation, and to only ever write double-quoted strings when they contain interpolation. String literals are strictly single-quoted. That way, I know that single-quoted strings, which is most of them, won't ever involve user input, while double quoted strings get a little extra scrutiny. It's not XSS protection by itself, but it's a useful little way to increase the odor of the code one way or another.
- gwern 15y agoFor those curious, the way one would do this in a language with a better type system (or objects) would be some sort of opaque object/type which you can't peer into, and which provides a function/method to extract the String within and which also sanitizes it along the way. So for Java, you might have a class with the String stored as a private variable and the obvious getter/setter methods. In Haskell, you'd have a newtype with similar functions. (Can this be done in C? I don't know.) A close approximation to Joel's example (string sanitation) in Haskell with newtypes: http://blog.moertel.com/articles/2006/10/18/a-type-based-solution-to-the-strings-problem http://blog.moertel.com/articles/2006/10/18/a-type-based-sol...
- olavk 15y agoFolks, you are all missing the context of the article. He is writing in VBScript - a now obsolete stripped down version of VB. It was created as an alternative to JavaScript, but was much more limited in its OO capabilities. VBScript was kind-of-OO in that is allowed you to consume objects, but it didn't initially allow you to define your own classes. So you are working in a language which don't allow you to defined custom types. You can work with built-in types like strings and integer, but if you want to add "metadata" to these basic values, you can't do it in the type system. Hungarian notation is a perfectly legitimate solution given those constraints. The distinction between "Systems" and "Apps" Hungarian also makes sense in this context. Systems Hungarian encodes the name of the built-in types. This made sense in BCPL (where it originated), but is cargo cult in VBScript, where this is already expressed in the type system. Apps Hungarian allows you to express "custom types" which is not expressible in the type system of VBScript and therefore makes sense. But it is cargo-cult programming in any language which allows you to create custom types or objects. Which is basically any other modern language. (The thing about exceptions being "invisible gotos" also makes sense in the context of VBScript, where exception handling was done through statements like "On Error Goto..." and "On Error Goto Next".)
- lucisferre 15y agoHow in the world are people still making the front page with years old Joel posts? If you want to read this stuff go visit his blog and read it.