×

Welcome to the Slashdot Beta site -- learn more here. Use the link in the footer or click here to return to the Classic version of Slashdot.

Thank you!

Before you choose to head back to the Classic look of the site, we'd appreciate it if you share your thoughts on the Beta; your feedback is what drives our ongoing development.

Beta is different and we value you taking the time to try it out. Please take a look at the changes we've made in Beta and  learn more about it. Thanks for reading, and for making the site better!

Defining Useful Coding Practices?

Soulskill posted more than 4 years ago | from the randomized-variable-names dept.

Programming 477

markmcb writes "A NASA engineer recently wrote about his disappointment that despite having well-documented coding practices, 'clever' solutions still made the code he has to maintain hard to follow. This got me thinking about the overhead spent at my own company regarding our code. We too have best practices that are documented, but most seem to focus on the basics, e.g., comments, modularity, etc. While those things are good, they don't directly ensure that quality, maintainable code is written. As the author points out, an elegant one-liner coupled with a comment from a few revisions ago makes for a good headache. I'm curious what experience others have had with this, and if you've seen manageable practices that ultimately offer a lot of value to the next programmer down the line who will have to maintain the code."

cancel ×
This is a preview of your comment

No Comment Title Entered

Anonymous Coward 1 minute ago

No Comment Entered

477 comments

Simple... (5, Insightful)

