• Naomi (unregistered)

    Oh, that brings me back to my uni days. I was asked to help out an introductory C++ course taught by a new professor (I worked for the tutoring center and we came up with a program where instructors could request help for whatever reason). One of the first things we realized is that the materials he'd inherited were terrible - half the examples wouldn't even compile, they focused way too much on being technically correct at the expense of clarity, there were no "real world" examples to contextualize why you might care about the constructs being discussed, etc., etc. Just rewording the slides to focus on what beginning students actually needed to know had a huge impact on the students' learning outcomes, and I think we managed to bring the class average up from a D- to a B by the end of the semester.

    I miss doing that.

  • CdrJameson (unregistered)

    For me a problem with example code is it teaches people to write really short code lines, and skimp on whitespace because that's that will fit best on a printed page. I think that's why otherwise sensible seeming people seem to use K&R style braces.

  • Sole Purpose Of Visit (unregistered) in reply to CdrJameson

    If the only problem you have is K&R bracing style ... now, you have zero problems.

  • Jupp3 (unregistered)

    Of course there's also the assumption, that every non-Windows platform in existence has alloca(size);

  • 516052 (unregistered) in reply to CdrJameson

    You mean the disgusting brace style where they are placed at the end of a line instead the beginning of a new line? If I ever get to teach a class that is going to be automatic failure right there.

  • Alistair (unregistered)

    If the code is indented correctly, it does not need braces.

  • Anonymous') OR 1=1; DROP TABLE wtf; -- (unregistered)
    usr.id = Math.random().toString(36).substring(2);
    

    This generates a random floating-point value between 0 and 1, converts it to a string in base 36, giving a value like "0.d46k0hjr9k", and then drops the leading "0.". Yes, it works, but it's super-weird.

  • (nodebb) in reply to CdrJameson

    I think that's why otherwise sensible seeming people seem to use K&R style braces.

    You are absolutely correct. People use the K&R braces because the book that the first generation of C programmers learned to program C with was The C Programming Language by K&R and they naturally tended to copy the style in the book. I learned C from that book, but I came from having just learned Pascal so I saw immediately that K&R style is a steaming pile. Nobody else with any other block structured language (not depriving its syntax from C) ever came up with such an obnoxious way to format blocks.

    I charitably assume that they were trying to save vertical space since terminals in those days were restricted to 25 (24 really, with vi) lines. That restriction no longer applies, so I say align your damn braces.

  • 516052 (unregistered) in reply to Alistair

    In principal you are correct. But it's one of those things that I find works great in perfect conditions but not so much in the real world.

    Once you start getting away from small code files and short snippets and into the world of functions several hundred lines long and code files the size of small books written and edited by generations of developers each with their own code style having a hard delimiter character around each block becomes priceless.

    At least that's my experience.

  • Daniel Orner (github) in reply to 516052

    (just wait till he sees Go code where that style is enforced by the compiler...

  • seebs (unregistered)

    I think at this point the "you should definitely use exceptions" advice is starting to look like itself being a WTF.

  • Junkfoodjunkie (unregistered)

    And... The first code example isn't bad because they create a user id in javascript code, instead of just doing autoincrement in the database? Who does that?

  • DaveD (unregistered)

    What are the chances of Math.random().toString(36).substring(2) generating a dulplicate value? It isn't exactly a GUID.

  • Richard Brantley (unregistered)

    Honestly...I really don't get the war over where to put the braces. it's a detail, and frankly not one I find very important.

    Languages don't just have syntax, they have culture. When I'm writing JavaScript I put the opening brace at the end of the line, because that's the commonly accepted style in that culture. When I'm working in C#, I put the opening brace on a new line, again, because that's the prevailing culture for that language.

    For legibility I feel it is more important to conform to the dominant culture of the language because that's what other programmers in that language are likely to expect. I've been in shops where somebody spent several days editing every file in a project to change the style of this one thing...and created a nightmare merge problem for everyone else on the team. And this does mean that if I'm on a C# team that's doing K&R instead of the commonly accepted practice, I will follow K&R, in order to be harmonious with the team.

    Now if they're still doing Hungarian Notation, we're going to have a chat.

  • Duke of New York (unregistered)

    The best formatting style is one that the current project or organization has adopted, even if that is K&R (which, if you were more enlightened and practical, you would understand is not worse than whatever unique snowflake style you prefer).

  • Barf4Eva (unregistered) in reply to seebs

    dude... right? I can't believe I just read that.

  • jay (unregistered)

    One thing I really hate about examples in tutorials is when the example is way more complicated than is necessary to illustrate what is being taught. For example, a company I worked for bought a gadget to read credit cards. It came with a tutorial on how to use it. Great. Except ... If I was writing the example, I would have written code that, like, read the card and displayed the relevant information. Period the end. Their example displayed all sorts of animated graphics, advertising for their other products, linking to their web site to get information to populate the ads, etc. I had to wade through pages and pages of code to get to the part that actually read the card. And then I had to figure out what parts of this code were actually related to reading the card and what was to display the graphics and the advertising. It was maddening!

  • jay (unregistered)

    RE "this example is too simple to need comments" Well, I'd expect an example in training to be simpler than a real-world problem. Would you really want them to put together 100 pages of cryptic code just to illustrate what comments should look like?

    That said, what really drives me crazy is when someone writes cryptic code and gives no comments to explain it, and then writes a comment for something blindingly obvious. I once saw a line of code -- I am not making this up -- that said

    x=x+1 // add 1 to x
    

    Like, wow, thank you for explaining to me what the plus sign does! I'd forgotten that and there's no way I could have guessed such a subtle programming technicality.

  • Sole Purpose Of Visit (unregistered)

    Without wishing to delve further into K&R parenthetical stylings, I would just point out that things get messy with Javascript and TypeScript and apparently Go and Dart and probably huge numbers of web-footed languages. Why? I don't know. I particularly fail to understand why anybody would ever write a language parser that uses different varieties of white space to differentiate between different semantics of parenthetical usage.

    Still, there we go. As commenters above say, if the flow ain't broken, go with the current flow.

    And we seem to be drifting. Ignoring Remy's usual idiosyncratic approach to exceptions, he has a real point with the "sample code." I've been programming in C for twenty years, and I've never used alloca. Why not? Because I was taught to use malloc which (without checking my C references) is guaranteed to put things on the heap. There may be cases where you want to allocate things on the current stack frame, although to be honest I can't imagine any such case outside, say, the kernel, but the comment in this case is plain wrong.

    As Remy says, it's telling you to do precisely the opposite of what you should do. And the icing on the cake is the cretinous ifdef (which might at least be wrapped in a preprocessor macro, if you really have to make platform-dependent choices).Want to make a really rotten choice? Here, we'll give you the option to make two really rotten choices in addition. Mind-blowing stupidity in a theoretically canonical example.

    It would actually be an excellent tutorial on how to read pre-existing C code for potential vulnerabilities, if only it were done right. Not that those vulnerabilities would have anything at all to do with security, unless you count an internally-generated random brain fart over the memory model as a DoS, I guess.

  • jay (unregistered)

    All these people talking about K&R C is giving me warm fuzzy thoughts about punch cards and ASR 33s.

  • Airdrik (unregistered)

    I promise not to pick on training materials too much

    I'd like to get the reasoning behind this, because really, training materials should be exemplary, clear and concise. I suppose you could give them a pass because they aren't intended to be used as-is, but only to demonstrate or highlight certain things you should or should not do. But insofar as they fail to convey what they are intended to convey or they present bad practices and WTFs as being exemplary, we really should hold them to a higher standard than we do the rest of the code that we write.

    People are going to use the example code provided in the training materials, and while scrubbing the code to make sure it meets accepted standards is expected before shipment, it isn't guaranteed; but neither should it be necessary if the example were written to meet those standards the first place.

  • Tulaska (unregistered)

    The first one, just do user.save().

    The second one, I always think of pointers like desktop shortcuts. Your computer responds to input by booting up, creating a desktop shortcut to C:\file, returned that shortcut as output, and shut down.

    Education is about behavior. Get the jerks out of here. Notify everyone about the psychos. Last lesson is no one has an answer. Choose your own sunset. The tighter the education, the more likely you are going into a real hostile work environment. And you don't have to if you don't want it. The job is actually easy when you start getting other people out of your head.

  • Peter of the Norse (unregistered)

    It’s likely that the JS example is out of date, but you have to remember how buggy IE was about some of these things. I just saw that MDN says that it was fully supported in IE 5, but I know I kept running into bugs with IE 7 that made me never want to use them again. It’s possible that this is how people learned it because it could still run on some XP boxes.

    Also, as someone who worked on FORTRAN 77, all this discussion about brace style is funny as hell.

  • (nodebb)

    _malloca can raise a stack overflow error I thought the point of _malloca was that it would allocate memory on the heap to avoid causing a stack overflow error...

    (never mind that it misses the point of stack allocation altogether by requiring the use of a freeing function due to this)

    Addendum 2021-12-17 03:22: Ugh, forgot to add an empty line at the actual end of my quote. When are we getting a preview feature?

  • CdrJameson (unregistered) in reply to Richard Brantley

    I work in both styles, because of dominant code conventions, and I find it just emphasises why K&R is still fine but has several annoying quirks when I see lines like these:

    if ((complicatedCondition > someOtherThing) && (anotherComplicatedCondition === somethingElse)) { // Nasty elision here someCodeStartsHere; and some more; }

    or

    if (thing) { code } else if(anotherthing) { code }

    and I want to simply comment out the 'else if' block for a quick test.

    Small things, but they add up.

  • löchleindeluxe (unregistered) in reply to Junkfoodjunkie

    I think enumeration vulns are in the OWASP top 10 now, but I'm too lazy to check.

  • Duke of New York (unregistered)

    _malloca is not missing any point. You've just misunderstood what it was made to do: allocate an arbitrary amount of function-local memory with a performance optimization for smaller amounts.

  • (nodebb) in reply to Duke of New York

    My opinion on stack allocation may be colored by the fact my first encounter with alloca() was in a macro that relied on its later automatic release way more than it relied on performance.

    So to me, the point of alloca() is that you don't have to release it yourself. A purpose for which _malloca is useless (and for which C++ is better suited, but when you don't have C++...).

  • Jan (unregistered) in reply to 516052

    "You mean the disgusting brace style where they are placed at the end of a line instead the beginning of a new line? If I ever get to teach a class that is going to be automatic failure right there." Why would I waste a line just for the opening brace? The line after the control statement is indented, you'd have to be braindead to need an opening brace there. I hope you do not teach! Anyone! Ever!

  • Officer Johnny Holzkopf (unregistered) in reply to Jan

    Currently we're all being taught to be friendly to the environment, to preserve nature, to work efficiently ("smart, not hard") and to follow rules ("do what management tells you to do, and don't ask questions"). So wasting single lines just for opening braces shows a much more significant problem of byte waste: indentation, and depending on if you indent with spaces or tabs or spaces and tabs (prepare for further flamewar), that's lots of bytes wasted. Even worse, if you code on Windows, it's an additional byte from the 2-byte linebreak. We can do better. The C compiler doesn't need indentation and newlines, so why should we? Aren't we better than the machines? Well... in fact, things just get worse, we don't learn from our (and other one's) mistakes, as we can see every day (cf. "your company's app"), and as we all know, it's just ones and zeroes at the end...

  • 516052 (unregistered) in reply to Jan

    It's an usability thing. Blank lines and whitespace in general are not just an aesthetic choice. They exist to help our brains parse the image it is receiving into distinct chunks that should be processed together.

    That is why we add whitespace at the end of sentences (each representing a single thought) and paragraphs (which represent a collection of sentences all serving a common whole). Whitespaces is what tells our brains to stop loading data and process before moving on.

    You can see that easily by reading other peoples code or indeed just regular text. Proper use of visual separators to split a paragraph into multiple where appropriate not just can but is the difference between a text that's easy to read and understand and an unmanageable text wall.

    And this is where we get to brace styles. Braces are a visual delimiter, just like newlines and whitespace. And as delimiters their placement directs what they have to say.

    Having a brace on a new line immediately draws the eye to it with a loud "HEY THIS IS THE START OF A BLOCK" just like having a blank line between two paragraphs. Having it on the same line just isn't as good at this.

    Consider the text I wrote above, but substitute every blank line with a tab at the end of the last one. For example:

    Having a brace on a new line immediately draws the eye to it with a loud "HEY THIS IS THE START OF A BLOCK" just like having a blank line between two paragraphs. Having it on the same line just isn't as good at this. Consider the text I wrote above, but substitute every blank line with a tab at the end of the last one. Yes, you absolutely can train your self to read that but it is suboptimal.

    Yes, you absolutely can train your self to read that but it is suboptimal.

  • Gordon JC Pearce (github) in reply to 516052

    Curly brackets on their own line is a defect. Anything other than K&R is out of spec.

    Anyone who puts curly brackets on their own line should probably get out of programming.

Leave a comment on “A Learning Opportunity”

Log In or post as a guest

Replying to comment #:

« Return to Article