What Workplace Coding Practices Do You Use? 682
Agent_9191 asks: "Recently I've been promoted to what essentially amounts to a project lead role for every project we do, in house. Since my company has run for the past 35+ years with no form of central IT department, there has been no standards put into place for developers to abide by. One of my tasks is to set up standards in how projects will be implemented and produced. Right now I'm more concerned about trying to set up coding standards, so that any developer can jump into any part of a project and be able to figure out what's going on, without wasting a couple hours just to figure out the code. I've come across some documents in this area from a few sources (of course can't remember them off the top of my head). What practices/standards do you use in your workplace?"
Comments (Score:5, Insightful)
Evolutionary Prototyping (Score:5, Insightful)
It's nearly impossible for me to get final specifications from a user until they've actually seen something. Paper is okay in a pinch, but a semi-functioning web application is worth a thousand meetings.
Unrealistic expectations (Score:4, Insightful)
Unless you are dealing with trivial projects it will take more than a couple of hours to figure out the code. Even the best documented open source and commercial projects take a few days to figure out.
GOOD code review; Chief Designer at every inspecti (Score:5, Insightful)
And good unit test drivers.
Awesome commentary (both at the top of a package outlining the entire low-level design and at the algorithm level) goes without saying.
Oh yeah, and run spell on your code. I mean, really!
Looking for magic? (Score:5, Insightful)
That is a pipedream. Any project of significant size will require some immersion before a new proj member can get his hands around the particular bit he's trying code/solve.
Standards can be good, but they're not magical. Unless you're trying to generate a group of little robots, everyone has a slightly different style.
GOOMOALMWIP/GOOMCALMWIP (Score:3, Insightful)
or
Get Out Of My Cubicle And Let Me Work In Peace
This applies mostly to the people that come in and have to inform me of their new cat, girlfriend, boyfriend, computer, game, TV, kitchen, car, shoes, and/or midlife crisis (and that's just the top of the list).
A request on the part of the devs under your control: Don't implement a new paradigm every time one comes out. From extreme programming to agile programming, from scrums to design workshops, find something that works in your particular case and stick to it. Your employees will thank you for it (at least in the long run by not planning your demise in the parking lot after the fifth methodology change that quarter).
loose standards are best (Score:1, Insightful)
So if you are going to have standards make sure they are loose, and pertain mostly to external interfaces etc. requiring comments or code descriptions or something. I am telling you the worst thing for a project is frustrated programmers because they will make shortcuts in the code. Trust your developers
Coding Practices (Score:5, Insightful)
Re:Comments (Score:3, Insightful)
You shouldn't be using magic numbers anyway - use a #define so that the comments and code stay the same regardless of what the value happens to be.
Instead of
function(1);
try
#define LOAD_DATA 1
function(LOAD_DATA);
Then you don't need to care what LOAD_DATA is.
Specs, reviews & tools are the real key (Score:2, Insightful)
Also key is a standard process of developer peer reviews. All developers should have peers review specs. New or mediocre developers should have their code peer reviewed. Proven developers can be excused the code review but not the spec review.
Experience counts (Score:4, Insightful)
My suggestion is get someone who has done this in a structured and successful environment. Otherwise developers will roll you over and your projects will be late, over budget and buggy.
I have seen it so many times where an internal inexperienced person jumps in the saddle without mentorship and guidance in the areas of software development (NT or UNIX) and systems management not native to the environment. And I have seen how long companies suffer with the problems created by this and how much it costs companies in the end. It makes a $1000 per hour consultant look cheap.
A good example is code management. Very few IT shops have it. Why? No one wants to know who checked in the buggy code! But few developers want such tools, especially the microwave generation. But at least when your caffeine isn't good enough and they move on you will know where the source code is.
Sounds simple? Not really, there are hundreds of issues like the one above. And it can't be taught quickly.
So get a consultant for 6 to 12 months that has done this, listen and learn and you will be off to a fast start.
Pottery Barn rule (Score:1, Insightful)
My boss on the other hand, it's more like the bull in china shop. Heck if I know how he got in there, but I know there is going to be heck to pay in the morning.
Re:Comments (Score:5, Insightful)
Actually, IMHO, those are bad comments. Too much commenting, while not as bad as too little commenting, is still a problem. Writing too many comments is not only time consuming for the developer, but it makes it harder to find the important comments in the sea of crap. Also, if the program is modified, all the comments must be changed as well. This can be a tedious and time consuming process for large projects.
Personally, I try to use comments for parts in the code that might be confusing. Even for a novice programmer, code like if(x == 456) is self-explanatory, no comments are needed. But complicated statements involving many different variables from different parts of the file may be confusing, and likewise merit comments. Also, comments with input/output or precondition/postcondition for functions might not be a bad idea either.
Use comments when you need them, but don't write so many comments that they become useless.
Re:A Good Coffee Break (Score:2, Insightful)
That and something to scribble on. Either lots of paper or a whiteboard. Whiteboards are cool for getting your thoughts organized. Unfortunately you can't make printouts afterwards...but a good digital camera snapshot of a whiteboard will give you enough to remind you of what you thought up.
The general hint -- give yourself some time to step back from the problem. There are times when it's good to bury yourself in the code and times when it's better to think things through away from the code.
Programming Standards (Score:5, Insightful)
That's Like Scrum... (Score:3, Insightful)
I find that a good standard for code reviews is to assume that the programmer knows what he's doing and I don't try to push my political agenda in them. If you want to have a passionate argument about hungarian notation or putting braces around if statements that only execute a single line of code, the code review is not the place to do so. If you think a data structure he used isn't up to the volume of data you'll be running through the system, THAT's something to bring up in the code review.
You can require comments in your code all you want, but I find that you inevitably get something like this: "a++; /* Add 1 to a */" With no indication anywhere of what A is or why you would be incrementing it there. I would propose power stapling the offending programmers in such cases, until they learn not to do that anymore. I would say remedial English classes, but even I am not THAT sadistic.
Peer Review Often (Score:3, Insightful)
Establish regular peer reviews: regular, as in daily; and not just when the library is finished and ready for delivery.
Peer reviews encourage developers to describe what they're doing and why they're doing it (not just conceptually, but at the code level) so deeper awareness of whole systems is fostered.
This can lead to projects with less redundancy, and greater integration. It also helps ensure that code will pass any human driven acceptance tests that the commisioning agent may stipulate.
An additional benefit is that utilisation estimates are improved because as developers get better at describing what they're doing, they become better at describing what they plan/need to do.
The canny manager will schedule the peer-review session 30 mins before lunch, recognizing that it gives developers something to discuss as a group whilst eating.
35 years says a lot... (Score:2, Insightful)
Let programers do what they want. When somone complains that XYZ is hard to read, then it's his job to refactor that code into something that is easy for him to read. Assuming you have the tests you should have written, he'ss have no trouble doing this. If the tests aren't there, then write the tests first so you know if you broke what's already there.
Don't comment your code. Make the code so damn readable that a comment is superfluos.
Above all, don't make rules you can't break on a whim, but do make rules as you find them helpful. Go with what feels right until it stops feeling right and then fix it.
The first person who says something unhelpful as "your code doesn't comform to our company mandated brace alignment standard" gets fired, but only after he's shown what a modern IDE looks like and how well it autoformats the code to any brace standard he cares to think of.
Re:Comments (Score:3, Insightful)
I would say a good comment (that is, a comment that I would find useful) for that piece of code would tell you why the statement was important, what is it going to accomplish, and if needed why was it writen the way it was. For your code my questions when reading it would be "why 456?" and "what is going to happen in the following block(s) of code?".
Re:Comments (Score:5, Insightful)
Re:Comments (Score:5, Insightful)
Comments should concentrate on "why" not on "what." A machine can figure out "what," so a programmer should be able to do that too (eventually). No machine has a clue as to "why" though.
Any time I'm reading through my code and I can't remember why I did something, it's a red flag - that needs a comment. If the code doesn't look like it's needed, but it really is, you need to put in a comment explaining why it's there.
"What" comments should be reserved for the top of a function or largish body of code.
Re:code complete has some good things to say (Score:3, Insightful)
5 is not that required since most modern version control tools are able to run scripts on your data before/after the commits.
In that case, the indentation cleaning, compile test and full unit-testing of the modified application could be done automagically at commit, with commit refused if code doesn't seamlessly compile or if any unit test fails (any code change would also, naturally, require the concurrent commit of the modified unit tests for the code).
Re:Looking for magic? (Score:2, Insightful)
Worry about what not to do, too (Score:5, Insightful)
The moral of the story?
A. You are not the font of wisdom. If very lucky, you are the point of the pen. Rule carefully.
B. Don't make standards based on what you learned in school. Base them on what you learned in real life.
C. If an Old Fart tells you that one of your edicts is stupid, don't assume that they're resistant to change just for the sake of being crotchety. Maybe they learned something useful over all those years and all those lines of code.
Re:What a question! (Score:3, Insightful)
You work for me, you do it my way. If you think your way is better, present it to me and tell me why. "Cause it's the way I do it " doesn't count.
I'll train you, I'l give you time to set up your editor so it automates whatever you need automating. I'll mentor you, have other developers mentor you. But there is a line where I expect the developer to be up to speed.
Re:Comments (Score:5, Insightful)
Write clean code that can be easily understood by reading it. That is, good variable and function names, try not to make any absurdly complicated statements, and have your comments explain the logic of the operations. As for style, try to stick with the style that the original author started with. And finally, all people who use Hungarian notation are locked in the basement and given menial tasks until they repent their sinful ways.
I hope this helps.
Standards (Score:3, Insightful)
I think the most important policy is to slap the guy that says, "I like tabs more than spaces" or "I don't like the way you indent" or "I hate the way you put spaces around ('s".
Honestly? These people have too much free time. People use a variety of conventions and I've seen pretty much all of them. As a senior developer, I just take everyone's idiosyncracies in stride, even when they name variables retarded things like: n, vt, pkq, and rsptln.
If I can deduce what they are doing easily, it is no problem. If I cannot, I make them explain it. If they are not around anymore, problem solved. I rewrite or have their stuff rewritten in a good way, since the stuff was 99% likely to be utter crap anyway, and move on without a moments hesitation.
I've worked on a lot of large codebases and I've never encountered this idea of, OMG this code is so archaic that I cannot possibly decipher this person's intent--and believe me, I've worked on some crazy ancient crap. My obligatory developer arrogrance leads me to state that people that cannot figure out code because of coding conventions are weak developers. Anyone that has slogged through the convoluted "efficiency" of Knuth or the a,b,c,i,j,k madness of Wirth can figure shit out.
So anyway, if you have the authority and your people are actually willing to go along with a standard without a huge hullabaloo, then just pick any standard (you'll get way more mileage from just sticking to a consistent convention no matter what it is). If people are going to make a big deal of it and it is difficult to enforce, just deal with it individually and tell people to write sane things. Their coworkers will provide quite good feedback if they are producing shit, and that's where you really need to step into your lead role and work out a resolution.
One of your best tools for a standard is to create automation to enforce it. Get yourself some prettyprint scripts that you have run on all source that is checked in--in fact, get your developers the same tool so they can run it on what they check out to print it the way they like it. (Of course, you only want to check the source in with the standard pretty printing or diffs become atrocious, but that's technical stuff for a different discussion.)
Bottom line is that whatever you can automate in the way of conventions is a win because then it's completely automatic, difficult to bicker about (two coworkers can't very well bicker at each other when it's the prettyprinter's fault, so they can only come to you and you have authority to resolve the issue right quick, whereas they could just engage each other in an endlessly unproductive slugfest if they are coding by the convention of their opinion), and if people want a change it goes through you and you have a strong argument for--"if it isn't broke, don't fix it".
Kind of a ramble, but after many years this is my take on standards. Use a convention if it is convenient. If not, play it a bit more loose, but be firm on snuffing out those annoying neverending debate situations.
That said, one factor that is relevant is the type of work you are doing. I'm assuming from what you said that you have some flexibility to structure as you like. If for instance you were subject to government or other agency auditing (my current company is), then the loose method is not going to fly, but on the other hand, you would probably already know what conventions you needed becaus
Geek minds (Score:5, Insightful)
Someone commented that the difference between Microsoft and Google is that Microsoft programmers are holding concepts the size of "If...Then...Else" and Google programmers are holding concepts the size of Bayesian filtering; thus, Google's Geeks are better at making big, coherent plans without getting lost in the details. It's not 100% true across the board, but it's an insight.
As a Project Manager, then, your job is to:
1. Allow your Geeks to transfer the concepts from the screen/page/whiteboard into their heads; and
2. Allow your Geeks to hold those ideas easily once they've got them.
Step 1 is a bandwidth issue: make the "inputs" more efficient by, for example, giving all of them dual-head monitors and high speed printers, so they can get lots of code into a usable format for reading (some of us prefer printouts; others just need vi/Emacs and a flicker-free monitor). Step 2 is a quality issue: Geeks who have to hide in headphones or run away to the park to read because of ringing phones and nagging managers are NOT going to be able to do their job.
And with any data pipe, throughput is more a function of time rather than pressure. So your dream of getting your programmers up to speed in minimum time really is -- pardon the pun -- a pipe dream. They won't be any use to you if they don't have the time to learn the systems they're working on.
Re:Comments (Score:3, Insightful)
I looked at that if statement and wanted to know why 486? Why does it execute that block if x is 486? That is what the comment should do.
That said I really need to comment my own code better than I do
I recommend the Mercury project model (Score:3, Insightful)
compiler for a declarative programming language
comprising some half a million lines of code. The
project has been running for over ten years with
multiple developers working at any given time, some
of which are in different locations.
Key aspects of the development model are:
(1) Use a good source code control system (we use cvs,
but are considering svn).
(2) Add at least one test case for every piece of
functionality you add to the system and for every bug
that is discovered during use.
(3) Use a robust, automated build-and-test system.
(4) All code changes should (a) compile, (b) not break
any test cases, and (c) -this is vital- pass peer
review on a mailing list.
(5) All code should be adequately documented. Every
change should be accompanied by a log message explaining
the rationale for the change and what the changes were
and a unified source code diff.
(6) Have a common coding standard for things like
naming, layout, commenting, and preferred idioms.
Shoot any coders that use more than 79 columns in
their code.
Avoid complexity and cleverness unless it is absolutely
warranted.
(7) Code should check all error conditions. Exceptions
are rarely a good error reporting mechanism.
(8) Have nightly builds and test runs.
(9) Your watchwords should be discipline, cleanliness,
simplicity.
-- Ralph
Fundamental coding truths (Score:5, Insightful)
I recently put together a list of Fundamental Coding Truths after musing about this topic and why it was so hard to plan software development:
1. Software is not at its core a collection of a few clever algorithms.
Rather, it is primarily (in the ways that matter) a huge collection of arbitrary
choices and random implementation details.
The algorithms that consititute the mathematical/logical basis of a piece of software
are an important, but very small (eg: 1%) and relatively very simple part
of the overall code.
2. Code complexity is pretty much exclusively determined by the (combinatorial)
number of interactions between pieces. Each interaction requires at least one decision
and usually many more.
3. Because of #1 and #2, deep, intimate familiarity with the code (this vast
collection of implementation details) is only ever fully knowable to the original
author(s) who made these uncountably many, mostly arbitrary decisions.
(Familiarity by secondary authors/maintainers comes primarily from
re-writting sections of code.)
4. Because of #3, programmers are not interchangeable. The efficiency with
which a person can navigate the code, implement or even imagine changes
is almost entirely determined by how familiar they are with these many, many small
details. The ratio of efficiencies between a primary author and another
equally talented coder is very large (eg: 100). Because of this, the original
authors of a section of code are usually the only ones who are ever able to efficiently
modify or restructure it. This becomes rapidly more true as the the size and
complexity of the code increases.
5. Because of the complexity of code (the number of interactions and interdependencies),
debugging and maintenance constitutes the vast majority (eg: 99.9%) of the work
required by a piece of software over its life.
6. Because of the complexity of code (number of interactions between components), it is
very hard, if not impossible, to predict with any accuracy what will be involved in implementing
a given change. Even for original authors, unintented side effects are almost inevitable, and
the primary determinant of the length and difficulty of a task lies in finding and rectifying
unintented consequences or unforseen interactions. Because of this, the uncertainty in the time
it will take to execute a change is very large.
(eg: 10x range in 95% confidence limit of time estimate, say 1 day-2weeks).
7. Because of the complexity of code, bugs are an inevitable byproduct of writing code. It is hard
to predict how long it will take to find and repair bugs as that depends on how many side effects are
involved, which is not known until the repair is done and "fully tested". The only way to avoid bugs
completely is to not write code. There are things that can minimize bugs or speed up finding/fixing
them, but they will always exist.
Re:Comments (Score:5, Insightful)
If you write the code first, then annotate, you fall into two traps: "What the heck was that variable for?" forgetfulness, and "It works so stop messing with it" laziness.
Coding Style (Score:2, Insightful)
I love good variable names and statements of purpose and all that, but I think pure conformity is counter productive. Whatever guidelines you put in place, if you allow for some differintiation between authors it will help with the debugging later.
Standards are irrelevant (Score:3, Insightful)
And you know what? None of us have any trouble at all reading or maintaining each other's code.
Why? Because we're good programmers; because we _care_ about what we are doing, we take a long-term approach, and management judges us by our long-term track record and doesn't look over our shoulders micromanaging how many spaces we indent.
And we all write LOTS of comments, but we comment the things that need to be commented, not just pro-forma and CYA stuff.
You want documentation, not coding standards. (Score:3, Insightful)
Even how you name your variables vs. functions vs. methods vs. objects has very little to do with being able to jump into a project, so long as people are consistent. What's more important, is to maintain good documentation, so that someone has some clue what the relevent files are, and what the overall logic was in how the program / general modules / etc are laid out.
No one is going to be able to jump in and start modifying code on a moment's notice. On a large project, spread across multiple developers, it might take a week or more for someone to have a grasp of what needs to be done, why it's being done the way it is, and what the implications are to change things to the way that they think is better. (I consider unit tests to be a form of documentation -- given a specific input, I expect the given result)
And let's not forget the whole mythical man month -- tossing in another developer at the wrong time may screw up the existing developers if they get pestered by the newbie. That's why I try to keep documentation explaining what the purpose of the project is, known outstanding issues, how the program is laid out, all of those sorts of things that a new developer would need, should I get reassigned, fired, given extra help, or just give up and decide to quit.
A ticket tracking system, and some centralized documentation repository (might be a wiki for multi-person projects) can really help you get a handle on these sorts of things.
If you want actual programming tips
Re:Comments (Score:5, Insightful)
Write clean code that can be easily understood by reading it. That is, good variable and function names, try not to make any absurdly complicated statements, and have your comments explain the logic of the operations. As for style, try to stick with the style that the original author started with. And finally, all people who use Hungarian notation are locked in the basement and given menial tasks until they repent their sinful ways
Well that's a good start, with good intentions, but you need to have a standard definition of what constitutes good function names and good variable names. If you have 5 different programmers on a project, you'll have 5 different opinions on what good names are.
Make sure your coding standards are DOCUMENTED.
If it's a java project, the best source would be Sun's java coding standards. A very useful tool for this is Checkstyle. [sourceforge.net] You can decide which rules to enforce (some of the ones enabled by default are more annoying than anything) but if you take the time to get your code to where Checkstyle likes it, you'd be amazed how easy it is for humans to read.
As for my department, we use CVS for version control.
Every time code is checked into CVS, it is formatted by Jalopy. So, it'll look nice and neat the next time it's checked out.
Also, we have a script that does nightly builds, and then emails the result to everybody on the team. So if you checked in something that breaks the build, everybody knows about it the following morning.
We have a regular release schedule. All work is done on the main CVS branch, but when it's time for a code freeze, the new version is branched off and tagged in CVS. During QA testing, bugs are fixed in the branch and the mainline. New features are only added to the mainline.
When we are ready to deploy, we tag the release in CVS. The deployment script checks the tag out of CVS, builds it, and packages everything up into the relevant
This is all a very strict process, but things rarely fall through the cracks this way. If you don't have any processes in place now, it's best to implement them a step at a time. Get everybody used to working with CVS or some other version control, get them used to the notion of tagging and branching, and make sure there's actually a document detailing whatever processes you have.
And lastly, have code reviews every week or two. Review a different person's code each time and make sure everybody on the team is allowed to have input. If you're not at the coding stage yet, have design reviews.
Re:Comments lie (Score:3, Insightful)
Comments lie. Code never lies.
You don't have to come up with anything... (Score:2, Insightful)
I achieved a similar thing in my company by setting up a wiki (I started with Twiki and then we changed to Confluence) with a basic skeleton that I wanted have fleshed out. I even got our developers to define the skeleton, they all knew what we needed, code guidelines, review methods, development procedures etc. Now all I have to do is spread the word about the existence of the wiki and watch it emerge!
Re:Comments (Score:3, Insightful)
When I see code like this, I have turned to my current boss/client and said "You didn't plan this thing very well at all did you?" on many occasions. That question always gets a look of guilt quicker than two teens with no clothes on when her dad walks in. When you explain how you noticed so quickly, you can see the look of "How did I get here? Do I know what I'm doing?" wash over their face a few times over as they think of everything else they are in charge of in the same light... and wonder if their mistakes are always that obvious to others. I remember one PHB wo implemented a "Code Review" the very next day. Fun! Sad, sadistic, pitiful fun - but still fun sometimes.
I wish I had mod points for you Webmoth. You hit the nail on the head dead square. Even countersunk it a little.
Re:Comments (Score:4, Insightful)
Also, have a simple set of automated test scripts and require that every change must build and pass all of the scripts before being checked in. Also have a more in-depth set of test scripts that are run on a regular basis, and make sure that failures are fixed. Finally, make sure that you have a test org in charge of maintaining the scripts and adding new ones, so that your code doesn't become 'immune' to your tests.
Re:Comments (Score:4, Insightful)
Re:My boss doesn't care (Score:2, Insightful)
Don't arbitrarily set up standards. Ask people what problems they have. Tell people what problems you're facing (e.g., you need to be able to move people more easily between projects). Then ask the developers who don't have those problems what they do. Feel free to toss in your own suggestions, too. But let them talk first. And let the developers decide how to do the work as long as they address your needs.
Remember that you're not working in some Taylorist 1930s factory where you have to specify every motion. Creative work, which is what your developers are doing, is utterly different than factory work. (See the book Artful Making [google.com] for more info on that.) Treat them like professionals and they'll act like professionals.
Re:Comments (Score:3, Insightful)
You're right - how could it be possible not to know what that code is doing? (The rule is, the only magic numbers allowed are -1, 0, and 1. 456 is right out.)
But then again, don't worry, everything should be clear [thedailywtf.com], right? :)
Re:Comments (Score:3, Insightful)
Re:Comments (Score:4, Insightful)
Re:Magic Numbers (Score:2, Insightful)
Re:Evolutionary Prototyping (Score:2, Insightful)
The flip side of this is that after showing marketing a semi-functional prototype that is pretty close to what they are looking for, there is often a tendency to assume that the project is near the code-complete phase and that a majority of the resources can be reallocated elsewhere. Just leave a couple of developers on the project to polish up the code and the installation program
Because of this, I usually like to leave an obvious (from the UI perspective) piece of functionality missing from the functional prototypes. This makes it clear to the management and marketing types that there is more work to be done. They don't really care that the prototype is non-scalable and has the web server making direct database calls, whereas the real implementation would need the web server going through middle-tier business components, data access layers, etc.
What we do (Score:2, Insightful)
The most important thing is AUTOMATE everything that you can.
We run a cycle where we do an automated checkout every 15 minutes. This is compiled and the checks below are done on all packages that have been updated or which raised errors the last time. Every three hours we do a zero base checkout and run tests across everything including running all unit tests. We also then do a complete construction of installers etc. for the products we ship and run tests on that (rather than in the developer environment). We also checkout across multiple platforms and run the unit tests on these (this is a bit more irregular). The results are collected on a company internal website and errors cause a real-life set of traffic lights to turn red (everyone can see them).
The things we automate include:
There is more to testing than this but this certainly deals with the low level coding stuff well.
partially agree (Score:3, Insightful)
Re:Question about Hungarian Notation (Score:5, Insightful)
// the old c style
if(cur == last) rec->tag = name;
// camel case
if(currentKey == lastEntry) Record->keyTag = userName;
// hungarian
if(iCurrentKey == iLastEntry) prRecord->m_pszKeyTag = pszUserName;
Now imagine discussing them with your coworker. Imagine thinking in your head "What should I do if prRecord->m_pszKeyTag is NULL?" Humans are good at symbolic manipulation. Giving something a name makes it easier to deal with. Giving something a label that cannot be easily manipulated in language (spoken or in your head) severely hampers the ability to think it through.
The argument for Hungarian is usually "but it lets you know what the variables are". This is the maintainance programmer argument. This argument rarely makes sense in reality, unless some very bad programming is involved. First of all, if you do not understand the current code you are about to modify, you should *not* be modifying it. If your maintainance programmer is just going to have a look at two lines of code, add a third in the middle, and hope for the best then you are truly fucked. He has obviously not understood the code enough to know what the consequences of the modification will be. The reality is, if your current logic unit is such a monstrosity that looking up the types of your variables is a burden, and your variable names are so poor that it is insufficient to infer at least a basic understanding of what is going on without having to resort to prepending types, you should probably step away from the keyboard, turn off your computer, and tell your boss that you had an epiphany and will be pursuing a career in French fry development.
Re:Comments (Score:5, Insightful)
People forget that code itself is a language. And usually a much more clear and logical one than English. Requirements docs are for explaining complex business processes and code itself explains most of what is going on. That is not to say that comments are not important, but when they exist I want them to be there for a reason. Anyone reading your code is assumed to be conversive, if not fluent in the code language, so comments should explain things such as:
Comments that merely "translate" basic code language into english are at the very least useless and often harmful: they bloat the filesize, obfuscate executable lines (I have deleted blocks of apparent comments only to find that unit tests are subsequently failing - the reason? - a single line of executable was buried between 2 dozen lines of commented out code), increase the burden on the maintainer and/or reader who must sort out the important details from the quotes laid down by Capt. Obvious.
Some of my rules (Score:3, Insightful)
1) Thou shalt NOT make the user re-enter data
2) Waste not clicks for they are precious
3) Thou shall not design a screen that hath no purpose
4) Move not your bits about the screen like a drunken stripper
5) Gulp not your data but merely sip... as it makes reguritation less lumpy
6) That which the user doeth the most, shall not be obscurred by that which he doeth least
7) Dress not your screens with vain and lustful colors that are without purpose
8) The user is the one true god and thou shall hold no gods before the user
9) The user is a friggin idiot
10) An image that measures 16 pixels across and 16 pixels along it's length is rarely worth one word
G
I keep my own log book for programming (Score:2, Insightful)
One, when I start plunking away at the keyboard, most of my ideas have been muddled through and I'm not wasting time fumbling through books and websites to find answers. I can also note what ideas did and did not work. Also, since I am typically juggling mutliple projects, it helps me keep track of what I've done and what I have to do.
Second, I've learned to keep it for review. Basically, I learned at my last job that documentation can save your butt, especially when working with nurse manager who still can't find her archives folder in Outlook or trying to explain how archaic software works to management when nobody has even looked at the source code in 7 years. Its a picture into my brain and its a log of where things have progressed for a give project.
Third, my notebook has served me are my only way to figure out what the heck I'm working on. Essentially, I've always been given a massive system to rework/hack/redesign that nobody else bothered to figure out. My notebook is my only guide to solving problems, since its my only reliable reference.
Fourth, a journal can double as a weekly to do list. Alot of times, I have so much crap going on running my system that I forget what the hell I was working on. So, I often write down 10 projects or assignments I need to do within two weeks and cross them off as I go along.
And finally, it keeps me from having to write the same things twice. Often, I can use code snippets, data structures and old work flow schemas in other projects. that's really helpful when you're up until 12-1 in the morning hammer away at some God awful perl script and you need to get everything finished by the weekend.
** PACS and RIS stand for Picture ArChiving System and Radiological Information System, respectively. They are two ancillary systems that hospitals now use to save X-ray, CT, MRI and other images of the body.Re:Comments (Score:3, Insightful)
The general theory of coding practices: Don't be a moron.
Re:Comments (Score:3, Insightful)
Referencing the documents that the PHB/customer helped write also makes your comments easier for them to understand. Not to mention something the PHB/customer is actually happy to look at (gasp!). It usually makes for better and more consistant documentation - especially if you add in minor "this is for that" line comments where needed.
When it comes down to it, it's actually a lazier way to go in some respects even. It's been a huge time saver and a check against feature creep for me in many cases. Try it and you may never go back.
Re:Comments lie (Score:3, Insightful)
Comments can lie, and code never lies about what it does, but code doesn't tell you anything at all about what the author intended it to do. The comments are more likely to give you a hint, and at the very least if the comments and the code agree, you can probably be sure it's right. When the comments and the code disagree then you know that at least one of them is wrong.
Use automatic code formatters (Score:2, Insightful)
And Jalopy for Java.
Formatters are available for most languages.
Decide on what all of the options are for each formatter and make
a script available that runs the formatter with the appropriate options.
Require that automated formatters be run before code is checked in.
It is easier to read consistant formatting than your favorite formatting.
Re:Comments (Score:2, Insightful)
And I would consider attempting to get in the habit of putting the number / constant first. If you accidently drop an = from ==, it will be a compiler error. The other way around can be maddening to hunt down and correct... although a good IDE will at least give you a warning.
EX:
#define UPPER_BOUND 456
if(x == UPPER_BOUND) do_something_useful();
if(x = UPPER_BOUND) assign_upper_bound_to_x(); and_always_evaluate_to_true();
if(UPPER_BOUND = x) compiler_error();
Re:Comments (Score:3, Insightful)
{
}
this is bad code and no amount of commenting is going to fix it. It begs 2 questions; What is x and why 465? I would recode it as something like this that makes the purpose clear enough that no comments are needed:
const int screenWidth = 456;
if(xCoordinate == screenWidth)
{
}
this way I type more code but less comments.
Re:Comments (Score:2, Insightful)
In addition to everything others have mentioned, for web development you need a good deployment system to compliment subversion or CVS or whatever you use for version control. As far as planning goes, always start with the data model, that is my best advise. Come up with the most versatile data model you can, try to plan for everything, don't just add columns to your existing tables as you go along (or try not to at least). Using a program like inkscape, omnigraffle, or visio can be handy for this, although it takes a bit of practice to come up with useful diagrams.
Usually the data model is the easiest part of the application to convey visually and will lead to the quickest understanding by newcomers. It's usually the first thing I start with when I'm familiarizing myself with something new, whether or not there is good documentation, I'll look in the database first.
As much a social/managerial issue as a tech one (Score:3, Insightful)
The first step is to assess the current situation - what coding practices are currently in use? What do the developers want? Can you roughly group the existing codebase into various standards, plus a pile of incoherent crap? Is it worth while rewriting the crap portion to the new standards?
Second, decide what level of standardization you want to achieve. The more detailed your standards, the more difficult and risky. You will probably make some wrong decisions, and they will irritate developers now or in the future. However, if all your developers code in the same language, and several of you are experts, you may be able to write detailed standards and get it right.
Third, identify relevant references. If you're working with Perl, Damian Conway's Perl Best Practices is a good choice. In C++, Meyers' Effective C++ series is good.
In general, micro-standards will not be successful. Instead of trying to make everyone use the same indentation or something, you'll get the most bang for the buck by focusing on high level issues. For example:
Good luck.
Code cleanly and remove comment (Score:5, Insightful)
messages_processed++;
This actually makes sense without the comment.
Re:Comments (Score:2, Insightful)
Re:Comments lie (Score:3, Insightful)
I once came across a ~1400 line function of complex maths transformations with one comment
i++ /* increment i */
What's i? and more importantly why increment it?
Re:Comments (Score:4, Insightful)
The beauty of slashdot :) (Score:3, Insightful)
- What is a development envorement?
- What is QA?
- How can I test code before putting it on production?
- How can I plan for and track team progress in development?
- What kind of documentation will I need?
- What is a process?
- How do you declare/manage process?
- Who is responsible for builds, who writes specs?
- Do we have separate QA team?
- Is there any testcases?
(silly, I know, but shows the scope of his position a bit)
YET we have 300 comments + discussion of using or not using hungarian notation in naming variables.
Perrfect!
Re:Code cleanly and remove comment (Score:4, Insightful)
Re:Comments lie (Score:2, Insightful)
index = 0;
if (string == null)
return error;
index = getNextIndex();
Comments should be reserved for describing functions and non-intuitive variables or code blocks.
I find that having naming conventions for variables, classes and functions is very important. Using proper names makes reading the code so much easier and eliminates the need for useless comments like the ones above.
I remember back in my first or second programming course they said, "you should be able to remove the code, read the comments and fully understand what the code is doing". I never agreed with this statement.
Re:Joel on Software (Score:1, Insightful)
Re:Comments (Score:2, Insightful)
>this will cause a compile-time error if you accidentally type
>const int SCREEN_WIDTH = 456;
>if (SCREEN_WIDTH = xCoordinate) {
It depends on the language. Any language that has a boolean type is going to give a compile time error to xCoordinate = SCREEN_WIDTH. The only time it will not is if you write if (something = true). But then again that comes down to bad code.
Re:Joel on Software (Score:2, Insightful)
That is because Joel has fallen into the legacy vs new trap.
Legacy code is difficult to maintain and only your best and most experienced programmers can work on it without either braking it, making it worse, or doing it very very slow. In comparison, writing new code _seems_ relativily easy (can you hear the alarm bells?).
So if you have to put your best programmers on the legacy code, everyone else gets to write the new code
There is no easy answer, pair programming helps, but requires more staff. Not many managers understand the "pay a bit more now, collect the big reward later" way this works. Good experienced programmers are expensive, young inexperienced progammers are cheap if you only consider how much you pay them (and not how much you have to pay to sort out the mess later using your expensive experienced programmers).
It works for me - I make a living out of fixing bad legacy code. I don't get to work on the sexy new projects, the youngsters do, creating my future employment needs... and so the cycle continues...
Re:Comments (Score:3, Insightful)
In addition... (Score:5, Insightful)
More importantly: Don't be too clever.
It's when people try to get clever in their coding that it gets hard to read. And, quite frankly, that's the code that generally breaks most easily.
Re:Comments lie (Score:2, Insightful)
Re:Comments (Score:3, Insightful)
You should still know (Score:3, Insightful)
I hate Hungarian because you know the type from the context anyway. You don't do addition on a list. You don't do foo[bar] on a real.
A variable should encode everything you need. A variable strSql isn't as useful as selectFoo which tells you what you are doing with the variable. The the variable contains sql is obvious from the context where you care about the contents, and you tells you what it is for where you don't care about the exact contents.
Code Review is Good (Score:2, Insightful)
Have an opinion on all the above but some of your best coders might disagree. And might not agree with each other.
Code reviews for bugs, design, format, readability et cetera are a good way to improve code quality and application quality. Code reviews are very difficult to perform and very difficult to manage.
The idea of code reviews is so old that the older recommendations say you should review before your first compile! Find a newer guideline. The most important guidelines are about the emotions involved in code review. People can get very accusatory and very defensive.
One way of doing reviews is pair programming.
You will find as you go along that many managers and customers simply do not want higher quality if it delays first release. Chew on that.
Think in advance what you will do if you find you have a good coder that nevertheless produces code that is too hard for others to understand. Rather than canning somebody, perhaps you can help the coder to express him or herself more clearly, and help teach the other one to read code more effectively.
Code reading is a specific skill and may be a specific natural talent. That is, different from the skill and the natural talent of code writing.
Code reviewers, testers, managers, and others often have a legitimate need to add comments and/or links to production code ("bug #1234 crashed here", and "I don't understand this", and "90% of the cpu is used here"). It would be good if there were a version-control and text-editing system that allowed non-coders to add "yellow sticky notes" to code -- without breaking the build!
Re:You should still know (Score:3, Insightful)
Sadly strSql isn't a made up example - I was looking at code that used it while I wrote that reply.
qryLogin, is useful because it tells me what is going on (even more than the replacements I came up with). If the prefixes have meaning I do not objects. The datatype however is rarely meaningful.
Where you use data type prefixes is with a variable like userID. Is it an int or a string?
You do not care what type userID is! Does it make sense to do userID + 1? No, so even if it is an int you don't treat it like an int - it is a userID. If userID was a string, likewise you do not do string manipulation on it, so it doesn't matter that from context you are unsure what it is (though I would object that it should be userName).
Re:Question about Hungarian Notation (Score:1, Insightful)
Re:Question about Hungarian Notation (Score:2, Insightful)
"What should I do if open paren capital R ecord dash greater than capital K ey capital T ag equals equals null close paren?"
If we used Hungarian and I were to ask the question of a coworker, I would of course leave off all the crap (unless it were relevant). Humans are good at that and Hungarian notation makes it pretty easy to spot the "real" name (just skip everything until you get to the first capitalized letter).
You may have a point if you are instructing a coworker in what to type into his editor, but if that's the case you probably have bigger problems with your development team.