Anonymous Coward | more than 4 years ago | (#30343510)

Simple, clever doesn't pay the bills, reliable and maintainable do. It's a cost benefit analysis: if that clever one-liner saves many man-hours of work, then probably a good idea. If it saves you two or three lines of code and all of an addition 45 seconds, probably not worth the blow to maintainability and readability. It's always a tradeoff...just have to decide which is more important in any given context, and at most companies, reliability and maintainability is king compared to a slight runtime increase or 45 seconds/3 lines shaved off.

Keep it simple (5, Insightful)

yog (19073) | more than 4 years ago | (#30343646)

the op has it mostly right. There's little value in fancy show-off code that may earn a programmer some machismo points from like-minded colleagues but results in maintenance headaches down the line.

Elegance is often misused to mean terse, clever code, but that is really far from what elegance ought to mean.

I define good, elegant code to be code that is clear, well commented, self-explanatory, and easy to modify.

I'm dealing right now with some "object-oriented" Perl programs that are nearly comment-free. Sure, eventually it'll start to look familiar and I'll know where to go to fix stuff, but it pisses me off at the programmer.

I don't want people cursing and mocking my name after I've left a position, so I always strive to make my code as obvious as possible, at the cost of some high falutin' fanciness that just bogs people down and keeps a company from getting its business done efficiently.

To me, the highest compliment is when a newbie says "I just read your {Java|Perl|C++|SQL} program and I was surprised at how easy it was to understand. I just wanted to thank you for that."

Soem of the complaints aren't valid (3, Insightful)

tomhudson (43916) | more than 4 years ago | (#30343810)

If you have a variable that is a rating of employees at an organization, organizationEmployeeRating is not a ridiculous name, while erating is.

If you have a method that calculates the risk of an investment, name it calculateRiskInvestment(), not risk().

erating is fine, especially if it's in a struct, to give you the context, or when it's first declared: int erating // employee rating

risk() is also better. Since the author says its a method, it's in a class. Investment.risk() is a hell of a lot better than Investment.calculateRiskInvestment().

The author is complaining because the code is all in c. Awww - c has different style conventions. Don't try to make it look like java.

Re:Some of the complaints aren't valid (1, Insightful)

tomhudson (43916) | more than 4 years ago | (#30343862)

And this hooter:

The other side of C/C++ indirection is pointer logic. Pointers are powerful, but dangerous. For now I will just say try to stay away from statements like:

int ***values;

Instead, try C++'s STL Containers . First, the code is in C, not C++. Have fun porting the STL.

Second, there's nothing wrong with int *** values; If you can;t figure it out, go back to java.

and .. "OMG USE BRACKETS ALL THE TIME"

if(test)
do_something()

to

if(test)
do_something()
do_something_else()

People get bitten by that once, then they learn. No brackets means a SINGLE statement. Brackets are optional, and not needed. Don't lcutter up your code because some n00b doesn't know how to read.

I've seen people get bitten because they put brackets in - and because their indent style isn't consistent (they used 4 spaces instead of a hard tab, so when they cut-n-pasted code, "BAD THINGS(TM)" happened.

Sure enough, the author cites Java coding conventions at the bottom of the article. c is NOT java. java is way to verbose, some of us like the clean lines of c, and think java should at least get a pre-processor so we can hide some of the typographical pollution. Even the original creator admits that the "everything is a class" model was a bad idea.

Re:Soem of the complaints aren't valid (3, Insightful)

AmberBlackCat (829689) | more than 4 years ago | (#30343888)

"erating // employee rating" requires you to look in the comments of the declaration section in order to figure out what the variable does, whereas "organizationEmployeeRating" tells you what it is no matter where you see it in the code...

Re:Soem of the complaints aren't valid (2, Interesting)

tomhudson (43916) | more than 4 years ago | (#30343978)

If you're going to be maintaining it, you'd better damn well look over more than just the immediate code. Look at the declaration, instead of assuming what it is. There are too many pieces of code where people asume the type of a variable, "fix" the code, and make things worse.

3 most important rules

  1. ALWAYS look at the variable declaration.
  2. ALWAYS look at the variable declaration.
  3. ALWAYS look at the variable declaration.

ctags is your friend. Even the laziest f*** can learn how to use it in a minute or two.

If you can't use ctags and/or fgrep effectively, you shouldn't be touching c code. You're simply not qualified.

Re:Soem of the complaints aren't valid (1, Insightful)

Anonymous Coward | more than 4 years ago | (#30344090)

Exactly. Use ambiguous terms like erating if you want to ensure that other people are going to have to do global searches on erating in order to figure out what it means.

One of the most insidious ways of introducing bugs is by loosely defining the exact the purpose and value range of a variable, and one of the first steps to reduce that problem is by using an unambiguous name. (That said, I wouldn't embed a variable's acceptable value range into its name -- that should be taken care of with unit tests and assertions, and noted in comments or docs.)

Re:Soem of the complaints aren't valid (1, Troll)

tomhudson (43916) | more than 4 years ago | (#30344174)

Exactly. Use ambiguous terms like erating if you want to ensure that other people are going to have to do global searches on erating in order to figure out what it means.

I would want anyone maintaining the code to look at the declaration to make sure they know what type it is, then look at any initialization code, before monkeying around with it.

That's what ctags is for.

It even supports php, javascript, perl, make and shell scripts - it's not just for c any more.

Re:Keep it simple (5, Insightful)

UnknownSoldier (67820) | more than 4 years ago | (#30343986)

> well commented,

Many programmers don't understand that concept:

* Code tells you 'how'
* Comments tell you 'why'

I have found this to be _especially_ important for bug-fixes. Very important to document why things were done a certain way to minimize implicit side effects.

Re:Keep it simple (1)

Twinbee (767046) | more than 4 years ago | (#30344166)

I suppose the clearest code of all would often have exponential run times, zero optimization, extremely inefficient disk access routines, and of course, very short code.

I would die for that day.

Re:Simple... (4, Insightful)

Coryoth (254751) | more than 4 years ago | (#30343662)

Simple, clever doesn't pay the bills, reliable and maintainable do. It's a cost benefit analysis: if that clever one-liner saves many man-hours of work, then probably a good idea. If it saves you two or three lines of code and all of an addition 45 seconds, probably not worth the blow to maintainability and readability.

I view it as a premature optimization issue. It's very rare indeed that you save much time in writing code by doing something cute or clever; usually it's a matter of trying to do something slickly to save cpu time or memory. Rather than prematurely optimize I find it is best to try and write things in the most clear straightforward fashion first (even if it's not the most efficient implementation) and then go back later and make things more efficient if it proves to be necessary (often it doesn't because of real bottlenecks elsewhere).

Re:Simple... (1)

Z00L00K (682162) | more than 4 years ago | (#30343758)

There is clever and there is clever.

You may have a clever detail in the code, and you may have a clever overall structure.

And in a larger solution there will always be parts that are clever and parts that are stupid. Sometimes by the same programmer.

And appeared to be a good idea at the time may end up being an outrageously stupid idea when time has passed and the component has grown over all limits.

It's also important to notice that an idea can be excellent from the point of understanding of the solution but have absolutely horrible performance. And it can be the opposite too, excellent performance but you have to be top grade to understand how it works.

The thing is to find a fine balance between structure and performance.

And as a designer - don't confuse people unnecessarily by using "smart" coding by utilizing "stored procedures" in external resources like databases. That will ultimately just cause headache. People may reason that using stored procedures will decouple the database from the code, but it also adds a new layer of code which is requiring different skills to maintain and that is tricky to debug in addition to not providing compile-time warnings/errors when there is a mismatch.

Re:Simple... (2, Interesting)

camperdave (969942) | more than 4 years ago | (#30343926)

The thing is, though, that that sort of programming used to fetch the highest dollar. This was back in the days when computers only had 2K of memory and you had to use overlay programming. 45 seconds is always a significant amount of time.

I remember porting a piece of date validation code from an old WANG computer. At the heart of the algorithm was the computation 3113-1881 (or something like that). I ported everything straight over, and... it didn't work. I ran through the code manually, and... it made no sense. 3113-1881 is 1232. I went back to the WANG computer and typed in PRINT 3112-1881, and suddenly the algorithm became clear. On the WANG, 3113-1881 was 1231.9999, which made a perfect mask for a numeric date.

Re:Simple... (1)

b4dc0d3r (1268512) | more than 4 years ago | (#30344078)

What people forget, every single time, is that people are different. Coding practices differ depending on your language, and your coding team's abilities.

I saw lots of code during peer review that was just terrible - looping to fill a DataTable from a DataReader, applying transformations for a single column. My code would have applied a function to the Template, so you let the Template iterate and call your function for the translation.

ASP.NET does not make it easy to do such things, and there are so many ways to do it, and so many code examples which recommend one way and some recommend another. And the documentation is terse - it does not explain what's happening.

Do you expect me to use Reflector to figure out how the language works when I have a line item due Monday? No, then I will do a code search, copy and paste, and when I find a different solution I'll have two different methods in the code, cos I'm not going to back-port anything that works and has been tested.

Ultimately, you need to agree on something that is readable by everyone who might read it (including support staff if applicable). If looping for data transformations is more clear, go with that. I decided to bite my tongue and allow code like that if there existed an example of its usage (without being a recommendation against using it of course). It is more clear that way, but lots of overhead. So you need to have a body of coders who understand the language completely and know which design patterns to choose.

Do you fill an ALLOW list of properties from an initialized array so that someone can't just go around changing it, or load it from a config file so someone can just go around changing it? Do your array functions check the lower and upper bound, or just go from 0 to <= .Length?

My point, if I have one, is to choose an appropriate language, and make sure your people know how to use it. Then they will code appropriately and it will be understandable. Any time you move to a different language, or a different version of the same language, there's a learning curve and the first code out the door will have problems. Do you rewrite it later? Or do you invest time up front to understand the language features and *recommended* usage? I'm saying spend the time up front. You're not being paid to learn the language as you go - you're being paid to know it. And if the job requirements change, management has to give you time to make sur eyou know the new stuff, so you can do your ACTUAL job, which is to create readable output.

And your definition of "clever" is? (1)

mi (197448) | more than 4 years ago | (#30344088)

Simple, clever doesn't pay the bills, reliable and maintainable do.

Except that one's "clever" is another one's "perfectly normal". For example, a client I worked for, had a huge body of C-code, where they — following one of the company founders' coding practices — would bzero a just calloc-ed array. In hundreds of places throughout the code...

Was it clever of me to not do it, knowing that calloc returns zeroed-out memory (its only difference with malloc in these days of flat memory), or was it stupid of them to insist on doing it for the sake of "reliable and maintainable" code?

Re:Simple... (1)

digitig (1056110) | more than 4 years ago | (#30344146)

Simple, clever doesn't pay the bills, reliable and maintainable do.

Whose bills? You're right that reliable and maintainable pay the shareholders' bills, but there's no difference to the coder's bills (because [s]he's off on a new contract with a different company by the time the maintenance problem hits) unless you have really good review processes in place. So the coder is going to do it the way that gives most satisfaction, not necessarily the way that's best. I reckon that strong reviews are the only way to overcome that.

multiple revision? (2, Insightful)

leuk_he (194174) | more than 4 years ago | (#30343514)

As the author points out, an elegant one-liner coupled with a comment from a few revisions ago makes for a good headache.

A oneline that had multiple revision should be completely rewritten, because if you manage to get multiple changes in one line it surely is a mess... somwhere.

Re:multiple revision? (1)

joaommp (685612) | more than 4 years ago | (#30343672)

At my company, the coding standards include not only guidelines for styling and comments, but also for performance optimization, code run-time stability and robustness, tips to avoid common programming errors, tips about readability, safety, security and productivity.
The manual has a whole chapter dedicated to the compromises between performance, productivity, readability, robustness and safety.
There's also a summarized presentation version of the manual that all new employees must attend before they're allowed to begin coding for the company.

Re:multiple revision? (2, Informative)

daedae (1089329) | more than 4 years ago | (#30343782)

Unless of course they meant a one-liner coupled with a comment from the previous implementation, ie, the clever programmer failed to cleverly update the comment.

Re:multiple revision? (0)

Anonymous Coward | more than 4 years ago | (#30344044)

I read "a few revisions ago" as meaning that the source file has been committed multiple times since then, not necessarily with changes to the "elegant" one-liner.

Who reviewed this story lead, anyway? Kids these days would never have made it in the good ol' comp.os.vms ng.

Literate Programming (3, Insightful)

John_Sauter (595980) | more than 4 years ago | (#30343530)

To my mind, the best coding standard is Don Knuth's Literate Programming: http://www.literateprogramming.com/ [literateprogramming.com] . Quoting:

I believe that the time is ripe for significantly better documentation of programs, and that we can best achieve this by considering programs to be works of literature. Hence, my title: "Literate Programming."

Let us change our traditional attitude to the construction of programs: Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to human beings what we want a computer to do.

The practitioner of literate programming can be regarded as an essayist, whose main concern is with exposition and excellence of style. Such an author, with thesaurus in hand, chooses the names of variables carefully and explains what each variable means. He or she strives for a program that is comprehensible because its concepts have been introduced in an order that is best for human understanding, using a mixture of formal and informal methods that reinforce each other.

Literate Programming (1, Informative)

Anonymous Coward | more than 4 years ago | (#30343630)

Let us change our traditional attitude to the construction of programs: Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to human beings what we want a computer to do.

The practitioner of literate programming can be regarded as an essayist, whose main concern is with exposition and excellence of style.

The language which provides the capability to achieve all these goals is called COBOL. Ever heard of it?

Re:Literate Programming (3, Insightful)

CortoMaltese (828267) | more than 4 years ago | (#30343634)

Yup. I'd go as far as saying readability is more important than correctness; fixing or improving easy to understand programs is trivial compared to trying to decipher spaghetti code. You write code for other people, and that other people might be you a few years from now.

I'm afraid you can't really force this attitude on people by using coding standards etc. though. I think it's something every coder needs to figure out for themselves. Like Pragmatic Programmer says, "care about your craft".

Re:Literate Programming (1)

UnxMully (805504) | more than 4 years ago | (#30343760)

Yup. I'd go as far as saying readability is more important than correctness; fixing or improving easy to understand programs is trivial compared to trying to decipher spaghetti code. You write code for other people, and that other people might be you a few years from now.

Can I hold out for testable as well as readable? Tthe efficiency and quality gains you make from being able to run a suite of unit tests that confirm that the code still works as intended, or as you intend it to when you change it, shouldn't be underestimated.

Re:Literate Programming (1)

ClosedSource (238333) | more than 4 years ago | (#30344074)

"I'd go as far as saying readability is more important than correctness;"

This reminds me of the joke in the "My Fair Lady": "The French don't care what they do actually
      As long as they pronounce it properly"

Re:Literate Programming (0)

Anonymous Coward | more than 4 years ago | (#30343682)

Yes, I use a similar way of thinking.
I couple this way of thinking about source code (meant for humans to read even before computers) with personal face to face exchange of information, especially when handing over maintenance of a codebase to someone else.

Re:Literate Programming (3, Insightful)

joaommp (685612) | more than 4 years ago | (#30343736)

Let us change our traditional attitude to the construction of programs: Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to human beings what we want a computer to do.

I'm sorry, but I can't help but disagree with this sentence. The purpose of creating a program really is to instruct the computer what to do. Not to explain other human beings what we want the computer to do.
Computers don't do what we want, they do what we tell them to do. Success in programming a computer comes from telling it what we want it to do.
One must not compromise the precision of the orders it gives to the computer in order to achieve readability by something/someone else than the computer. One should, however, try to make his code as readable and elegant as he possibly can without sacrificing precision in the message to the computer.
If we program without prioritizing the computer, we may end up writing something that may look, to us and anyone else that reads it, like what we want the computer to do, but the computer my not take it that well...
I do understand and advocate the need for excellence in coding practices. I even teach it. But as so, I am also the first to tell that we should allow the need to have others understand what we want to sacrifice the absolute necessity of having the computer understanding just as much.

Re:Literate Programming (1)

joaommp (685612) | more than 4 years ago | (#30343754)

typo, correction

"I do understand and advocate the need for excellence in coding practices. I even teach it. But as so, I am also the first to tell that we should NOT allow the need to have others understand what we want to sacrifice the absolute necessity of having the computer understanding just as much."

Re:Literate Programming (3, Insightful)

John_Sauter (595980) | more than 4 years ago | (#30344012)

I do understand and advocate the need for excellence in coding practices. I even teach it. But as so, I am also the first to tell that we should NOT allow the need to have others understand what we want to sacrifice the absolute necessity of having the computer understanding just as much.

I think you are misconstruing the intent of Literate Programming. It isn't Programming if you aren't telling the computer what to do. Programming becomes Literate Programming when a person, reading your code, is also able to understand what you are telling the computer to do.

The first time I read a program, I ignore the code and look only at the comments. I hope to get a high-level understanding, so on the second read I can comprehend the details better. When I review my own code I do the same, and improve the comments if they don't convey an appropriate level of information.

Re:Literate Programming (1)

joaommp (685612) | more than 4 years ago | (#30344062)

I'm not challenging whether one tells the computer what to do or not. I'm challenging whether or not one tells the computer what he wants it to do. You can tell a computer to do something else than what you want it to do. It's easy... just do it wrong. And I'm just essaying on that sentence alone. I have not read the book, so that sentence is what I'm left with and is that sentence I'm deconstructing.

"elegant code" overhead coefficient (2, Interesting)

GrimNotepad (1400123) | more than 4 years ago | (#30343542)

In my company i am the sole/lead/only developer, and as such i have my own defined best practices and i follow them adamantly, that said i have written clever couplets of code that "just work" they are commented from here to the nines yet 4-6 months and 3 projects later when it comes time to look at reviewing for a possible update in the project i can sometimes look at it and have to spend extra time to follow the elegant code around to get it "loaded" back into my head to see what i did. i think that so long as programs are written by humans who can sometimes look at it sometimes as an art form there should always be an "elegant code" overhead coefficient worked into every project update.

Re:"elegant code" overhead coefficient (1)

maxume (22995) | more than 4 years ago | (#30343590)

For the sake of discussion, could you point to some code that you think is 'elegant' rather than 'simple', 'concise' and 'clear'?

Re:"elegant code" overhead coefficient (0)

Anonymous Coward | more than 4 years ago | (#30343708)

And I've wasted hours figuring out how object oriented "patterns" are supposed to work. Spent extra time to get it "loaded" into my mind. It's a huge waste of effort, institutionalized, because your typical developer can't handle straightforward abstractions like simple function definition.

I had one peer tell me to use a factory pattern instead of using "map". Stupid. It's a functor either way, and one of them is actually readable, keeps the algorithmic code together, and separate from the data code. Even better, the functional arguments to map form a monad, so (most importantly) I can keep calling list functions on the resulting lists. Big win for readability. For exampmle:

sort $ map {runMethod . dispatch_constructor} list_of_symbols

The factory pattern makes some assumptions about code. The functional code codifies our assumptions. It makes them clear.

Some OO patterns are so elegant they are just ontologically nasty. Yes, it is clever to pass around an object that represent behaviors for other classes to use. Great. Is that how you thought of objects when you first started? What kind of cognitive overhead is there for abusing the notion of an object, and coming up with a weird type system of patterns to combine?

Re:"elegant code" overhead coefficient (1)

dodobh (65811) | more than 4 years ago | (#30344110)

Using a factory when you have functional language style functions available is stupid. Take a look at Peter Norvig's presentation on design patterns in functional languages for what patterns from the GoF are redundant.

Subs and functions (2, Interesting)

A Friendly Troll (1017492) | more than 4 years ago | (#30343546)

A person whose code I regularly inherit seems to hate functions. He just writes subs with no parameters and uses global variables to pass information to and from them. It's awesome...

Re:Subs and functions (1)

Relic of the Future (118669) | more than 4 years ago | (#30343678)

No, the person whose code *I* inherit hates functions; a single 6 to 9 thousand line behemoth strewn out to a dozen levels deep with whiles, fors, and 20-wide else-if trees is something I've seen more than once. Parameterless sub functions would be a huge improvement.

Re:Subs and functions (1)

i.r.id10t (595143) | more than 4 years ago | (#30343762)

I tend to write like that until I see a particular piece of code being used a second time, esp. from a different location. Then it is time to include it in a functions file...

As a self taught programmer/code monkey, is there anything wrong with that?

Re:Subs and functions (1)

dodobh (65811) | more than 4 years ago | (#30343904)

This depends on the language you are working with, but a general rule is to have a function do one thing, and do it well. Follow the same rules for functions as for Unix programs.

You may find it useful to learn about Object Oriented Programming (at least about encapsulation, composition and inheritance from OO).

Learn a functional programming language like Haskell, Scheme or LISP. Those teach you about being able to build abstractions even in your code structure and the benefits of encapsulating state.

Learn a message passing language like Erlang (or an event driven framework).

Being able to separate your code into small logical pieces makes it easier to understand, test and maintain.

Re:Subs and functions (1)

Graff (532189) | more than 4 years ago | (#30343996)

I tend to write like that until I see a particular piece of code being used a second time, esp. from a different location. Then it is time to include it in a functions file...

As a self taught programmer/code monkey, is there anything wrong with that?

Yes, there is something wrong with that.

Technically I'm sure it all works but when you code code long stretches of code in one rambling function it becomes less focuses, difficult to read, harder to maintain, and you lose opportunities for code reuse.

First off: readability. Write a long, technically correct paragraph with a couple of dozen sentences. Now take that same paragraph and break it up into a couple of smaller paragraphs with 3 or 4 sentences each. Which is easier to read and follow? A long stretch of code has very few natural markers that allow you to parse what the code is doing. Remember that most humans can only hold so much in their short-term memory before they need to clean house. By breaking long stretches of code into smaller functions you provide context and limit the amount of information you need to keep active to understand the code. This means that the code is easier to understand, write, and maintain.

Another benefit is by having a couple of small functions verses one large one you make your code more modular. When your code blows up, and almost all code eventually does, it's much easier to refactor a small function than a large one. By using several small functions you limit the scope of the code you need to re-write, making the code much more easily maintained.

A great side-effect of small functions is that you start seeing many more opportunities for code reuse. Even if you have a large function without much repetition you might still actually have some nice sections of code that COULD be reused, if they were set apart from your large function. By breaking large functions down into small parts you help yourself to recognize those clever sections of code that would do well to be encapsulated in their own function and reused.

By encapsulating code into small, easily maintained, easily reused, functions that do a single thing well you greatly improve the quality of your code and make the job of programming much easier. Sure, what you are doing works for you and changing it might cramp your style for a bit but if you do make the change and stick with it you will become an even better programmer - especially when you work with others.

Re:Subs and functions (3, Insightful)

AB3A (192265) | more than 4 years ago | (#30343770)

Functions have their place, Subroutines have their place. Global variables have their place. Static variables, Heap variables, and stack variables have their place. Even a Go To has it's place (in rare cases).

The point is to use these tools in such a way that someone else can figure out what you're doing.

On the other hand, as Albert Einstein is reputed to have said, things should be simplified as much as possible, but no farther. If the code is obtuse, sometimes it is because the programmer doesn't understand the background of what it is supposed to do. In other words, if you understand Digital Signal Processing, someone's code may look quite elegant. If you don't understand it, it looks obtuse.

We'd all like to think that good programming is simply a matter of writing reasonably concise and well documented code. But it isn't. One needs an education on the subject being programmed. If you don't know the subject well enough, no amount of documentation is going to help you.

Best practices only go so far... (3, Informative)

djpretzel (891427) | more than 4 years ago | (#30343550)

"Quality" can be both objective and subjective, and it seems this post is leaning towards the latter in terms of what it's getting at... while I believe in having formalized guidelines of some kind, I've found the best way to seek out and improve the elements that can't be easily quantified is through (drum roll) code reviews/walkthroughs. It seems like these are rare, at least where I'm at, and it's hard to get buy-in when you're talking about contractors charging by the hour, but in my opinion a single quality code review can save TONS of time down the road and is necessary for projects over a certain size. Also, read "The Pragmatic Programmer" and "Code Complete" for some of the best guidance on this topic.

Re:Best practices only go so far... (1)

nietsch (112711) | more than 4 years ago | (#30343694)

So true. Because contractors are expensive, money people think that less is better. To get something done on time, little or no time will be spent on testing/review. Ugly hacks will always continue to 'work' which is what the client pays for.

What's worse that no documentation? (4, Insightful)

johnlcallaway (165670) | more than 4 years ago | (#30343556)

Incorrect documentation.

And the only correct documentation is the code itself. Anything else is a opinion and should be viewed accordingly.

In other words, when it comes to reading documentation ... trust .. but verify!

I don't know how many times over my 30 year career that I've read documentation and started work only to find out later that it hadn't been updated. The first standard in your documentation rules should be that all relevant documentation is created and updated before code goes into production. No excuses.

If it doesn't have that .. then the documentation is unreliable at best, and dangerous at worst.

Re:What's worse that no documentation? (1)

GrimNotepad (1400123) | more than 4 years ago | (#30343568)

best comment i have ever seen in the code i inherited is //insert comment here

Re:What's worse that no documentation? (1)

PolygamousRanchKid (1290638) | more than 4 years ago | (#30343690)

My favorite was in tcp_input.c in BSD code:

"This is ugly, but . . . "

Re:What's worse that no documentation? (1)

Lord Pillage (815466) | more than 4 years ago | (#30343968)

I came across a macro-laden hell one time when I was going through some C code with a comment:

This is right, but I hope the compiler can sort it out

This was followed by something like A(B((C(D))D(C))A2(C))....

Re:What's worse that no documentation? (1)

mclearn (86140) | more than 4 years ago | (#30343756)

I've always wondered if there was any (automated) way to at least give developers a fighting chance when dealing with out-of-date documentation.

My only experience using a source code manager is CVS -- sorry. But I'm sure SVN and Git are similar. CVS understands the sections of code that have changed. There are also numerous ways to parse languages. Can we not combine the two to determine if there is a so-called "significant" change (where this is a highly questionable quantifiable value) and, if so, reject the check-in unless the comment directly above it, beside it, (or whatever) has changed as well? Perhaps there are already tools that do this? I am not aware of them and I would be most interested if anyone has anecdotal stories about things they use at their workplace to try to automate this.

Of course, nothing will stop a motivated developer from eventually getting around such a stop-gap system, but this would be designed to HELP, not PREVENT.

Code != documentation (4, Insightful)

mveloso (325617) | more than 4 years ago | (#30344042)

As I've explained many times at work, code is not documentation.

Code only tells you what it does. It doesn't say why it was done that way...and the "why is it doing this" is really almost always the problem.

Review the Code (4, Insightful)

RAMMS+EIN (578166) | more than 4 years ago | (#30343562)

Review the code that gets checked in (you are using version control, are you?). If it doesn't obviously do what it is supposed to do (including the case where it is not obvious what it is supposed to do), something is wrong.

You can spend any amount of time writing best practices, but that doesn't ensure they are good, workable, and actually applied. In the end, what matters is if other people can understand the code. And you can measure that by just having them do that. As an added bonus, you get more people familiar with the code.

who said that? (1)

turbidostato (878842) | more than 4 years ago | (#30343566)

90% of code is rubish. Which should come to no surprise since 90% of everything is rubish.

The point here is that there're not so much qualitatively different high-level solutions to "the art of programming". The fact that after 30/40 years of repeating basically the same (obvious) things most of us can't cope with its basics shows the obvious: 90% of coders are rubish. The fact that 90% of coders think about themselves to be in the other 10% doesn't help, either.

Re:who said that? (0)

Anonymous Coward | more than 4 years ago | (#30343932)

90% of code is rubish.

This is an important insight, that the vast majority of code is, in fact, written by rubes.

Stop reading the code, stupid! (1, Funny)

Anonymous Coward | more than 4 years ago | (#30343572)

Works for congress.

Not Here! (1, Insightful)

Anonymous Coward | more than 4 years ago | (#30343580)

I wouldn't ask here. Some of the worst code advice I've ever seen comes from Slashdot, especially from the idiots who think all programming is like their PC or Linux box. The worst are those that think Java is suitable for everything, or that what's good for the web is good for every situation.

Re:Not Here! (1)

nietsch (112711) | more than 4 years ago | (#30343650)

Quality of advice is not measured by the worst piece, but but the quality of the advice you take to heart. So who cares that someone recommended java for kernel programming? If only the best is good enough, you get nowhere fast. accepting different opinions and using your own head gives you better ideas, because you can discard the bad ones. The OP came here for good ideas...

Comments and standard libraries are useful (1)

TheLink (130905) | more than 4 years ago | (#30343592)

Even if they themselves aren't useful, they might give you an idea of how crap or "clever" the code is at some point ;).

Anyway, to me one very important good coding practice is using standard or defacto standard libraries where possible instead of rolling your own (unless it means using those libraries in "rube goldberg" ways, in which case roll your own).

Because it means less to document, maintain and also it makes for easier debugging - because when you see "standard library method/function" you know what it does, you don't have to look it up and check it.

Whereas if the program is filled with custom library methods (even when standard ones that do the same thing exist) you will have a lot more work to figure out why and whether they do what you think they do and what they are supposed to do.

And that's why in the real world, writing in certain languages is better than in others, if it means you end up writing less code of your own. It doesn't matter if the language is so cool and powerful that you can write code that does zillions of stuff, but if it means you have to rewrite lots of stuff that would be standard in other languages, it's not as maintainable.

Yes in some scenarios you want a powerful language that helps you in the code that you write. But in most scenarios, you'd want a language that helps you in the code that you don't have to write ;).

Train your programmers (1)

Alain Williams (2972) | more than 4 years ago | (#30343602)

He gives a few things that he calls CRAP and then goes on to extol the GNU programming style. I do agree that documentation is key, the problem is that many people say that they will ''add the comments after the code is debugged'' - this is what is wrong, you write the comments when you write the code, if you change the code 6 times you change the comments 6 times.

I fear that he is really trying to bring everyone down to the level of the novice programmer rather than raising the standard. I have met managers like that, they say things like ''we won't do that here'' (meaning: ''I have not seen that construct before and am afraid of something new''); ''goto is forbidden'' (meaning: ''someone important said goto is harmful'' - not having understood that Dijkstra was talking about code where 25% of statements were goto - in the days fore things like while loops).

We need to educate programmers, make them better - not dumb down programming.

What is clear to one ... (3, Insightful)

WoodstockJeff (568111) | more than 4 years ago | (#30343622)

I work in an environment where there are 4 programmers, of varying skill. What is "clear" to one is not necessarily clear to another, even if it is straight-forward coding. For example, I might program a loop to iterate through an array of data, extracting the important information, while another might explicitly write out each iteration, because he is less familiar with arrays. His code is quite clear - but inflexible, and subject to errors if he makes a required change to 19 of 20 copies of the calculations. Mine is quite clear, but subject to some obscuration if there's something special that has to be done in 3 of the 20 iterations.

In the case of TFA, if the author were this other programmer, he might consider my code to be "too clever".

Much was made of the use of "obscure" variables. Yes, that's one I dislike a lot, too... but I haven't made too much progress on that score in 25 years, with regard to others. When you're working on code that requires a lot of manipulation of a variable, typing a long, descriptive name 65 times is a bit of a PITA, and subject to its own bugs, when you misspell it a few times!

Re:What is clear to one ... (2, Insightful)

Relic of the Future (118669) | more than 4 years ago | (#30343692)

typing a long, descriptive name 65 times is a bit of a PITA, and subject to its own bugs, when you misspell it a few times!

Learn to use autocomplete.

Re:What is clear to one ... (1)

tepples (727027) | more than 4 years ago | (#30343806)

Learn to use autocomplete.

Then how do I teach an editor to allow autocomplete for a given language?

Re:What is clear to one ... (0)

Anonymous Coward | more than 4 years ago | (#30344186)

meta-x given-language-mode

as the gods of Emacs intended. or, if you are a god of Emacs, start writing the elisp module.

Re:What is clear to one ... (0)

Anonymous Coward | more than 4 years ago | (#30343734)

Exactly - verbosity (I mean not in variable names, which should be descriptive, but in how the code is written) makes things easier for novice programmers, but has a serious maintainability cost. I've worked on highly complex pieces of software, and constantly struggle with this: when a change in behaviour is needed, I can accomplish it with a few lines changed in 5 minutes, but several others spend a week re-writing large amounts of their code because the required thing is not well encapsulated.

There's an inverse relationship between the level of abstraction and expressive power. I believe in high levels of abstraction coupled with well commented code and long-ish descriptive names. Others favour high levels of abstraction with terse names, which is very hard for anyone else to make sense of. Yet others favour low levels of abstraction because they do not understand the higher level ones. The problem with that approach is that there can be many orders of magnitude difference in what such "low abstraction" programmers can accomplish. I'll take a shop of 5 programmers highly proficient in powerful techniques, over one of 75 "low abstraction level" programmers.

Excessive code verbosity also has an obscurity all its own. When I see 60 lines of code doing what could be done in 1 or 2 lines, it's very hard for me to read such code, because not very much functionality fits on my screen at once. I can't see the high level picture because the low level details are taking up so much space.

Re:What is clear to one ... (1)

Jeremi (14640) | more than 4 years ago | (#30343826)

When you're working on code that requires a lot of manipulation of a variable, typing a long, descriptive name 65 times is a bit of a PITA, and subject to its own bugs, when you misspell it a few times!

Only in a language that doesn't require you to explicitly declare variables. In a reasonable language, any typos in your long variable name will result in compile-time errors and will therefore be caught and fixed the next time you compile the program.

In fact, the only time when a typo in a variable name should compile is if there is another variable declared with the typo name. The chances of that happening are much smaller when you're using long variable names than short ones.

Baffled, what ancient age are you from? (1)

mauddib~ (126018) | more than 4 years ago | (#30343638)

I'm baffled. Here we use extensive extra documentation, mostly outside of the code. Programming changes are related to changes in design documents and deployment documents. Also most of the design follows UML diagrams which are thoroughly kept together with all programming code. As far as we use programming code, every change is reviewed by another developer. Without these, we would quickly lose our minds, heads and bodies to the massive complexity.

I always thought NASA was one of the top quality software engineers, but apparently not in every department.

Lowest Common Denominator (0, Insightful)

Anonymous Coward | more than 4 years ago | (#30343666)

Why should I write my code so that the lowest-common-denominator dull thud who took CSci just for the money can come along five years later and maintain it? I agree that good coding practices produce readable code. But too often this whole topic leads into the idea that all code should be McCode, meaning blah standards-conforming blocks, often not even approaching the best possible solution to a problem.

Sorry. Not a priority. And no, I don't care that you won't hire me. You want an assembly line slinger. And will pay accordingly.

Re:Lowest Common Denominator (3, Insightful)

tepples (727027) | more than 4 years ago | (#30343822)

Why should I write my code so that the lowest-common-denominator dull thud who took CSci just for the money can come along five years later and maintain it?

No, so that you can come along five years later and maintain it.

Code Reviews (Gerrit) (2, Informative)

jtolds (413336) | more than 4 years ago | (#30343674)

Traditional everyone set aside time and review checked in code is hard to do, difficult, and time consuming.

On the other hand, automated code review tools are life changing. There's a bunch of tools out there, but the one I think is far and away the best is Google's Gerrit tool (http://code.google.com/p/gerrit/), which is what Google uses publicly for Android.

I cannot understate how helpful Gerrit has been in this regard. So many things that are trouble down the road are easily caught by even just one other pair of eyes. Everyone who has used Gerrit at my compnay has fallen in love with automated code reviews. It's refreshing, leads to better code, etc. I seriously could gush about Gerrit for pages.

The same logic isn't common in everyone (1)

techhead79 (1517299) | more than 4 years ago | (#30343688)

As we all know just about every coder has their own way of doing things. Each person has found the solution to common programming steps differently. This flow of logic is carried over to larger programs and new logic that must be considered to answer more complex coding problems. There is no one way to write a program and this means there are a thousand different ways each person could come up with the logic paths to answer the question. Clever cures boredom and does what every programmer should be doing...making their program more efficient....

What makes sense to one person is a combination of how they answered similar problems and other coder's answer to similar problems. There are many hacks in the industry that cause a lot of problems for code readability. They are not clever, they are the other extreme where they barely understand what is even going on. Any real coder though can see the difference between being clever and being a hack, it usually involves comments carried over from what program they gutted to get their's to work. I think it's important to separate those two types of problems.

Once you take out the hacks you should be able to see how any coder reached the logic they did. Rewrites because of logic doesn't just stand at the one coder required to maintain class xyz. Shit falls down hill. If the overall design is flawed, if the requirements are not clearly outlined, if someone high up keeps changing their mind..then the coder at the bottom of the hill doesn't stand a chance at writing long term good code. Anyone that's worked in a project knows there is this odd relationship that forms. You have the heavy coders, you have the logic gurus looking at the bigger picture and delegating, you have the do what you cans that are left the scraps after the heavy coders get their work, you have the project leaders which hopefully will be writing code too, you have the project owners that write no code, you have the upper management barking orders. There isn't just 1 person responsible for good code even if there is just 1 person writing it.

communication is key, not just documentation (2, Insightful)

Kartoffel (30238) | more than 4 years ago | (#30343726)

One person's clever, obscure trick is another person's common practice.

Communicate with the other coders in your project. Write decent comments. TALK to the other coders. Cooperate and share ideas.

Re:communication is key, not just documentation (1)

lytles (24756) | more than 4 years ago | (#30343882)

One person's clever, obscure trick is another person's common practice.

i guess i'm the evil programmer type - i read the article for the sake of seeing some clever tricks. i stopped reading after his first example ... not clever at all, not obscure at all, no need to comment, no need for fancy variable names, no nothing ... and i don't think i've coded in c in 5 years

for(ss = s->ss; ss; ss = ss->ss);

if there's any ambiguity about what that line is doing, you're not qualified to be commenting on anyone else's code

Optimize all the time... for clarity (2, Insightful)

noidentity (188756) | more than 4 years ago | (#30343740)

Optimization is fine, as long as you're "optimizing" the code to be more clear. This is a good way to redirect the energy that programmers often put into pointless performance optimization. Most understand that optimizing for one thing often de-optimizes somthing else, so they understand that you can't optimize for speed and clarity in many cases. Always looking for ways to make code clearer can become an enjoyable habit, as optimizing for speed is for many. Then you spend your idle moments eliminating many lines of code that you realize are unnecessary, bringing the code closer to its essence. My experience anyway.

I've ignored this non-problem for years (1)

OrangeTide (124937) | more than 4 years ago | (#30343742)

At the last few places I've worked we found that just ignoring this problem long enough lets it just go away. People who have style and coding practices that are bad, end up changing them eventually or leaving. And people with good practices tend to have success with their software, even if the styles end up being different from one another.

If you can't wait for the problem to sort itself out, then try hiring a bunch of good people that have worked together before.

Practices.. (1)

JoeZilla (150219) | more than 4 years ago | (#30343746)

When will people finally realize that defining and documenting practices alone doesn't make good code? You need good programmers that care and that monitor each others and (more junior) programmers' code quality. Encourage feedback between the programmers, etc.

The only thing which counts for businesses (1)

kipsate (314423) | more than 4 years ago | (#30343764)

is releasing new functionality as quickly as possible. Timelines counts, not code quality.

One of the classic arguments between manager and coder is about how much time should be invested in cleaner code, since, as most coders would argue, such investment earns itself back because new features can be implemented faster when having a nice and tidy code base.

Managers of course often get their ways and coders reluctantly give in, mumbling about code becoming unmaintainable.

Investing in code quality is indeed risky:

- Even despite poor code quality, the coders know their stuff and implement new functionality without any problems;
- After investing in code cleanups it may soon turn out that this particular functionality is no longer required and all this nice and tidy code has been developed for nothing;
- "Cleanups" may end up in overly complicated code which turns out to be even more difficult to maintain than the original code base.

Rule of thumb (4, Insightful)

xororand (860319) | more than 4 years ago | (#30343766)

"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it."

The solution to bad comments is good comments (0)

Anonymous Coward | more than 4 years ago | (#30343778)

There is no such thing as self-documenting code. A block of code without comments, no matter how well-written, is an order of magnitude slower to work with than code with just a couple of sentences at the top explaining what is going on and why. I find this "comments are always out-of-date anyway" argument baffling. If that's the problem, then the solution is to make keeping comments up-to-date a key part of the requirements, not to omit them entirely.

If someone lacks the discipline or intelligence to update a simple sentence after making a change, then their 'self-documenting code' is not something I ever want to see.

All code is obscure to the incompetent. (0, Insightful)

Anonymous Coward | more than 4 years ago | (#30343792)

for(ss = s->ss; ss; ss = ss->ss);

Pretty standard way to traverse a linked list.

Re:All code is obscure to the incompetent. (1)

jlowery (47102) | more than 4 years ago | (#30344114)

To get to the first 0 pointer in the list? Perhaps, but what if the list is very large? Wouldn't a wrapping class that maintains the list's last node work faster?

What do 's' and 'ss' stand for?

Sane source control is critical (1)

Antique Geekmeister (740220) | more than 4 years ago | (#30343804)

Using good source control helps, a lot. I've gotten very fond of git and its ancestror for style though not code, BitKeeper, because they let you do work locally and submit it centrally when you're ready.

Also, if your "coding standard" isn't built into your editors and common tools, you're doing something wrong. For example, if your C++ standard is not consistent with 'indent', you're doing something wrong.

what? (0)

Anonymous Coward | more than 4 years ago | (#30343812)

why do we call this 'clever'?
clever as opposed to what, stupid?
maybe 'obscure' would have been a better word...
imho, the Linux Kernel Coding Style is the best.

I may have to give up (1)

some-old-geek (1329305) | more than 4 years ago | (#30343816)

First, I suggest a perusal of Capers Jones' book Software Assessments, Benchmarks, and Best Practices, from which we learn that most of the cost of internally developed systems (the sort TFA is talking about) is in maintenance. So there should be no argument that making the code maintainable is of some high priority.

[f/x: get off my lawn] Sadly, there are many programmers who don't understand that maintenance is not the act of rewriting the system in a language they would like on their resume. That might be adaptive maintenance, but the lion's share of maintenance actually involves fixing that which is broken (this would be corrective, perfective, and preventive maintenance).

Sadly (again) we already know the answer to the OP's question. You need an enforcement mechanism. The cheap and easy way to implement that is via code reviews. And we know that isn't going to happen.

Why? Because too many people who get to make decisions don't want to believe that first item from Jones' book. Making an innovative change to a UI is sexy, makes it obvious that some work has been done. Bullet-proofing user input edits is mundane, and smacks of cubicality.

You are unlikely to get a commitment from management to let you do things "the right way." If you did, you would have no way of knowing that it won't be rescinded when the boss' kid gets a job programming in the cubicle next to you.

The only way I know of to make this work is peer pressure. And that is unreliable. Thus maintenance will always have at least some aspect of the "fix what the clever kid did" to it.

Coding style (1)

tomhath (637240) | more than 4 years ago | (#30343834)

Coding style is a no brainer for most languages: Use the default that your IDE provides. Or lacking that, whatever the "prittyprinter" program produces. If someone violates the style convention, the IDE or pretty printer will clean it up. Design reviews, code reviews, and updated documentation are unquestionably good ideas but they have to be budgeted in at the start. A project manager who's afraid of missing a delivery will treat them as slack in the schedule and let them go even faster than they will squeeze the testing schedule (but that's another story).

author seems somewhat confused and inexperienced (5, Informative)

bcrowell (177657) | more than 4 years ago | (#30343838)

The author of TFA seems somewhat confused and inexperienced.

  1. "Most of the variables in CRAP are one or two letters long. Originally, this was due to the memory constraints involved when programmers first designed and built the system." This is not particularly plausible. C is a compiled language, so using long variable names has no effect on the amount of memory used at run-time. It would also have been more or less a non-issue in terms of RAM used at compile-time. C only dates back to 1972, and didn't start to get popular until ca. 1980. By that time, using long variable names would have had a pretty negligible effect on RAM used by the compiler in proportion to total available RAM. And in any case, if compiles are taking too long, you just break up your files into smaller parts.
  2. He uses this code "for(ss = s->ss; ss; ss = ss->ss);" as an example of bad code: "For those of you that are interested, the line traverses a linked-list of sources and sub-sources to process the values inside. But it took a good deal of research to figure that out, because there were no comments and the variable names, well, suck." Well, I read that and said to myself, "It's traversing a linked list." I think what's really going on here is that the author is probably a programmer who learned to program relatively recently with C++ and Java (he says in TFA that those are the languages he's used to), and he's used to doing things with big OOP libraries. The culture he's been inculcated in is one in which you never have to understand how a linked list is actually implemented, because you just use a library for it. To anyone who's actually implemented a linked list in a language that uses pointers, it is fairly obvious what this code does. It shouldn't take "a good deal of research" to figure it out.

Linked list (1)

tylersoze (789256) | more than 4 years ago | (#30343850)

for(ss = s->ss; ss; ss = ss->ss);

Really? An idiomatic linked list traversal is too hard to understand? Does this guy think find postfix increment (++) too confusing too?

I admit though it is confusing if the semicolon at the end isn't a typo. Is this straight C or C++? I can't imagine that statement actually doing anything useful unless there's some kind of C++ operator overloading going.

Re:Linked list (3, Insightful)

TheSunborn (68004) | more than 4 years ago | (#30344006)

While I don't understand why he did have a problem with seeing that this is a linked list traversel, I think he do have a point about fucked up naming, because in what implementation would you call the node to the next element ss instead of next, or nextNode.

Re:Linked list (0)

Anonymous Coward | more than 4 years ago | (#30344184)

I had the same thought as you - that line of code did not seem terribly opaque. But I think there is an understandability issue here. "s" and "ss" are just painful variable names, especially when ss is also a field. The over use of s's obscures what (I think) is going on here, which is that "s" is a struct containing a linked list "ss", which is then walked over. It is not really even clear to me whether "s" and "ss" have the same type. Is "s" a linked list, and this traversal is skipping the first element? Or is "ss" a list element of "s", which we are then iterating over? For me, most of the confusion comes in the initializer statement. The rest, as you say, is an idiomatic traversal.

Of course, using Java-style idioms does not make this line much better:

for (ss = s.getNext(); ss != null; ss = ss.getNext())

Although here it is clear that I've gone with the "s is itself a list and we're skipping the first element" approach, rather than:

for (ss = s.getList(); ss != null; ss = ss.getNext())

Of course, the verbosity here is unpalatable... if we go with next() instead of getNext(), it's far better, IMO.

Finally,

I admit though it is confusing if the semicolon at the end isn't a typo. Is this straight C or C++? I can't imagine that statement actually doing anything useful unless there's some kind of C++ operator overloading going.

I think he was just trying to show the loop conditions, and not the body.

That said, I *despise* operator overloading for precisely the reason you indicated: it is impossible to tell what any given statement is doing because your basic, built-in operators can do bizarrely different things! To build on examples you've given, with C++ iterators, the postfix increment "ss++" now means "ss=ss->ss"! Madness!

Too MUCH of this (2, Insightful)

omb (759389) | more than 4 years ago | (#30343900)

There is increasingly a meme that pretty code in a strongly typed language id OK, everything else is CRAP.

Well no, neatly written code, in whatever, is good, as are good code and clear comments where they are needed, ie NOT,

i = i++; //increment i

Some of the worst code I have seen written is in C++, Java and C#. OO over the top, full of OO jargon, code that wanders around a thousand method calls without solving the problem, and TOO MUCH CODE, zillions of complex libraries and dependancies.

Clarity, order and simplicity are the secret of writing good code, not language, tools or methodologies, and then it can be written in anything from Lisp to C#.

keep it simply stated (1)

God of Lemmings (455435) | more than 4 years ago | (#30343916)

Our workplace is such that everything has to be easy to follow and understandable with a glance. This is not necessarily because someone else will be working on our code so much as that we almost certainly end up coming back to it 6-12 months later, or that the person writing it won't be the person maintaining it or porting it.

If it isn't easy to follow, you can usually fix this by spreading out the code and inserting more comments, and avoiding shorthand statements like inline ternary that save typing, but don't enhance readability. Inline comments are uncommon, instead varying kinds of flower-boxes before a section of code. In general, it ends up that being clever requires much more commenting in the flower box to explain functionality, so in the end it becomes a wasted effort.

A few days ago I saw someone going around with this sig from Brian Kernighan;
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.

Teams (5, Insightful)

jlowery (47102) | more than 4 years ago | (#30343918)

I've worked with teams a large percentage of (supposedly) hotshot programmers, and on teams with a similar percentage of mediocre talent. In my experience, it is the team with the so-so developers that deliver the more maintainable code. Why? I think it's because they know their limitations and are not afraid to "talk out the process" of writing code. They ask for feedback and opinion.

What that leads to is a collaborative development process, where everyone has some idea of what the other is doing. And in these environments, for some reason, people take ownership and responsibility for their code, end-to-end.

Contrast that with the hotshot teams: they know too much to ask for help, resent questioning of their implementation, mess around in other peoples domain "because they know better", and engage in heated arguments over trivial or religious matters. And in the final analysis, the lack of cooperation leads to disfunctional interfaces between components, idiosyncratic code, and incomplete functionality or low-quality performance.

Whereas the so-so teams learn to collaborate to get things done, the hotshot teams rely on heroics: they take on too much, show exaggerated progress by declaring their code complete even though it fails edge cases, and then spend outrageous overtime fixing 'bugs' (or worse, they're too important to work on bugs, they do features, so the lesser mortals on the team get to clean up after them). Because bug fixing doesn't get scheduled up front, the schedule slides and more work hours are demanded to catch up (with decreasing effect).

To my mind, the MAIN criteria for arriving at a maintainable codebase is OWNERSHIP, OPENNESS, and COLLABORATION. A collaborative team can do more in 40 hours than a heroic team can do in 60. They just don't look so impressive.

While I'm not an expert developer.... (1)

MrCrassic (994046) | more than 4 years ago | (#30343930)

The one job that I did have as one made me realize exactly how uncommon it is in corporate-level work to find code with nice, detailed comments describing what's going on where. I will blame the lack of comments for one project I was assigned taking months to complete rather than weeks or days, especially considering that it was pure Java Swing code (i.e. no NetBeans), which is especially infuriating to work with.

Code Review is only part of the solution. (1)

TimCostantino (1694318) | more than 4 years ago | (#30343938)

Changing someones development practices is a kin to changing any other behavior, I.E. hard to do.

I've found that code reviews offer a good barometer of where everyone is on the behavior chart but it is not enough to make a significant change to the behavior.

Here are few items that I find essential:
1) Maintainability Must be a priority: The architect\tech lead on the project must make this a priority. Simple code must be reinforced at all stages of development. This means new development must wait for previous development to be refactored into simpler code.

2) Shared understanding: The team MUST recognize the importance of this requirement. If they don't then the constant reinforcement will seem more like nagging, nit-picking than anything else. Have the entire team read "Clean Code" send out the Daily WTF articles. Jokingly pass out the bad code offsets.

3) One on One Coaching: Often complicated code is written simply because the simpler solution was not obvious. To help overcome this, team members should help each other with refactoring efforts. As an example: Interfaces and factories are often seen as "To complex to be simple" by junior developers. Consequently, it is the responsibility of the entire team to help teach why these "more complicated" solutions are actually much simpler and cleaner than the alternative.

4) Constant Communication: As with all creative work, whether you've accomplished the goal is very subjective. This means the team must have constant discussion, and sometimes debates, on what is maintainable. If you are the tech lead, be sure to show examples of your own code that is sub-par, and then discuss how it can be improved. If you don't have samples of sub-par code, you need to start writing more code. I can't emphasize enough that the tech lead must use their own bad code as examples, this helps create an open environment where people feel free to make mistakes and ultimately learn how to write better code.

Well that's my two cents as I sit here getting ready for Football to start. (c:

Test Driven Development (1)

ixl (811473) | more than 4 years ago | (#30343946)

TDD, TDD, and more TDD. If it's too clever to maintain, than it's not testable. When done properly, test driven development functions very well as a guard against that sort of thing. The converse is also true, by the way. If something is very clever, but written in a testable way, than it's likely to be maintainable and easy to read. Even if it's not easy to read, the tests allow it to be refactored into an easy to read form without breaking anything.

Perl Critic (1)

Herkum01 (592704) | more than 4 years ago | (#30343952)

Perl has probably got one of the best coding analytic suites in Perl::Critic. It addresses numerous areas dealing with Best Practices and addresses certain types of bugs. It is also highly configurable and easy to write your own rules as well.

The hardest part was actually getting people to use it. The fact is, there are a lot of people who have a ego and rather inflexible about changing their habits. The other side of the business will not care unless it can be shown it is a common practice or directly impacts money. So it is a tough battle to fight and most people are just not willing to get involved with it.

I wrote my own platform (1)

holophrastic (221104) | more than 4 years ago | (#30344014)

...for web development. And the primary goal of this platorm is to make doing typical things very straightforward, and easy-to-do-right and hard-to-do-differently. Commenting teh code itself is completely useless because the code reads fluidly. So comments are limited to what isn't programmed, or what has been removed for good reason.

Some advantages are quite clear when it comes to security things like user permissions and sql injection avoidance. The platform makes it horribly difficult to do those kinds of things in the traditional way, and really easy to do it in the consistent way.

So the rule really is that if it's difficult to write, and it looks like carp when you're done, then there is a proper way to do it.

It's what a friend of mine has been saying for years. It's not enough to make good code look good. You've got to make bad code look bad.

Treat comment bugs like code bugs (2, Insightful)

presidenteloco (659168) | more than 4 years ago | (#30344050)

They are just as serious. Updating/"maintaining" a piece of code and not updating the comment
should be made into close to a firing offense, after the suitable number of admonitions.

The biggest weakness I find with code I review is that the programmers seem to be either
inarticulate, lazy, smug, or exhibiting Aspergers syndrome (lack of empathy), in that they forget to
include the most important comment for any method or class;

The "What the h*ll is this?" comment that explains the gist of the method/class and why and
in what contexts one should care about it.

Also frequently missing is the considerate: "Mind the low headroom" comment.

I've never had an enjoyable experience with this.. (0)

Anonymous Coward | more than 4 years ago | (#30344142)

One company I worked at, when we sat down to discuss basic coding standards at the start of the project one of the developers whined and whined and wouldn't give up on one very stupid point. He was in his 60s and he claimed that he had used 2 spaces instead of 4 his whole life because it fit better on dot matrix printer paper. We pointed out that 2 spaces looks less readable and 4 looked fine on todays printers and fonts. He wouldn't give up and it was prolonging the start of the project indefinitely to the point where management said fine just use 2 then. So, we were all stuck using 2 spaces, which led to a giant war during development. We were all using Eclipse, so anytime he would write a piece of code with 2 spaces, the rest of us would would click Format document and cause all his 2 spaces to turn to 4 automatically and then re-commit. Which would make him cry, while the rest of us laughed. Essentially, majority won, but thank god for auto-format otherwise we wouldn't have been able to stay sane at that job.

Therefore, it is my opinion, that coding standards are crap. And, the only coding standard you need is to abide by whatever auto-formatting that Eclipse or your preferred IDE provides. As far as working out concepts like modularity and that sort of thing, simply refer to refactoring rules in design patterns and you'll do great. Enough said, now get coding and stop wasting time discussing nonsense.

Testability (1)

cmsjr (1515283) | more than 4 years ago | (#30344158)

While coding style is certainly important, the most clearly written, nicely commented, richly documented source possible can't tell you if the code does what it's intended to. Formal coding standards may help mitigate the difficulty of debugging and modifying a program, but I think can you get a lot more bang for your buck by implementing a solid testing framework. If I had to pick between coding behind someone with great style, or someone with great unit tests, I'd take the latter.

Names, meanings, code documentation & culture (0)

Anonymous Coward | more than 4 years ago | (#30344176)

Meaning is very problematic beast. Philosophers has know already for few centuries how difficult it is to define proper names and point how meaning is bound to words or other constructs. If I have understood some what modern day consensus of philosophers any language will always be more or less defined for small audiences. To say that in practical way tech talk is talked by techies to techies. So called general language that can be heard in news or such will not cut, it just lacks practical way of saying difficult things e.g. news for nerds are not written same way as CNN articles.

Where does that lead us? Code documentation, style and even variable names can be meaningful and sensible activity, but only within limits of programming culture. It is waste of time to teach non programmers to understand 'this particular' code. Non programmers should first learn programming culture and then they should be able to understand. I understand many of you will say that there is no such thing as homogenous programming culture. In that you are absolutely right, and wrong. For example intending code is better than not intending, but we can argue till end of time is correct intend 4 or 8 chars. Programming languages have idiomatic expressions, one should always favor them. This sort of 'rules' are part of culture. But culture is greater construct than set or rules. In order to understand variable names for example one has to take a look of hackers dictionary (foo, bar, zyxxy...). Some times there are references to geek popular culture (I've seen magical number 42 too often that it would be just a coincident).

Defining coding practices is a very difficult task. The definition should match with culture and limit possibilities provided by culture. Paradoxes are hard to crack.

elegant != clever (4, Insightful)

dsoltesz (563978) | more than 4 years ago | (#30344178)

Elegant and clever are not the same thing.

Elegant describes the algorithm or solution as using resources efficiently, having no unnecessary steps in getting to the solution, and easily readable to another programmer familiar with the subject at hand (as AB3A mentioned inre to DSP).

Yes, if we use Webster's definition, there is a certain amount of "cleverness" in beautiful, elegant code. However, when we say "clever" we usually mean cutesy-clever, like mashing several traditional lines of code into a one-liner. That's fine for a geeky contest of "who can write this using the fewest number of characters," but (as most of us agree) does not have a place in professional code. One-liners and similar stunts might be clever, but are rarely elegant, and cause headaches for later maintainers of the code.

Load More Comments
Slashdot Account

Need an Account?

Forgot your password?

Don't worry, we never post anything without your permission.

Submission Text Formatting Tips

We support a small subset of HTML, namely these tags:

  • b
  • i
  • p
  • br
  • a
  • ol
  • ul
  • li
  • dl
  • dt
  • dd
  • em
  • strong
  • tt
  • blockquote
  • div
  • quote
  • ecode

"ecode" can be used for code snippets, for example:

<ecode>    while(1) { do_something(); } </ecode>
Sign up for Slashdot Newsletters
Create a Slashdot Account

Loading...