Ask Slashdot: When Do You Include 'Unnecessary' Code? (sas.com)
"For more than 20 years I've been putting semicolons at the end of programming statements in SAS, C/C++, and Java/Javascript," writes Rick Wicklin, a researcher in computational statistics at SAS. "But lately I've been working in a computer language that does not require semicolons. Nevertheless... I catch myself typing unnecessary semicolons out of habit," he writes, while at other times "I include optional statements in my programs for clarity, readability, or to practice defensive programming." While Wicklin's post is geared towards SAS programming, Slashdot reader theodp writes that the question is a language-agnostic one:
...when to include technically-unnecessary code -- e.g., variable declarations, superfluous punctuation, block constructs for single statements, values for optional parameters that are the defaults, debugging/validation statements, non-critical error handling, explicitly destroying objects that would otherwise be deleted on exit, labeled NEXT statements, full qualification of objects/methods, unneeded code from templates...
He's wondering if other Slashdot readers have trouble tolerating their co-workers' unnecessary codes choices (which he demonstrates with a video clip from Silicon Valley). So leave your answers in the comments. When do you do include 'unnecessary' code in your programs -- and why?
He's wondering if other Slashdot readers have trouble tolerating their co-workers' unnecessary codes choices (which he demonstrates with a video clip from Silicon Valley). So leave your answers in the comments. When do you do include 'unnecessary' code in your programs -- and why?
Thank you for being a friend
Traveled down the road and back again
Your heart is true, you're a pal and a cosmonaut.
And if you threw a party
Invited everyone you ever knew
You would see the biggest gift would be from me
And the card attached would say, thank you for being a friend.
All of my code is unnecessary, you insensitive clod!
I'll add extra intermediate variables, break up lines to make them as short as possible, and use extra verbose variable names along with explanatory comments of the logic of each object/function. The goal is to make it so that anyone reading the class for the first time with no prior experience can understand its purpose and basic function without having to spend 5 minutes deobfuscating the code. Yes you generally can golf most any class into a single line, but it's unmaintainable even to its original creator after a couple weeks.
That said, for personal consumption code, I don't generally bother going to that much effort to make my code clean/clear.
.
There are some programmers who like to complain about other people's code (it seems to make them think they are a better coder), so why not give them something intended for them to complain about?
for example an if( condition ) { /* some comment */ } else { actual_code_here(); }
The rules are:
1) We do not have a comment compiler, so you really need to read the code.
2) If the code is no clear as mud - then fix the code - delete the comments
When we have a comment compiler, we can revisit rule #1 and #2
3) last resort - add a very short comment to explain the line or two of code
4) In really tough situations, write a "theory of operations" paragraph as a comment
... so debugging/validation statements and error handling can be removed.
Some others are a cheap way not to write comments.
Others are... noise... that might cause bugs as soon as the function is modified.
ID: the nose did not occur naturally, how would we wear glasses otherwise? (apologies to Voltaire)
In effect most punctuation, indented blocks etc is superfluous to a computer. Is your code more or less readable with whatever construct you include? What if you add more code between eg your declaration and your use, would it still be obvious?
That's why languages without those construct are a pain to work with, you add a bunch of code and suddenly you've lost whether you're 4 or 5 tabs deep when the tabulation decreases. I like to add comments to the end brackets of regular code myself and add brackets to all if statements. It's superfluous but it's harder to rewrite a conditional one liner into a multiline code after the fact.
Custom electronics and digital signage for your business: www.evcircuits.com
I //
get
paid
by
the
line
;
When Do You Include 'Unnecessary' Code?
Here is how I make the determination: if it reduces my cognitive burden now, later when I return to the same code, or other programmers who will have to maintain it, then I include it
These days, a programmers time is nearly always far and away the most expensive commodity employed in any project. Why should I spend time asking myself about minutiae rather than focusing on architecture and algorithms?
I definitely will remove semicolons if I accidentally put one where it's not suppose to be.
The only "extra" code I ever use on purpose is braces to delineate a long single-line C/C++ block just to make it easier to read.
Other than that I never put in useless code. You're just asking for trouble because it makes the code less clear. Do people actually do that? I would call them morons! Probably engineers.
Flashes a subliminal message that says "Hillary for President" on the screen.
You can tell from the way he writes "java/javascript" as if they're related.
Not terminating statements with a semicolon means you're using semantic whitespace. Semantic whitespace is stupid. And the proper whitespace style is "tabs to indent, spaces to align". It's a courtesy to people who favor other tab widths.
If I think it makes the code looks cluttered I will remove it.
If I think it makes things more clear then I will put it in.
For instance, braces for if else where one of the branches is more than 1 line and the other isn't.
I never use variable names of more than one character unless all possible single character names have already been used, which rarely happens. I never indent blocks; extra white space is only superfluous. I never do in six lines of code what can be done in one long convoluted line. If the person that needs to maintain my code can't make sense of it, too bad. They're probably just a sloppy programmer.
09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0
Commenting code and making it human readable are ALWAYS a good thing. I'm sure we've all gone back to uncommented code we wrote years before and to this day still aren't sure how or why the hell it works.
If adding superfluous code or comments doesn't negatively affect the way it runs or the size to any significant degree then why the hell not if it will benefit you or somebody who needs to read the code in the future.
I work on flight safety critical code. There is no superfluous code. It's either directly traceable or it isn't in there.
I used to make firmware that goes into aircraft instruments. The FAA has some guidelines on this.
Unnecessary code is generated machine code, and the rule is that you can have none of it. Source code doesn't matter, if it's ifdef'd out it's the same as commentary.
The theory is that if execution takes an unexpected jump, it can't land in anything that isn't specific to the purpose of the device. Some people take this to extremes, writing new versions of printf() that omit the floating point and pointer output formats when they're not used in the system.
However, if a buffer overflow causes the program to jump, it can't land in the middle of the pointer formatting section and send a pointer to the airspeed computer instead of the decimal altitude.
What the OP is talking about is unnecessary source, which is a different matter.
IBM did studies of bug frequency, and concluded that the number of bugs in a program depends on the number of source lines a programmer can see at any one moment. Big screens allow the programmer to view more lines of code at once, little screens require reading the code through a soda-straw.
Their studies showed that simple code-tightening techniques reduced the number of bugs. Placing the brace on the if-statement, for example, allows one more line to be viewed in the window. Omitting braces altogether for single-statement "if" saves another line. Using 120-char width lines instead of 80 allows fewer wrapped lines, and so on.
There is a competing goal of readability, so tightening can't be taken too far. The complex perl-style or APL-style "everything on a single line" construct goes the opposite direction - too much info and it becomes hard to understand at a glance.
Typical C-like syntax with line-tightening techniques is easy to read, and presents probably an optimal view of code to the engineer.
Braces on their own act like vertical whitespace. Requiring one-and-only-one exit from a subroutine leads to convoluted and chevron code (where the code looks like a big sideways "V" and the hints of indenting is lost). Requiring all definitions at the top of the module requires the reader to flip back-and-forth, and requiring Hungarian notation makes the code look like gobbledy-gook.
Dump it all.
Name your variables clearly, using nouns for objects and verbs for actions. Name your subroutines after their functions. Tighten your code to make it terse, but keep it readable.
In professional software development, the general idea is clear: if any non-functional change in a source code file makes it more readable and more maintainable, then it's good, and vice versa. You write the thing once and it has to be maintained for years. This is actually called code refactoring, which is part of several methodologies.
Code refactoring may mean either adding or deleting code. There ought to be a golden middle point somewhere where the code is neither too verbose nor too condensed.
There is a slight complication in that not every person agrees what is the most readable form for a program, but in general it's best to imagine that you may have a total autobiographical amnesia in the next day and still need to understand what the program does.
A function should read like a good short story. Set the scene, develop the characters, advance to the climax, then there's the denumont/ epilog (sp?) where loose ends get resolved. Add comments if the story is hard to follow, don't if it's not. If the story is too long, create some helper functions.
A dash of humor here and there helps keep things entertaining, but go easy on it.
Remember, some software archaeologist may have to go back in 5 or 10 years and figure out what the heck the code does to fix a problem -- and that guy may very well be you.
I'm completely serious. This is what I do, and I actually enjoy going back through my 10 year old code (I've got a nice stable job)
I've seen a lot of style wars - tabs vs spaces, braces starting same line vs next line vs omitted when possible, commented enums required (especially by European companies using StyleCop), etc.
All of that is unnecessary from a compiler perspective. But the style you are accustomed to aids your efficiency and effectiveness. Code doesn't care if it's consistently indented, but finding that unbalanced loop is much easier with it.
For me personally, since I'm in C++, Java, JavaScript/Node (never by choice), Groovy, C# and Python every week, style consistency for me, rather than optimizing for what zealots for a particular language want, is highly beneficial. So the Groovy gets semicolons. The inability of JavaScript to handle certain brace formattings resulted in me modifying my default across all the languages, because they other (real) languages don't care.
Use what makes you personally across all your development, and more importantly your entire team, faster and better.
I add "unnecessary" parentheses to complex expressions in order to avoid the mental burden of thinking of operator precedence. I instruct my team to do the same.
Obviously if I can name a sub expression reasonably I just extract it, this is often enough not a reasonable solution.
Usually I prefer terse code, but the above is a fairly common exception.
The items listed in the summary aren't unnecessary - they are good practices. Readability, ease of maintenance, debugging and error-handling are all good things, and SHOULD be included - even if they aren't needed in a specific instance.
Car analogy: Most cars never need to have airbags, but we put them in because they are a good idea. The same should go for the listed code constructs - they should be there for the times it does matter.
Reading code is like reading the dictionary - you have to read half of it before you can go back and understand it.
Brian Kernighan famously wrote:
Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it?
— The Elements of Programming Style, 2nd edition, chapter 2
I over parenthesize C/C++ expressions. There are so many precedence levels that it is easy to forget who goes first**. There's a limit of course, I wouldn't write 4+(5*6) but I would certainly fully parenthesize:
x = 4*A|| B? C||D: E && F || G +3;
** Brian Kernighan admitted to having the table of precedence glued to his monitor, since he himself can't keep them straight.
Whenever it improves the code, reduces the risks for bugs, or when your company uses LoC as a metric. As a programmer, you're supposed to know when something is an improvement and when it's not. If you can't determine that, you're just a typist.
One and two lined if, while, for, etc... statements should always have block characters as someone might come along and introduce another line without realizing the block was missing.
Optional parameters are optional, you shouldn't include them unless you think the defaults might change in the future and you require the current defaults. More parameters make function calls harder to read and you risk accidentally swapping parameters.
Debugging and validation code is part of your error checking code. All of it should be included. Asserts that get complied out should be refactored into if statements. If a problem can occur during testing, it definitely will occur during production. Using asserts and removing error checking/handling leaves you extra vulnerable to things you haven't tested against.
You should always destroy all objects. If someone comes and refactors the code, they might not realize they need to perform additional cleanup.
When you take shortcuts, you cut your current typing time and extend your debugging and support costs while reducing the quality of your program. Occasionally it's worth it, but almost always it'll hurt you more in the end.
I also write notes to people, like this one, with the usual amount of English that isn't really necessary - like a quarter of the words in this sentence.
A certain amount of redundancy in communication is still around, though, yes, languages tend to drop and slur words over the centuries. Interestingly, military communications, where you'd think speed was very important, tend to be written quite formally, that is to say, with lots of that redundant English. Turns out that clarity is even more important than speed when lives are on the line!
I bet that your really important code that runs SCADA and other real-word systems has the most ponderous, overstated, tedious and obvious code of all. The same way that surgeons say, "Hand me the #3 rib spreader" rather than "Gimme that" while gesturing in a general direction.
Actually declaring and destroying your variables - stating what they are in clear, rather than by implication, and making clear when they are no longer needed - should be considered documentation for the programmers, even if the mechanism will perform identically without it.
Since I make a ton of money, and my boss is itching to fire me and replace me with a Syrian refugee who will work for cafeteria scraps, I make heavy use of 6-level deep macros and the C downto operator: while (i --> 0)
Intron: the portion of DNA which expresses nothing useful.
Caveat: I am retired. Programming was a major part of my career between 1995 and 2005 but I mostly do HTML/CSS these days, with only enough PHP to glue others' existing scripts together.
What I determined back in the day is that efficient coding is unnecessary for performance when the wetware BKAC would always be the primary limiter on speed. Since virtually all of my work was repurposing documents from old versions of Word, Excel, WordPerfect, Lotus1-2-3, and other outdated apps to newer standards (mostly early HTML), I did not have to worry about shaving off microseconds. The typing speed of the person selecting the raw data had more impact on performance than the programming. So I was much more concerned with whether I would be able to rewrite a handler for a Windows3.11 app to work on a Windows98 version, if that need arose.
So I worked mostly in Perl using the Tk graphic interface and Javascript front ends, which made rapid development and easy revisions to meet new criteria possible. I used explicit declarations, human-readable naming conventions, extra punctuation, and the long way around the barn whenever the shorter routes looked like they might cause head-scratching later on.
If I had been working in an environment where microseconds counted, I would have used a compiled language and a different approach.
My old-timer's advice to you young'uns: Look at the environment you are coding in and match your coding style to fit its shape. Eschew becoming the cleverest code monkey in the cube farm and focus instead on becoming wiser than all the others.
I code for thousands of mostly-unique commercial software products a year, using 8 languages (mostly C#), for many dozens of major customers, and lots of smaller ones.
Because of this, I have a huge chain of demands I keep track of, and methods of automation in order to collectively manage a constant flow of data requirements, and of course tracking issues both shared and common between these scenarios.
When I'm coding, I've got to code in a way that communicates these details to myself, consistent between all the languages I might have to touch for coding, scripting, database, reporting, and specialized languages a client may suddenly require.
Because of that, my code has to be a loose framework, a late-binding train station of logic, where demands may switch at any moment, and limitations imposed from other teams may similarly pop up.
My code is littered with multi-paragraph discussions of a technology I once had to interact with (customers often switch back), large sections of functions commented out rather than deleted, and other 'bad' practices just to give me landmarks and a 'flavor' of what a customer is occasionally interested in, amidst a never-ending avalanche of context switching between products and customers.
I've redesigned these several systems from the ground floor once (they used to only handle a small fraction of the work, using an antiquated language), and am working with a team to do a better design... but it's been very difficult for a team of perfectionists to understand how to react to an unlimited flow of changing requirements. Fortunately, the code itself has been quite usable, and they're using the same languages, but no system can really handle these demands truly consistently - I'd call it NP ridiculous. It's basically the "mythical man month" writ live, where I've got to do my work, and train a team whose work process may never really be able to do what I can do - definitely healthier long term, but can't help but result in some amazing process failures.
I actually would have made most of these design changes myself, but at the time, I was forbidden by management from making those choices, since I was doing my work directly at the production level - so it's actually a bit of a relief to see someone at least allowed to make some of the better choices.
In short (and yes, for this scenario, this is short), because I'm doing alone, for years, what a team of almost any size would struggle to approximate, as many of us seem to be doing, I've got no choice but to code how I need to in order to have a system that I can sanely maintain in an insane set of requirements. There's not really a choice in the matter, if your put in a position where "oh, we suddenly need this" exists as a live production task in a growing industry.
Ryan Fenton
Yes. I learned coding several years before the following story came out; became the object lesson as to why to speciify "obvious" things, for me as the programmer...
Graduating college, one of the news stories indicated that a satellite mission failed, simply because of the basic unit measurement system. Of course everyone uses the same standards when measuring correct? A standard gallon is the same as an imperial gallon and the respective non-metric weights have the same ratio's, etc.... Even when converting to or from metric all of the measurements are identical and round off error never occurs.
Or so everybody thought until re-examining the source code for the lost satellite and discovering A) rounding errors and B) not the same measurement units (different sections written in different countries)..
In C++... I keep each class in separate hpp/cpp files. I always prepend the this-> keyword in front of any member functions/variables to indicate locality. I often forgo use of typedef and would rather just see the entire type wherever it's at, even if it's 30+ characters for unique_ptrs to namespace prefixed classes templated against std::function's accepting variadic arguments....etc.
I'd rather type out statements instead of using macro's or compile-time template meta-programming. I repeat catch blocks rather than setjmp/longjmp trickery others use when mixing C/C++ code across shared-libraries. It all results in more typing and longer source code but honestly it's easy for anyone to see exactly what's going on without having to go lookup definitions across other files in a massive src code repository. Grok & Vim is all that's needed when the code is structured this way.
I'd also opt for composition over inheritance any day despite the average C++ coder's love for it. Every member gets initializer list entries even if default constructed... no if statements without braces even for one-liners.... I guess I just prefer verbose methods. What do you think?
Just yesterday I initialized a variable to get rig of a warning although it was never used without being set.
This was for work. For my private projects I'd never give in to bogus warnings.
Write code in a way you'd like to read it, if you didn't write it and had to fix/extend it.
If you've been programming since the early 80's, you've probably had to go back to code you wrote 10+ years before on occasion.
If its written well, (haha) with good comments and variable/function names, you'll spend almost no time getting it to work again.
Clarity is key, avoiding writing code which makes debugging difficult, I often create a local var and pass it to a function when I could just put it in the function call. Why? Well, I can easily look at it in the debugger, the little extra effort of a local var gets optimized out anyway, and it makes debugging a LOT faster.
I feel a peculiar sadness whenever I come across an expression of the form "someBooleanExpression == true" in the source code of the application my group maintains, inherited from the vendor my agency paid millions to for its development. I once had a naive illusion of professional developers being competent.
Every single statement you post is verifiably false. Post a link if you have proof. Otherwise shut up or move on to another crazy conspiracy theory (hint- you've already missed the train on Benghazi, I suggest something newer). There's already plenty of links showing what you claim is all lies.
Some "unnecessary" code can be very necessary to improve human understanding of the code and maintainability. When I use it, that's why.
If you believe that code will help someone with understanding (yourself included) then it is necessary. It is needed to help with clarity. It may not be strictly required for the correctness of your program, but your goal should not be to express the correct solution as succinctly as possible. That approach leads to many other problems.
Occasionally I include solutions for problems which have not yet been uncovered. Those methods may not be called (dead code) and any kind of static analysis would report them as "unnecessary." If I make the decision that such code will help me, or help someone else, later then I believe it is totally necessary, and good to include. Worse-case is that it will be a good starting point for someone later, and they will throw it away and replace it with something better.
Never include unnecessary code. If there are incorrect implementations that you are replacing, remove the incorrect ones! Don't leave traps lying around for people to get caught in. Unexecuted code, or not succinct code, is not unnecessary. I constantly include semicolons, and brackets around one-line conditionals - those are defensive practices which are designed to prevent future problems, and aid in clarity.
This is why people are hiring you - to apply human intelligence and judgement to a problem. There are situations where doing not strictly necessary things is appropriate, and situations when doing not strictly necessary things is a waste of time. It's up to you to decide. Different actions are necessary for different metrics. One thing may be necessary for a correct solution, and another thing may be necessary to help someone else understand your correct solution. Everything should be useful (necessary?) under some kind of metric.
Whenever I'm finished with a project I run the code through an ascii art converter to transform it into a giant ascii My Little Pony character*.
Never got a complaint, have gotten a few weird requests...
* (not a fan myself, but to each their own)
If it's just for myself or a personal project, little comments or extraneous stuff
If a junior programmer or someone I haven't worked with before will be using it in some fashion, I'll probably use more descriptive variable names, more comments, even formal comment blocks describing a given method/function, etc.
But regardless of who it's for, I always use proper indentation, consistent naming conventions, etc., just makes life easier all around.
As far as error handling, again, depends on the audience, if there's an end user product where it really matters, then absolutely have thorough handling; if it's an internal app used by the dev team, probably stick to handling critical errors for the most part.
'The unexamined life is not worth living' - Socrates
Since when are semicolons considered code?
Sent as ripples into the electromagnetic field. No single photon has been harmed in the process.
I get paid by the line you insensitive clod
I'll include code or comments that isn't technically necessary if it improves readability of what could be otherwise complex code. For instance, labeling the beginning and ending of specific logic blocks makes sense when you have to nest a number of logic conditions. It gives a person a much better idea of where to look when troubleshooting the application.
In the same regard, I'll often clear out and remove a lot of unnecessary definitions or separation if it detracts from the readability, preserves unneeded data beyond its scope (i.e. delayed garbage collection), or defines unneeded variables that are used only as part of a class constructor and/or function call. After seeing countless examples in different languages (most notoriously VB and C#) that create completely unneeded variables for the above reason, I've gotten to the point where it becomes little more than nails on a chalkboard.
Redundant semicolons at the end of macro instantiations that have an embedded semicolon. Because code editors try to auto-indent the next line if it's not there. Both the extraneous semicolon and the auto-indent make me twitchy, but... other people's libraries. What can you do.
SAS = Semicolon After Semicolon
Old SAS joke
...is not unnecessary code. It's long past the time to embrace secure coding as a core competency.
When do you do include 'unnecessary' code in your programs -- and why?
In C and C++, I always explicitly use either the keyword "static" or "extern" on every function (outside of a class) on both the .h file declaration and the .c file definition.
I prefer that because it tells me at a glance whether the function is file-scope or not. It's kind of like a C version of "public" versus "private", except that it pertains to file-scope.
For example, I would never use "static void func();" and then later define it as "void func() { body }". Yes, the latter is also static, but I hate the inconsistency of having a static function that doesn't include the word "static". I also use "extern void func2() { body }" so that the header perfectly matches the corresponding "extern void func2();" declaration in the .h file.
In addition, I use explicit static/extern keywords for variables (again, only outside of a class), as much as I can. (There's one special case where you must omit "extern" on a variable, and that's if it's an uninitialized definition. In that case, I omit the "extern" in exactly one .c file, to tell the linker to allocate space for it.)
- - - -
Another thing I do is to include the unnecessary formal parameter name in a .h file function declaration. (For example: I use "extern writedata(char *data);" instead of the more concise "extern writedata(char *);".)
I prefer that style because then the .h and .c function headers are identical.
Basically, I hate any kind of inconsistency in declarations that must be duplicated between .h files and .c files.
- - - -
In C++ code, I always include a "public:", "private:", or "protected:" on every individual member inside a class declaration. That way, I can re-order the member declarations without accidentally moving something from one category to another.
Again, it's the same principle as above: I always like to explicitly declare everything applicable, every time. I don't ever like to rely on defaults.
Occasionally I include solutions for problems which have not yet been uncovered. Those methods may not be called (dead code) and any kind of static analysis would report them as "unnecessary." If I make the decision that such code will help me, or help someone else, later then I believe it is totally necessary, and good to include. Worse-case is that it will be a good starting point for someone later, and they will throw it away and replace it with something better.
This is called YAGNI - You Ain't Going to Need It, and all it does is clutter code and make it harder to see what is truly needed vs what some programmer thought might be needed at some point in the future, if some things changed. Don't do it. Alternatively, place it in as scaffolding, but remove whatever elements aren't needed before you ship the code.
Never include unnecessary code
See above.
I constantly include semicolons, and brackets around one-line conditionals - those are defensive practices which are designed to prevent future problems, and aid in clarity.
No decent programmer needs these, and often they just clutter the code. Only put in the semicolons and brackets that are actually needed by the language.
I agree with the final statements, though not the ideas you expressed which would be actionable items by those statements.
All those moments will be lost in time, like tears in rain.
When writing code you need to keep both classes of readers in mind: computers and humans (first of all, yourself). Whenever you forget to make your code human-readable, it will be write-once, patch into a hairy ball of gunk ever after. Or preferably, rewrite from scratch as soon as a bug it environment change arises.
This may vary,if writing something that is intended to be read by novices or some funcition that in my understanding should be explained by more verbose code.
I try to write self commented code where I can , and I'm a believer in simple to to read functions instead of 'virtuoso'code that needs heavy comments
JC
> block constructs for single statements
This one bugs the snot out of me, especially when the braces don't line up.
That shit just wastes disk space!
upid. This just begs the Slashdot readers to go away. Next story thanks.
Semicolons don't go at the end of statements; semicolons separate statements. You might be in the habit of following each semicolon with a newline, but newlines are also optional. In a language which allows omission of semicolons and also allows statements to span multiple lines, semicolons serve to remove ambiguity.
Case in point: I recently wrote some complicated expressions spanning multiple lines of JavaScript, and I omitted the semicolons out of laziness. When I ran the code through a Glype proxy, Glype parsed it incorrectly. I added semicolons to clarify my intended meaning, and then the code worked.
So, semicolons can be more necessary than you think.
The moment that the code is written is that moment at which the most knowledge of how it works and what its limitations are exists.
So, code gets lots of extra stuff. Pass a parameter to a method where I save it and use it later? I'll probably add an explicit null check at the top of the method if I don't dereference it "nearby" so that when you forget and accidentally pass null, you'll get an exception near the error instead of on a worker thread later. Have a combination of inputs that is known to be not supported? I'll put a check for that, too, so that you get an error that tells you why it doesn't work, instead of a confusing error later.
Technically, about a third of my unit tests are useless, too, since they're testing things that I know are correct -- their purpose is often to break later, when you change one piece of my code (for example, to support another use case), and don't update something else that I expect you to forget/not know about. (For example, suppose there are two enumerations in a system that represent similar things, and there's a mapping between them. I might write a test that checks that all values in each enumeration have a mapping to the other, even though I know they do, so that when you find one enum and add your new value, the test reminds you to fix the other.
You're conflating "what the machine can do" with "what is convenient for the human" as well as "whatever my preferences are" with "what other people prefer". And you're doing it in response to what was a very valid concern at the time... and for some people is still, even if they clearly are not you.
I always liked the story of I-forget-which-writer, putting the pages he'd written on the wall; the higher up, the more satisfied he was with how it had turned out. The low stuff got rewritten first, until everything was sufficiently high up to make up a decent written work. You could do that with programs too, of course, but then it helps to have (functions|procedures|subroutines) that fit on one page.
Be that as it may, I don't agree that what you're describing is a reasonable way to program. You don't need my approval, but you shouldn't really try to argue the unwinnable either: I know what my preferences are, and yours clearly aren't mine.
In fact, if you're arguing that breaking up large functions loses "high level clarity", then I cannot help but think that your powers of abstraction are lacking. For if the organisation into smaller parts is well-regulated, the clarity ought to improve. If it doesn't, if one big large lump is clearer than well-described smaller parts working together, something is deeply wrong and that probably needs addressing. This may well be the programmer himself.
Code is for humans.
Extra code/white space usually means extra clarity.
And most compilers will either remove unreferenced unused code or the code will only execute once anyway so there's no real performance hit.
She was like chocolate when she drank... semi-sweet at first and then increasingly bitter.
I write a ton of absolutely unneeded code. Being able to see the intent of my code is very important. It tells a story and I want that story to be easy to read. I share a lot of my code for public consumption so it is also a training tool for other.
With that said, I only do this because modern code editors makes it easy. If I was still hacking all this together in notepad then to hell with you all.
Overcoding > Undercoding
Gain increased readability and clarity of actions involved, with little bloat cost. Bloat and inefficiency are from reckless calls and libraries and imports and poor design, often a result of lazy/inept design.
lol who cares phones have 4GB RAM anyway who cares the web container can run 16GB anyway, if the user doesn't have that much how is that my problem get an i7 faggots stop living in 2014.
Obviously this is off topic for a story on comments in code.
I write a lot of embedded systems code, and everyone wonders why I check a timer configuration register that was already set at boot, or do an internal sanity check to verify everything is as I intended it to be before loading the timer (turning the output on) and then double check that the timer expired when I thought it should.
Sooner or later someone reuses the code, ignores the comments and takes those checks out. Then you get the "randomly quits working until I reboot" hell that drives warranty and service crazy!
...the poor bastards who have to try to understand, debug and fix your code twenty years from now (don't laugh, it will happen).
Be neat. Be clear. Be unambiguous. Don't try to treat your project as a contest to show off how kewl and terse you can be.
Is code written for human understanding or machine compilation? Perhaps both. An extreme example is Knuth's literate programming ideas, where the actual computer language statement are practically irrelevant to the program text. So this stuff has been discussed many years and no one here is likely to have anything useful or interesting to say beyond the obvious - unnecessary program constructs can enhance readability.
How about "unnecessary language?"
> Never include unnecessary code. If there are incorrect implementations that you are replacing, remove the incorrect ones!
When possible, I comment them out with "wrapper" comments to preserve the code in the source control change history. And explain _why_ you've replaced the code, so the evidence is there for at least one or two more releases. It can be very difficult indeed to compare new code to the deleted code it replaces if you've successfully removed the visible traces of the deleted code.
Code should be rid of any fluff. Any description of what/how/why about the code should be in comments - well written and this is for human consumption; so it can be elaborate to avoid any misunderstanding. Code is written once but read/debugged many many times; Maintenance is the real cost. So you don't want to have noise in the code which takes a higher cognitive-load on your brain; your visual system too processes extra lines. These are unnecessary. Only after reading the code and thinking about it, you realize that code is harmless/unnecessary (eg while debugging or extending the software). The point is a line of code should have the least labor (cognitive/visual) from the human. A code which doesn't exist does this job the most perfectly. Hence write compact code; use standard libraries. Think at higher level of abstraction (like say containers instead of managing an array of objects); this needs spending lot more time in the design phase -- seeing the big picture of the various moving parts.
Strictly speaking, things like talking variable names aren't "necessary", the code will compile just find if you rename "error_flag", "sample_index" and "accu64" to "joe", "bob" and "alice".
What an idiotic question. OMG, I'm using a sh*t languages that doesn't require semicolons, but I'm still using them. Who cares?
For 45 years I've used a style called 'pretty printing' which at first glance looked like extraneous use of spaces, blank lines
and short comments at the end of lines for the beginning of main sections of code 'paragraphs'. Along with comments
before the start of main section of code that explain what and why of it's function.
Done to not only help other programmers in maintenance of the code, but to remind me later on what the hell I was doing
when I wrote the code.
Does anyone actually print their code on hard copy anymore?
It used to be that when you printed a program with thousands of lines on folded computer paper, that it actually was like
reading a book.
Our company took over a small software company selling POS software with their one and only 'programmer' leaving shortly afterwards.
As installation engineers working with MS terminal server we couldn't work out why the POS app would throw up errors and would only work with users granted with admin rights.
After some troubleshooting with various diagnostic tools we gave up and asked various programmers for help.
After much head scratching the task was finally passed to our star programmer.
Who within minutes of stepping through some VB code had a WTF moment, he had found the following line (sorry I forget the exact syntax):
Date = Date
Essentially the code was setting the server's system date to the current system date and hence would fail without a user having rights to change the system clock.!!
Yes, code for the next person to work on it. And pray your predecessor did the same.
Personally I think of the described semicolons as 1 character comments.
And unneeded parenthesis in an expression are 2 character comments.
It look better if the comment describes the actual effect that calling the function would have, plus what each argument means.
AC:"The goal is to make it so that anyone reading the class for the first time
with no prior experience can understand its purpose and basic function
without having to spend 5 minutes deobfuscating the code.That said, for
personal consumption code, I don't generally bother going to that much effort
to make my code clean/clear.
----
and ^^ That said, I do the same for my personal code -- since maybe 10-15 years back when I started seeing code that I'd written 2-5 years before that I knew I had written, but looked totally foreign to me. As time has gone on and I write code that builds on code that builds on more code (much going into libs), AND as I am forced by ever changing priorities to work on more projects in "parallel" (meaning I have more projects that have unfinished code waiting for more attention), I find that even spending a few months away from some code and I realize I didn't leave myself enough signposts to spend 'no-time' getting back up to speed.
The 2nd big point of this discussion is who decides what is "unnecessary" and what removal of "extra code" doesn't violate the premise that premature optimization is, at least, in the top 5 time-wasters category? I had a Dilbertian-boss, who only wanted bugs fixed that were reported by paying customers, and didn't want pre-release stress testing on multi-threaded kernel code ("Today's untested code can become tomorrow's paycheck."), but using short-term solutions for short-term OS-limitations was bad -- especially if documented. I.e. estimated time before limitation was removed: 2-3 years (was actually 18 months). Condition necessary to hit the "design-flaw": 25-30 years of continuous system *uptime* (no reboots or crashes). Admittedly this wasn't windows, but ...
4) All of the above
Yes, I often put "do;... end;" unnecessarily in SAS code because it's highly likely I or someone else will end up putting more statements in there. It's not really a coding issue; it helps when there'll be multiple revisions just trying to get the desired results from some complex algorithm built on-the-fly due to impending deadlines set by someone unfamiliar with how the questions get answered.
What do you mean by unnecessary code? I always input my OS to my computer by flipping front panel switches.
Of course, things got a lot easier once I switched from C to C++ and the STL and RAII idiom, but trying to release resources is still ingrained in my muscle memory; it takes a conscious effort in C++ NOT to explicitly release a resource acquired through initialization.
cpghost at Cordula's Web.
I say faux video as it shows two actors supposedly coding on identical macbooks.
Tabs vs spaces.... gad, I remember an editor that came with a "C" package that would always change any tab character into five spaces unless you designated the tab character to be an ANSI code insertion which took as many keystrokes as doing five space characters.
"Unnecessary Code" that is punctuation and comment for clarity is only "unnecessary" for scripts instead of programs. Programs are "compiled" which ignores comments and extra punctuation. So, the extra comments and punctuation only exists in the source code and is often beneficial for clarity. Try going back to an assembler program you wrote a decade before and try to remember what you did and why you did it that way. Or, worse yet, get assigned to update someone's code that retired a decade ago.
Do they still teach the difference in a compiler, an interpreter, and a scripter? So much pop literature doesn't seem to know the difference in a program and a script.
NRRPT/RCT
Code relating to a complex situation or unique idea can often be more understandable (and self-documenting) if laid out in a certain, sometimes more verbose, way