35 points · by hhm · 19y ago · 65 comments
I am amazed how many programmers I have worked with who are not up to date and just do their job and are not interested in it.
There are (at least) 2 problems with long funtions/methods: 1) They typically lead to more duplicated (and less reusable) code, e.g. repeated blocks of code between functions that could have been replaced with to-the-point short functions. A typical sign of where to extract a function is when you see a long block with a comment above it inside an even longer function, then replace the block with a function with a name inspired by the comment.
2) The methods becomes harder to test, and possibly even more important, the test code becomes harder to maintain (and untested code of some complexity usually doesn't work), e.g. what happens to your existing tests if you add some new conditions at the top of a long method?
A method with 20 lines of codes is roughly 20 chunks. Move some parts of those 20 lines into other functions, and you have created more effective chunks. Presumably, the brain has a much easier time understanding things it can actually keep in memory.
One idea is to create functions instead of comments, that is instead of writing "compute the rank" followed by some code, create and call a method computeRank().
10. The exact same code is in multiple places because you didn't bother to put in into a common function.
9. You have error codes in functions, but never bother to look at them (a sure sign that testing was never finished).
8. You have early exits from loops because you don't know how to properly code a recursion.
7. You execute too much code because you don't know the difference between "if" and "case".
6. You use 10 lines of code when 1 line would do because you don't know any better.
5. You need to run batch jobs from time to time to clean up your data base because you don't know how to debug well enough to find what's messing it up.
4. A third grader doesn't know what your variable names mean.
3. You think "Third Normal Form" is paperwork you need to fill out for one of your 8 bosses.
2. No programmer who has to maintain your code would ever want to work with you.
1. Any programmer that has to maintain your code would be more than happy to accept the consequences of first degree murder.
(10) Good programmers don't repeat themselves, true, and to continually improve as a programmer it is important to patiently do everything correctly the first time. However, obsessing over a few bits of code duplication is often a complete waste of time.
Applying good coupling and cohesion principles is not obsessing. It's as much legitimate programming as writing an equality test.
Perfect programmers may manage to avoid duplicating code on the first try. But unless we have dozens of Mozarts posting here I'd guess that no one qualifies. That means we make mistakes, and the question of whether correcting those mistakes is good practice or obsession depends on the circumstances.
For you, maybe. But what about the guy who applies enhancements 3 years later and has trouble getting through testing because the exact same code was somewhere else and difficult to find because of the 67 mods since then.
Minutes "obsessing" today usually saves hours testing tomorrow.
This also squares with a lot of IBM's experience in The Mythical Man Month, i.e. code needs at least three clients to really be reusable.
True, but the app has to make it to tomorrow for testing to matter at all. It's better to be in the championship trying to figure out how to manage a tired team, than it is to conserve energy during the semifinals and wind up sitting in the bleachers.
Wow. Not every problem calls for recursion. If you really hate early exits from loops, maybe you should just code the loop's condition differently.
Exactly.
Like I mentioned before, I'm the poor schmuck that has to clean it up because someone didn't bother to take your (common sense) advice years ago.
http://www.csd.uwo.ca/~yuri/Papers/pami04.pdf
It's really great, for the record. Anyway, the algorithm they wrote uses an early exit. In fact, they use a while(true), the "worst case" example.
initialize: S = {s}, T = {t}, A = {s, t}, O = {(Empty Set)}
while true
grow S or T to find an augmenting path P from s to t
if P = {(Empty Set)} terminate
augment on P
adopt orphans
end while
In programming this algorithm, sure, I could probably move the first grow before the loop, and grow at the end. But, now its harder to understand, and violates the afore mentioned copy paste rule.My point is this, take any such "rule" with a grain of salt. There are plenty of examples where it makes sense to do something atypical.
Meaning what exactly? A language that automatically optimized for tail recursion? Are there languages which don't support recursion "properly?"
edit: I just realized what I actually mean. Some programming languages, or the culture/community around them, do not seem to encourage certain things that can be done with the language. In the case of C/C++, while/do/for loops are used before recursion. In the case of Scheme, you try a recursive solution first and then go for a do-loop if you really need to...or something like that.
Today. And what happens after 10 other programmers modify your slick little multi-return function? Nobody will ever be able to modify it again because the entries and exits are lost among the garbage. This is the ongoing debate I've had for years with "clever programmers". They're missing one critical point: the guidelines of structured programming are not meant to make your life easier; they're meant to keep the code alive longer by making life easier for the poor schmuck who has maintain it (usually me).
Another Sign You're a Crappy Programmer:
You make your own rules in direct violation of effective established principles because you think you know better.
It isn't always about being clever.
And here's what inevitably happens when you do that:
14 mods are applied and your early exit(s) get lost in the muck.
Programmer 15 puts his mod ON THE WRONG SIDE of your early exit because he never saw it. He doesn't do regression testing, and the data base gets screwed up over the next 6 months.
Then I come along, find the errors, fix the data base, advise the user of the effects of the damage, and rewrite the whole program with single entry/single exit processing so that this never happens again. And then post to a board like this only to re-engage in the same old debate.
Aside from poorly named variables, violation of "single entry/single exit" is the biggest lifespan reducing problem of code bases I've ever seen.
This is the future speaking. Please don't do that.
You can make the same argument that a bunch of nested ifs is going to end up with a lazy programmer who doesn't know what conditions need to be met, so he puts it in the wrong place, and now all of your careful code is broken. Coding style is ultimately pretty personal, and this is no different.
Honestly, I've never had a case where I visually missed an early exit. Most of the time, such exits are guard statements, designed to bail out with an exception if some precondition isn't met. Most of the rest, they're "found it, don't need to do any more processing" and apparent from the logic. I'll usually mark the latter with a quick comment anyway, just to be sure I don't miss them.
And early returns let you apply additional invariants to your code. You've checked your preconditions and bailed if necessary; you don't need to worry that this array might be null. You've handled the 1-item base case; you don't need to worry about your recursive function blowing up. I find that broken invariants cause many, many more bugs than missing an exit and not executing code.
Cue the blame-the-programmer-for-not-being-smart-enough comments.
Guys. The goal isn't to provide the "perfect" code that somehow those poor average schmucks just can't understand. The goal is to provide the dumbest, easiest-to-follow narrative of how the computer is going to solve the problem for the user so that the next guy is able to understand it.
I can certainly see how this is true in a large organization which hires lots of mediocre programmers. However, if you're in a company where the other programmers are top notch, this sort of thing is not a problem.
In fact, if I ever see nested ifs and such in a function where I work, it gets changed to the least number of lines of code possible. I can do this because there is only 1 other programmer here, and I know he's not going to screw it up.
I don't know your situation, obviously, but my initial reaction is... "Holy crap man... run!"
Why is the function being modified 14 times? It sounds like the original abstraction was poorly conceived. I would hope that at some point before edit #15, someone would think to break the function down into smaller pieces.
You make sense. However, I would just try to find more interesting work than cleaning up after others and then trying to get them to change in a certain way :)
1. You foist idiocy upon others and refuse to listen when they point it out as such, because someone told you that the idiocy was "effective established principles".
Your "effective established principles" seem to be neither effective, nor established, nor principled.
http://en.wikipedia.org/wiki/Structured_programming
Isaac Newton "stood upon the shoulders of giants." Interesting to see that you know better.
-----------------------
"...someone told you..."
Actually, I learned what I'm sharing in this thread (and much, much more) from MANY excellent mentors. I hope you find some, too.
----------------------
"The number one sign you're a crappy programmer"
I have hundreds of (well paying) clients that would disagree with you.
----------------------
I "foist" standards only upon those who work for me. You won't ever have to worry about that.
- rules are for people who cannot think
- every rule has a context where it fits perfectly, but
- every rule has many contexts where it doesn't fit at all
Rules only reflect your current knowledge and your current working situation. This is subject to change.
I'll add two items to this list:
1. You believe anyone who doesn't write unit tests is a crappy programmer. (I'm done trying to explain this to carppy programmers- not only are they crappy they think that unit tests make them not crappy, and so they can't concieve of the reason unit tests are bad (and often they are...) If you want to write unit tests for yourself, that's fine, but if you've ever told someone else that they should write unit tests, you're a crappy programmer.
2. You believe in Scrum. Like global warming, Scrum is a religion... back in the old days, when programmers had to actually program, we used to use the "daily status meeting" as an example of the height of absurdity that pointy-haired-bosses could achieve. Now crappy programmers think that it makes them less crappy. (No, it doesn't, it actually means your code is crappy... especially if you think scum is an improvement.)
Really.
I know I am speaking crazy talk-- at least most programmers under 30 seem to think its crazy talk-- but it isn't.
The reason we have crappy programmers now? I think its cause they are going to colleges and getting CS degrees. Back in the "old days" when you had to write code to become a programmer, when you had to learn and you cared about getting things done well, we had to self teach and the learning curve was higher.... nowadays really crappy programmers train crappy programmers by the ten-score at universities who's primary goal is separating fools from their money (and I mean any university other than maybe caltech and MIT this applies to.) and they just teach really crappy programming practics. Those that can do, you know.
Speaking of which, you gotta be poor at math to go to univeristy in the first place-- teach yourself and start working right out of high school, after 4 years you're senior software developer, you're much better than the people who have been taught bad practices at university, and instead of being up to your armpits in debt, you'll have a good job and a great income... and four years later- a8 years into your career and 4 years after your friends got out of college, they might have paid off their student loans but you'll still be making twice what they were.
But then, I'm expecting to get pounced on because this is a site full of university grads. :-) Sorry, this has been my experience, and I've interviewed a LOT of programmers in my time.
In fact, I've found that PhDs in CS are useless, Masters in MS are good for grunt work, if you watch them close but generally shouldnt' be hired, and people with jsut a BS degree can usually be retrained if you can get them focused... if they get a job at a big corp right out of school, though, they are lost forever. (Most of them anyway.)
All the really brilliant programmers I've known didn't go to college. (BTW, I did, so I know first hand it was a waste of time.)
Anyway.....here's a bonus "how to know you're a crappy programmer":
You're a crappy programmer if you think while (foo) { stuff }
is wrong because the curly brace goes on the same line as the while. Generally ,the sloppy programmers who think they are really productive but produce nothing but shite are adamant about that... the ones who think about what they are writing and are useful, put the brace on the next line.
Really should use that as an interview question.
I mean, we can debate silly stuff all day, like LISP versus C, Firefox vs. IE, Mac vs. PC, web 1.0 vs web 2.0, etc. But these "braces on the same line" guys are just completely out of their minds. :) <-- Smiley face means humor was used in this comment.
Maybe it really should be used as an interview question. There is no point in mixing same-liners and new-liners together.
Only remedy might be to use a programming language without curly braces.
if (a==b) { doStuff(); } else doOtherStuff();
Doesn't mean you should.I would consider this a little bit of a hangup on my part, though, as it seems other programmers go the other way. An interesting topic for a book is all the weird things programmers get hung up about. Variable naming comes to mind, as does error handling strategies. And when we get hung up, usually we're not too shy about explaining why everybody else is wrong!