Ask Slashdot: When Do You Include 'Unnecessary' Code? (sas.com) 239
"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?
"Unnecessary" code? (Score:5, Funny)
All of my code is unnecessary, you insensitive clod!
Anything for work (Score:5, Insightful)
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.
Re: (Score:2)
None of that is unnecessary code. You get larger debug symbol files, but it is way easier to debug and test. At a minimum, have a single return value, instead of returning whatever half a line of method calls do, so you can break point the end of the method, instead of all or its callers.
Disposing auto-dispose objects is unnecessary code is really not good practice, because how thorough is the twice disposed code path going to be tested? I would call it a bug.
Re: (Score:3)
Ugh, single return rule sucks the worst. Nothing like having to read through dozens of lines of code just to see if the result wouldn't change somewhere halfway when an early return could have made it clear in an instant.
Re:Anything for work (Score:5, Informative)
The single return rule makes sense in some circumstances. I like early outs, but then tend to the single return rule. If you're breaking apart your logic to that degree that you need a return in the middle of a long function, then you may want to consider breaking apart the function. Still, I think it's best to consider it a *guideline* rather than a rule. The moment you declare something a rule, someone will find a valid reason for breaking it.
As for other "optional" code, I tend to put parentheses around any C/C++ code that depends on operator precedent. The only one *everyone* knows is * or / before + and -, otherwise, it gets parentheses, just to be clear.
I see a lot of programmers try to cram as much as possible into one line, which I'm not a fan of. As one example, I'm not a fan of assigning a variable inside an if statement. It's harder to read than several short, clear lines, and it likely compiles to the same assembly in the end. So, I'll occasionally leave a formula as several steps and explicitly declare some of the intermediate variables, even if I could have stuffed it all into one line. It's easier to debug, since you can examine the intermediate values, and it helps others to understand what's going on, since the intermediate variables have an actual name as a hint. I'm sure it bugs some people who think it's too verbose or my variable names are too long and descriptive. I don't go crazy, but neither do I stick to single letters when a word or two works better.
Re: (Score:2)
I see a lot of programmers try to cram as much as possible into one line, which I'm not a fan of.
Me neither. Especially if you ever have to run it through a line-oriented interactive debugger like adb or gdb. (I'm old.)
Re: (Score:2)
I'm not a fan of assigning a variable inside an if statement. It's harder to read than several short, clear lines, and it likely compiles to the same assembly in the end.
I'm guessing you mean inside the if () part of the statement rather than in the body of the statement for the if.
I'm not a big fan of it either, but I see it often enough because i work with a lot of outside code. I typically see it looking a bit like this:
if (auto x = SomeTest ())
{
}
which always make me second guess the '=' statement...should it be '=' or '=='. It's valid syntax and it's both shorter and helps to contain the variable X to within the statement enclosed in parentheses, but...it's jarring to s
Re: (Score:2)
I'm happy to consider constructs like "if ((newThing = CreateAThing()) == NULL) { /* handle the error */ }" legit when you don't have try/catch exception handling.
Re: (Score:2)
I write game code in c++, so the expectation is anyone coming to work on the code has a pretty decent level of skill in c++. I early out whenever it makes sense, but obey the "one return" rule is there is nothing to gain from short-cutting the evaluation path. Game coders are used to multiple returns, so it's not a big deal for them.
Re: (Score:2)
Re: (Score:3)
None of the "unnecessary code" in TFS would be translated into executable instructions. Heck, the better the compiler's optimizer, the harder it is to add anything that's semantically equivalent but causes wasted object code.
Re: (Score:2)
...when compiling for release.
Re: (Score:2)
Re: Anything for work (Score:2)
You do not code for yourself you code for your customers and the next coder that comes along
Re:Anything for work (Score:4, Interesting)
My approach also. Main goal for me is to make code readable enough that only minimal commenting is necessary. If personal stuff gets big enough that picking it up in a year would take effort then it gets the ultra explicit, readable and immediately understandable treatment.
I agree with both this and the poster above, except that even if minimal commenting is truly necessary I'll still put in plenty of comments. A couple of months later I want the code to make sense to me as well as others, and it's so easy to forget what you were thinking at the time. My shorter programs tend to have at least as many lines of comments as of code. Perhaps that's overkill but there's no harm in it. Writing comments doesn't take a lot of time and it may save tons of time down the road.
Side note: some years ago I went to a class by an "expert" who said that code should be so clear it never needs comments (sort of okay so far) so therefore code should never have comments in it (I walked out at that point).
Re: (Score:2, Insightful)
The code says WHAT you are doing
The comments should say WHY you are doing it.
I took over a project a few years back. The developer had no idea about :-
- comments
- Functions and Procedures
- Everything was in if...then... else monolithic structures.
As a result thousands of lines were replicated many many times and totally unmaintable.
My background was in assembler code. We had one comment per line as a minimum.
Re: (Score:2)
+1 for the 'why' remark.... ...i'd also add, that it should explain semantics when needed, out of bounds logic, reasoning where it isn't obvious, and addendums to what the code is doing.
I'm a firm believer that you should be able to page through code reading only the "green code" in order to understand what is happening.
Where code perfectly expresses the algorithm / concept, few comments are needed...but the rest of the code should be commented to hell.
Re: (Score:2, Insightful)
To me code should not be commented to hell, it should be commented to a level that a make the code understandable to a programmer or average skill. Most code is self explanatory, I actually read code better than English it is always accurately describes what the program is doing, and it is always up to date. Yes there is a place for comments, in code that is complex or relies mathmatical principles, or an API.
Too many times have I seen coding standards that require you to comment every function, you end wit
Re:Anything for work (Score:5, Insightful)
Side note: some years ago I went to a class by an "expert" who said that code should be so clear it never needs comments (sort of okay so far) so therefore code should never have comments in it (I walked out at that point).
Comments describing exactly what you're doing should be relatively unnecessary. However, comments as to *why* you're (not) doing something or how you're doing something, especially if it's non-obvious and/or "clever" are always appropriate. Code is changed for many reasons. Commentary can help understanding of various facets in various ways.
Personally, I think clear logic and consistent style are most helpful for both coding and commenting. Most people should be able to skim your code and have a general understanding of what's going on and why. I always try to write my code so that more junior people (and, quite frankly, even more senior people) on our team will be able to learn from my examples and work with what I've written. (You know, in case I get hit by a bus tomorrow.)
Re:Anything for work (Score:4, Insightful)
I try to write my code as if I'm explaining it to a new, but competent coder. This serves me well when I write articles and include snippets of the code, as well as when I try and remember what the hell I was doing.
I also make heavy use of: // NOTE: // TODO: // HACK:
and their ilk.
Re: (Score:3)
Remember that comments always lie. Still put them but don't trust them.
Actually this can work to your advantage when debugging. If the comment explains what is supposed to be going on, but that's not happening, it can help narrow things down.
Simple reason... (Score:5, Funny)
.
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?
Re: (Score:2)
Not all code is completely unnecessary, it may be unnecessary for the language variant but if you work with many similar variants it may be an advantage to be a bit defensive.
E.g. not all C compilers initiates variables to 0.
Re: (Score:3)
No, that's you. The point he's making is that it's not unnecessary to miss out these initialisations in *any* compiler, even (and I'm not sure these actually exist), ones that initialise every variable to 0. You're writing C, not "C for this specific compiler", and that means that no matter the compiler implementation, the value stored in an uninitialised variable is undefined, and as soon as you read an uninitialised value, your whole program has an undefined behaviour.
Re: (Score:3)
Quite. Reminds me of the definition of "undefined behavior":
It compiles perfectly.
It debugs perfectly.
It works perfectly throughout all functionality and QA testing.
It explodes in the worst possible manner when proper functioning is actually important.
Bugs are optional too (Score:2)
... 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.
Code doesn't need punctuation (Score:4, Insightful)
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.
Re: (Score:3, Insightful)
Re:Code doesn't need punctuation (Score:4, Insightful)
Depends on what exactly you're doing. As a general rule I prefer to avoid deeply nested code, but I've also written some code where a large block of code all interacted with a large amount of data, so that there were no natural "separation planes" to decompose it into smaller blocks without creating subfunctions that would themselves take dozens of parameters that might (or might not) be modified, making the whole even more error-prone and difficult to understand.
Not a common occurrence I'll grant you, but sometimes the task at hand really is that ugly.
I've also employed deep nesting in special purpose situations code where it could be naturally decomposed into subfunctions, but those subfunctions would themselves be extremely brief with near-zero chance of reuse. At that point the overhead of function decomposition can rival the time to actually get it working, so unless there's a dramatic improvement in clarity or I've got time to spare, I'm unlikely to bother.
Re: (Score:3)
The problem is and remains readability, not testability. You can perfectly test minified JavaScript (all the superfluous is removed). Additionally, your code may test correctly but still not give the results expected, especially when you're doing things like write mathematical code or image processing (you can't test for correctness if you don't know the result yet). Manually scrolling and looping through a program in your head is not easy with everything is in superfluous functions. And that is precisely t
When it reduces the cognitive burden (Score:5, Insightful)
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?
Re: (Score:3, Insightful)
Only if it improves readability (Score:2)
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.
Re: (Score:2)
Agreed, if one branch is more than one line - and disagree if they are both only one line, or there is only one branch.
Code should be as concise as possible. (Score:5, Funny)
Re: (Score:2)
I second this, and also add that I like to throw in a bunch of superfluous methods in all my classes that are very complicated and are never called.
Re: (Score:2)
Re: (Score:2)
Then I clearly need to step up my game and have them call one another for no reason that anyone reading my code will ever be able to understand.
Re: (Score:2)
Ideally such functions will contain several pages of incredibly complicated looking code that will be completely optimized away in release builds, but exhaustively execute for debugs and traces, and require months of careful human analysis before anyone else can be completely certain of that fact.
Re: (Score:3)
Then I clearly need to step up my game and have them call one another for no reason that anyone reading my code will ever be able to understand.
You do. You really do. Until you do, we're revoking your evil overmind badge :-) Here is a function that is never called but cannot be easily proven to be called or not:
struct usethisoften {
};
void usethisoften (void) {
printf ("Doesn't get called!);
}
typedef void (*ftype) (void);
ftype foo[] = {
funcs, that, get, called, usethisoften, otherfuncs, go, here, will not get called,
};
foo[somevar % sizeof (int)] ();
Just ensure that
Re: (Score:2, Insightful)
You use variable names? That's so last century! Modern code doesn't use named variables:
postMessage(story("https://developers.slashdot.org/story/16/07/23/0357235"), createMessage(MsgType.ACPost).addSubject("Re:"+previousMsg().subject).addGenderNuteralBody(createText("You use variable names?"+Spacing.Sentence+"That's so last century!"), Lang.English).convertTo(OS.getDefaultLang()))
Re: (Score:2)
I never use variable names of more than one character unless all possible single character names have already been used, which rarely happens.
If you're not routinely using up all possible single-character variable names, then you're not making your functions large enough, and/or you're not using enough global variables. You can do better.
Re: (Score:2)
One-letter variable names alone provide far too little job security, except for l and o. This is much better code:
for (godzilla=pokemon, godzilla+=l; godzilla<jesus)
lllillilil = llliliilil + llillilill;
Did you think I was adding one to godzilla in the for clause? You're not worthy to maintain my code. Seriously, I got stuck maintaining a code base where some genius used l as a variable name everywhere - he now works for Microsoft Research (not making that up).
Re: (Score:2)
It sounds like you should just switch to writing your code in APL - or maybe you already did...
View from on high (Score:5, Insightful)
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.
Re: (Score:2)
However omitting braces is not necessarily a good thing because it's easy to get really nasty bugs if they are omitted.
Re: (Score:2)
If braces aren't put on single-line if or else conditions, that leaves the possibility of a bad code merge causing a goto fail [slashdot.org] situation. In the worst case, if you keep open braces on the same line (1TBS like "} else {"), you add one line over naked statements, which is still better than putting open braces alone on a line.
So basically, it ensures that if a merge or patch slips in an extra line, it doesn't silently cause a change in code flow. It also keeps the unchanged if() expression out of the diffs wh
Re: (Score:2)
Never experienced such a bug, not in my code nor in others.
And no: if not forced by stupid code formatting rules, I only use { and }, when it is actually needed.
Re: (Score:3)
It's great now that we have huge screens, we don't have any more bugs.
Re: (Score:2)
I put the open curly brace on its own line. Not that it needs to be, but because it enhances the readability of the block of code contained.
Readability == Less bugs
One exit from subroutines/functions/methods makes it easier to debug. Definition at the top, makes it easy to find variable type and initialization, instead if hunting through all the code trying to fi
Re: (Score:2)
This is true, but if you define the variable in the middle of something, and it's used somewhere other than just after the definition, you can end up playing hide and seek trying to find the definition, and can sometimes encounter unexpected scoping issues if you're not paying attention. I would probably say that it's better to define them at the beginning of the scope in which they're used.
Re: (Score:2)
Current wisdom is to define variables just before, or exactly as, you use them. This benefits the compiler as well as readability and cut and paste.
e.g.
vec3 v = OtherVec * SomeQuat;
vec3 abc = v * OtherQuat;
Your IDE will let you know pretty quick if you cut and paste it wrong. The CPU will thank you for your declarations and assignments, especially if it can shortcut some of it.
Re: (Score:2)
I haven't printed out my code since 1988.
I understand the sentiment, but it's just really not true anymore. Even just having a CRT makes following that rule unnecessary, let along a modern LCD which can easily handle 160 x 80 lines of code. Even still, I would never arbitrarily format my code to fit the screen resolution of the device I was currently using. To paraphrase the words of Fight Club "Code will go on as long as it needs to.".
It's just not true that a programmer needs to read the whole damn functi
Readability wins every time (Score:2)
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
Re: (Score:3)
Speaking of readability, here's an entertaining one I've been seeing more of in C:
if (result == SUCCESS)
versus
if (SUCCESS == result)
The rationale behind the second is that you don't end up accidentally assigning SUCCESS to result (eg, if (result = SUCCESS)). But I know that I find it weird to look at it the other way around. I want to know if the result was successful, not if successful was the result. Maybe it's an english thing.
I know that Xcode has been putting up warnings/errors for code that does a
Re: (Score:2)
I find it kinda weird too, but IMO it's a small price to pay for avoiding bugs that are sometimes pretty difficult to track down. I also tend to add parentheses where they're strictly not needed because I don't count on everyone knowing the rules of precedence. I've seen people get bit by something like "if( i & 0xff == TRUE )
Re: Readability wins every time (Score:2)
I prefer to use static analysis tools that will catch this sort of thing for me, rather than bend the code style so the compiler will catch it.
Re: (Score:2)
I agree with your statement generally, but the commonly accepted solution against unintended assignments in the if conditional is to add an extra set of parenthesis -- which is literally bending code style so that compiler (at least the static analysis tool) will catch violations.
Re: (Score:2)
Speaking of readability, here's an entertaining one I've been seeing more of in C:
if (result == SUCCESS) versus if (SUCCESS == result)
The rationale behind the second is that you don't end up accidentally assigning SUCCESS to result (eg, if (result = SUCCESS)). But I know that I find it weird to look at it the other way around. I want to know if the result was successful, not if successful was the result. Maybe it's an english thing.
I know that Xcode has been putting up warnings/errors for code that does assignments in if-statements and saying that if you really want to do that, wrap it in an extra layer of parentheses (eg, if ((booleanResult = Do_Something()))). I'm not sure this is somehow more clear that you're doing the assignment...
In proper C++ this would be
if (bool booleanResult = Do_Something()) {
or more usefully
if (AClass foo = PrepareFoo()) { DoSomethingWith(foo); }
This does not generate those assignment warnings, is in the right order for readability and does not need obscure extra parens.
Re: (Score:2)
Competent programmers, never. It's only for the other ones.
Code should read like a good story (Score:2, Interesting)
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 pr
Code Style for Effectiveness vs Purity (Score:2)
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), Gr
I avoid reliance on operator precedence (Score:4, Informative)
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.
Nothing Listed is Unnecessary (Score:2)
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.
Parenthesis (Score: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.
Re: (Score:2)
The post would have made more sense if you had shown us where you would have placed the parenthesis ... I see no reason for one, but I might be blind. :)
However I find the badly placed ? and : annoying
Re: (Score:2)
x = ((4*A) || B)? C||D : E && F || (G +3);
My rule it that if you have to even think more than a second about precedence then there is somewhere out there who will misinterpret it.
By the way Kernighan claimed that he should have done pemdas+left to right associativity between operators of the same precedence, instead of the present 15 levels of precedence in C and sixteen in C++.
You mean "documentation" ? (Score:2)
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 tha
I'm in my sixties (Score:5, Funny)
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)
Xtra code when there is no cost (Score:4, Insightful)
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.
Whenever I want really... (Score:3)
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
Re: (Score:2)
Re: (Score:2)
I know, it DOES sound absurd, and in practice, it is. Now, it's "only" around 800 individual products actually delivered fresh each year, but because I'm having to touch and test older games as a part of that process, I'm in effect coding for thousands of shipped products per year, just to make it as sane as possible to continue each product line.
And yes, that means each day, I'm jumping between 15 minute mini-projects, reviewing and raising issues on design documents, throwing together project directories
Re: (Score:2)
Well, if you need assistance, I call my self 'Software Generalist' on my business cards.
I gladly assist,
I'm especially good in shoulder massages, fetching coffee and siftdrinks and as I have a martial arts education, I can keep every one - unless armed with a Panzerfaust - out of your office room.
Deal?
P.S.
I'm a retired gamer, too. I can easily tell you which games are mot worth supporting anymore. E.g. Pokemon.
I use it when it makes things better (Score:2)
Some "unnecessary" code can be very necessary to improve human understanding of the code and maintainability. When I use it, that's why.
Never - But Because Your Definition of Unnecessa.. (Score:4, Interesting)
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.
Re: (Score:2)
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 lan
Depends on the audience (Score:2)
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 the
Unnecessary semicolons? (Score:2)
Re: (Score:2)
Hae?
In a langugae that requires semicolons?
What else should they be ?
Look! This is a for loop:
....
...
for (int i = 0; i < max; i++ )
Nevermind the ';' they actually don't belong to the code
Re: (Score:2)
Money (Score:2)
I get paid by the line you insensitive clod
Re: (Score:3)
/*
That's
fine
,
good
code
should
be
well
commented
*/
In C/C++ (Score:2)
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.
What does SAS stand for? (Score:2)
Old SAS joke
Re: (Score:2)
Honestly, habits die hard. I hit ESC three times in vi, but I don't "think" I'm OCD...?
/Wonders how many
//Probably the same amount that know of Ada
urgh (Score:2)
> block constructs for single statements
This one bugs the snot out of me, especially when the braces don't line up.
Re: (Score:2)
true that. also semicolons are optional in javascript. for ordinary statements you can simply leave them out.
Re: (Score:2, Informative)
I usually write all my C++ if statements, even if they contain just one statement, with curly brackets. I read somewhere it was better to do this, but I can't remember why.
It's a land mine. When you later add a second line to the conditionally executed section, you then need to notice the lack of braces and add them or you will not get the intended behaviour.
Re: (Score:3)
Any c++ programmer with more than 1 years experience will see this immediately and slap some braces around it. Thanks to modern IDEs and standard indentation (which the IDE will auto-correct) it's extremely unlikely anyone will make this mistake, or it will go unseen for very long.
I'd group this sort of 'error prevention' in the same category as putting the constant first in every if statement e.g.
if (1 == YouShouldHaveDoneThisTheOtherWay)
{
Whatever();
}
The people who make the mis
Re: (Score:2)
Any c++ programmer with more than 1 years experience will see this immediately and slap some braces around it. Thanks to modern IDEs and standard indentation (which the IDE will auto-correct) it's extremely unlikely anyone will make this mistake, or it will go unseen for very long.
I'd group this sort of 'error prevention' in the same category as putting the constant first in every if statement e.g.
if (1 == YouShouldHaveDoneThisTheOtherWay)
{
Whatever();
}
The people who make the mistakes that this shit prevents have no place working on code.
You assume braces. BEGIN/END is less visually distinguished.
You assume only one person will touch the code.
Code for what might happen, not what your ego tells you you will get away with.
Re: (Score:2)
Code for what might happen, not what your ego tells you you will get away with.
Experience tells me what might happen is that code and projects are broken up based on the experience of the teams working those code bases. You don't ever let an advanced code base get taken over by an inexperienced team. You will always have an A team, a B team, and the other guys. What is right for the A team is not right for the B team or the other guys - and it goes down the line.
There is always going to be advanced projects in languages that most team members will shy away from or will be too damn har
Re: (Score:2)
I often have to go in fix problems caused by people's overconfidence. Everyone is fallible.
I design chips, where the tolerance of design errors is substantially lower than for software. You can't just roll out a patch.
Re: (Score:2)
In all your wisdome you still made a mistake:
You formatted your braces wrong!
Sorry to point that out!
Re: (Score:2)
Well as you post as AC we don't know which of ... cough cough ... "your posts" got modded down.
That teaches you a lession, doesn't it?
Re: Happy Saturday from The Golden Girls! (Score:3, Insightful)
Maybe because you are a douche?
Re: (Score:2)
The sad thing is, some people probably do get paid by LOC.
Re: (Score:2)
And that is why almost every country in the world uses SI units instead of outdated imperial measurements, like the US.
Re: (Score:2)
+1 for writing code that you need to read 10+ years later
Re: (Score:2)