What Workplace Coding Practices Do You Use?
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?"
Tell them to use comments in code, and be sure that they make them good comments.
I don't preview or spellcheck.
Has several excellent articles on the subject This is about as good of a starting place as any.
SJW: a person who perceives an injustice, and while correcting it, commits a greater injustice.
If you really are starting from ground zero, I'd suggest setting up a repository such as SVN as a good first step. Couple this with a good template to set up standard locations for documentation directories alongside the code trunk and branches (and any other resources your projects requires (images, sound other media). Make sure everyone uses the repo - even if you have to spend a day leading people through it - you'll save time later. This also ensures your projects are backed up (so long as everyone checks in at the end of the day at least), and screwups - such as deleting the wrong directories and forgetting about it for weeks can be reversed.
Obviously there are other issues such as naming conventions, useful comments etc, which are often neglected in small projects, but become more important as more people work together without wars breaking out!
Find out your teams individual strengths and preferences - there's no point trying to hammer everyone into the same mould - some people will naturally gravitate toward, and excel at certain tasks. It's important for efficiency and general happiness that this is taken into account when allocating resources to a project.
Code, Hardware, stuff like that.
If you haven't been doing these things, pick up "Pragmatic Project Automation". It may not specifically address coding standards, but it definately will help you get some standards around processes.
In my job as a web developer in a healthcare system, I'm all about evolutionary prototyping and other interative methods. There's a handful of big projects where we take a more traditional waterfall approach, but even then it's highly modified.
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.
I like to think of it as "don't ask, don't tell" :D
got sig?
For every conditional, you chug a beer.
For every loop, you chug a beer.
And, of course, for every save, you do a shot of tequila.
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.
At every inspection; and of course example code for everyone to mimic the coding style.
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!
In the future, I would want to not be isolated from my friends in the Space Station.
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.
Drunken Style®.
This doesn't directly answer the question, but a nice big break in the middle of the day helps me get myself on track easily. After a few hours of coding, I may start to slow down. If I just take an hour (eat lunch, walk around a little), my brain clears, and I come back fully productive. My work place allows this, and I'm not sure how many others do.
Help Fight SPAM today!
Every place I've ever worked has had coding standards, and at none of them were they ever followed. There was never any difficulty telling who wrote what by how they styled their code. Efforts to enforce coding styles by management never succeeded.
The importance of a single language standard can't be overstated. Ever since my company switched to LOGO I can understand my co-workers' code at a glance.
Must be a simple project if you can switch projects and figure things out in a couple of hours. Lucky if it isn't a couple of days.
Outsource them all.
Assuming you have in house developers, rather than outsourcing everything, You should let your staff (or a committee of them) set the priorities for the development of standards, what standards to use, and review the stndards regularly (annually or so).
They know how they want to work, and also know what bugs them most, so they should set the standards and priorities (with you to guide them).
implementing standards is the easy part...having people follow them is the hard part hopefully you don't work with a bunch of close-minded morons...if you do its gonna be hard to have everyone follow them...if people see and buy into the value that standards offer... it will be a hell of a lot easier.
Get Out Of My Office And Let Me Work In Peace
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).
You can never go home again... but I guess you can shop there.
If you dont allow people to code the way they naturally can, don't expect any amazing code or new ideas. Their code may also have bugs. Don't buy all the standardizaion hype.
..u shouldnt be hiring 'em if you arent going to be trusting 'em.
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
At our workplace, we have very few (if any) standard practices.
1) We don't all develop in the same place (some use their HD, and some use a shared drive, some develop over FTP).
2) We don't use the same editors (Textpad, UltraEdit, Homesite, etc).
3) We don't use the same tab settings (Some use tabs, others use spaces).
4) We don't use the same methodologies (Using PHP as an example: Some prefer $_GET while others prefer to enable globals).
Part of the problem is because we came from different backgrounds (Some delhi people, some PHP, some home-taught, etc), but the biggest reason is that we usually don't work on each others code. A couple years ago, we decided as a department to start using some specific coding standards. These didn't last very long, because the company culture has always been one of one-on-one projects, and team-based development simply does not happen.
If you want to implement coding standards in a place where there have been none before, be prepared for blowback from the "grunts". They have been doing it their way, and they are used to it. They probably don't see any reason to change.
The only way for this to be successful is if you either have the power to enforce, or if you can have them catch the vision. At our place of work, I was the only one with a vision.
Good luck to you!
Online Starcraft RPG? At
Dietary fiber is like asynchronous IO-- Non-blocking!
First language try to choose languages that work well on multiple platforms with at most a recompile. Languages like PHP, Python, Ruby, are Good. If you have to use .NET try to make your programs compatible with Mono. Even if you are using a Windows network and don't plan to switch anytime soon working with platform independent language give you the ability to better negotiate with MS for licensing price because your 3rd party apps will cheaply move over to the new platform. Also programs designed to be platform independent tend to migrate a lot easier to new versions of the OS. Avoid using and single platform library or other 3rd partly libraries unless you really need them. If they stop development you could be stuck.
Second have a Good Data Warehouse try to use Rational Database servers that support Stored Procedures and Triggers, which is dependable. MySQL 5, PostGreSQL, MSSQL, Oracle are all good choices. I would put money to give all the DataBase Servers some good specs and conversly I would put all the data manipulation into Stored Procedures and Stored Functions. Also when creating them give them a prefix to show that they are your companies specialized functions and not built in the Database Server. The Database should give you the data they way that is most convenient for you to use. The reasoning for this is that it normally reduce network traffic to the SQL Server, and allow porting applications to different languages and platforms easier because the data format part is still complete.
Third use have all your apps on your intranet be web based. first it eases deployment and also allows desktops to be upgraded without killing the app every security patch.
So if you make a all your Apps Web Based with the bulk of the calculations on the Database server and having the Web Language handle the User Interface, and depending on you size of you apps a 3 or 4th tear with custom libraries for standardized uses of Interface and data a.
If something is so important that you feel the need to post it on the internet... It probably isn't that important.
Well of course commenting, good function/variable names are essential, but also i find that it helps alot to keep the way you indent the same. For example before I learned python i used C++ and since indentation was not necessary mine was horrible. Then after learning python I came back to some code that I had made before in C++, and since in python you need to have proper indentation I found it very hard to find my way around the code. I had to go through the whole thing and change the indentation before I could figure out what the code was doing.
Visit Tevlog
I work for one of Activision's subsidiaries and this is what we use:
int* gpiGlobalInt;
int FunClass::GetSize(int _iArg1, bool _bArg2)
{
bool bBool;
float* pfFloat;
static int siStaticInt;
for(;;)
{
}
}
Seems to work out well enough.
They do have expensive fancy pieces of paper prooving they can memorize things only.
Besides, cleaning up from their constant bumbling affords me the ability to ignore coding practices. There are bigger piles of shit to clean up!
I'm all self-taught, so I have my own style which others tell me is impossible to make heads or tails of. The standard is: the boss promises stuff to our clients, and I have to whip it out [snicker] as fast as possible. Doesn't leave much time to make easy on those who would come after me. I jokingly call the mess of code I have to make JOB SECURITY.
"You know you're narcissistic when you quote yourself in your sigs." -- PRoPAiN!
As simple as that he he he he he :)
Arash Partow's Philosophy: Be a person who knows what they don't know, and not a person who doesn't know.
GetOuttaMySpace - The Anti-Social Network
From my experience managing many multi-million line code projects for many years, its the tools (source control, bug system, langauges) and a standard documentation templates (market requirements doc, product requirements doc and detailed design document, unit test document) that are more important to standardize than coding guidlines. Sure everyone should follow a good variable naming convention (hungarian or equivalent) and heavily comment each function's purpose, but beyond that you can waste a lot of team time on arguing about idententation, and micro-commenting guidelines.
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.
You seem to be asking more about the basics of Project Management than specific tools. For a fair overview of the subject try this in Wikipedia. The grand-daddy of Project Management for software development is SEI-CMM.
The smartest man in the whole, wide world really don't know that much. - Mose Allison
Use top to bottom approach:
e sting/release. Then work your way down putting measurable controls where needed on each step of the process.
First of all, have some formal project management training, at lest to get the basics. With this, you will be able to come up with a simple methodology for project requests/paycback/negotiation/scope/development/t
I have done what you are doing now, and these where the first steps I took when facing a lot of teams with a lot of possibilities on "this is how we run a project" ways to do things.
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.
We use agile programming methods.
on this particular subject. i believe code complete 2 came out "reasonably recently". that said, were this my task, i'd say the following:
1) document things thoroughly using a tool like doxygen. there is no excuse for interfaces not to be thoroughly documented
2) adopt a standard naming convention. in java, this is easy -- just use the default. in other languages, you'll probably have to make your own up.
3) pick an indentation style. it really doesn't matter which since tools like indent can convert between them almost painlessly. all code that goes into the repository is run through indent to put it into a standard format
4) require that code compile cleanly with no warnings at the most anal retentive compiler settings before it can be checked in unless there are good reasons to ignore the compiler warnings
5) average devs are only able to commit to the "head" fork (or equivalent in your sccs). the code is not committed to the "real" fork until it passes whatever tests you have
6) incorporate tools like valgrind into your testing cycle --- they should come back largely clean. if they don't, things need to be fixed unless there's a really good reason not to.
7) people who check in code which breaks cvs or, upon a code review, are found to not sufficiently adhere to your guidelines owe their dev group donuts.
The pottery barn rule comes to mind: you break it, it is yours. Or at least that's the way it is when I am tweaking the legacy code.
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.
These are pretty obvious, but documentation and planning are something you need to stress.
Documentation is the most important, from business rules and operating procedures (this code gets backed up at this time every night) to the code itself. As a project manager, your job is to build a little box for the developers to work in. You want to make sure that all the important stuff is just a simple list of stuff to follow so they can concentrate on coding. Programmers are generally not good at scheduling or remembering to do mundane daily tasks. Get that stuff straight and you'll solve 50% of your day to day problems.
Planning is important. Make sure that there's a good plan that everyone's following. Plan naming conventions and folder/file systems for your code. Then, everyone knows where to look if they need to find something. Simple organization is important. As far as actual development, you need to have a broad plan for the goal of the project, what general steps need to be taken (initial planning, module coding, testing, beta, release, maintain) and do them in that order. You don't need to get crazy with project planning software either; what you want is results, not to dictate how the results occur.
To that line, this box you're building has to be open enough that your developers aren't too constrained to innovate. This means you have to make it kindof a fun challenge to document the code, plan the project, etc. Don't make it seem like it's some chore to document. Force them to pass their code around for a few weeks to work out the bugs; don't wait until you have to. Or start with some dumb easy project that is a small part of the larger problem, and make everyone do one little piece of the planning, then pass it to the other people.
Anyway, this stuff is pretty obvious management stuff. I can tell you that in my 6+ years of business experience with coding and coders, the most important thing is having naming conventions for your files and folders. It seems obvious but when you get a new developer in, he's not going to understand Module3.CreditWidget.x3.1211.c when it could just say "NumberVerifier.CreditCard.c".
The military logistics people have good ideas for that sort of stuff:
-A data element name consists of a prime word, a class word, and modifiers.
-A prime word is the noun designation given to an entity identified in a data model. For example,
a company may need to maintain information about customers, so an entity "Customer" could exist. The prime word for this entity would be called "Customer." The prime word identifies the object to which the data element refers.
-Prime Word Modifier. Prime word modifiers are adjectives that further refine and categorize the
prime word. They designate the name of a data subentity in the data model and distinguish it from other subentities of the same data entity. They are needed to distinguish that data subcategory from other subcategories of data represented by the data entity. For example, a company may be interested in information about two distinct groups of customers, "Retail Customers" and "Wholesale Customers." The prime word modifiers "Retail" and "Wholesale" are used to distinguish between these two types of customers
- class word is a noun that prescribes a definition for a general category of data. A class
word designates the category of data into which a data element fits. Examples of class words are: "Code," "Name," and "Quantity."
Etc.
Check out Department of Defense Data Element Standardization Procedures
Good luck.
Cool! Amazing Toys.
At my former job we used this mushroom management with great success. While people quit or get laid off we ended up with Lava Flow. And it ended up with my favorite practice called "down by the river eating government cheese".
Have you ever been to a turkish prison?
My thought is that you have just accepted a practically impossible task. If you don't have unwavering support from management, you'll fail. If you can't somehow get people who've been doing their job for 35+ years without standards to WANT to do it WITH standards, you'll fail.
Expect endless argument about what standards there should be and how far they should go. Expect that no one will be satisfied with your testimony about a proposed standard having worked well for you in the past -- everyone else will deny that your "standards" are solutions to the problems of project maintainability. Expect complaints that "we've never had to do this before" even if you know it's a good idea. Finally, expect it will take a LOT longer than you want it to.
If there's one piece of advice I can give you, it is: start with the very basics, work to expand them slowly, and pick your battles carefully.
Good luck, you're going to need it.
Comments:
concise comments.
Clarity:
Use readable and properly discriptive names. Avoid using hard to read code because it makes it faster. Processor are fast,and compilers re pretty damn good. The only exception is code write on top of the machine, But then you should commented well.
Consistency:
Apply the details to all developers. Meaning if you decide to to use 3 spaces for every indentation, be sure all the developers use it. If you use a common IDE, then it should be trivial to make the look consistant.
I'm a big fan of code reviews. It spreads the knowledge around, makes the developer interact, helps ensure consistency, and is a good way to be sure the project is on target. Too many times I've seen wrtitting a tool to help with a project, become the project.
The reason why I becames a fan of code reviews is a long and tedious story...so here goes:
I was leading a team of 4 developers. about 8 weeks before the project was do, I decided to do code reviews. 4 weeks later It was this developers turn. He doesn't show up to work, or the next day, or the next day. I had HR call him, but never got a returned call. At this point I get on his computer and start searching. The only code I found was learning code. Clearly this 'experienced developer' had no experience at all. The team came together and we managed to get his work done, and the project released on time. Saved the bank 100 million dollars. They gave us a football.
I ran into him years later, it seems a dot com where he was the lead developer had gone belly up when they couldn't deliver.
The Kruger Dunning explains most post on
When I started out programming I went to the example programs, and ever since then when I want to learn something new I find example programs. Have your programmers write example programs that demonstrate what they expect their code to do. This can also prove useful for unit testing.
I've hired an infinite number of monkeys, and seated them at an infinite number of PCs running Eclipse (with File->Quit disabled).
I expect them to have finished writing my code for me by Monday.
Yeah, standards are great.....we've got lots of them :-)
-Chris
--an unbreakable toy is useful for breaking other toys--
I'm a huge fan of the Unified Process. Note that UP focuses on the software development process, and not the project management process. Also: Set up a Subversion server, use Trac, and put daily announcements on the start page wiki (or similar). Unit Test your code, and make sure to use Javadoc/Headerdoc.
Well, coding standards can be very complex to very simple not to mention they're language independent. A coding standard for Perl would almost certainly be different to one for C - simple example, Perl doesn't have /* and */ so mentioning them in a Perl coding standard doesn't make a lot of sense.
:)
Here's some advice though:
1. Take a top down approach and a bottom up approach at the same time
- What are your broad goals and what do you want your standards to do?
- What standards already exist in the organisation?
2. Remember, you need to win the hearts and minds of your teams to change
- Sure you can be PHB and say "Thou shalt", but unhappy coders write unhappy code
- Listen to your team and get their feedback
3. Don't make wholesale changes because "you can"
- Otherwise you might end up making things worse
Out of all these three points, if you want to effect change, maintain respect and have coders who you can still herd about, point 2 is probably the most important...in fact, if you have the time and support to do it, getting your programming team to formulate the standards FOR YOU will mean they're more likely to actually follow them because they OWN them
HTH
Test Driven Development. It's the easiest way to end up with good code and tests that support you when you make changes. And, we all know that we will make changes :-)
Contract developers and new programmers joining an organization, especially a small organization, appreciate thorough documentation of processes and modules from an overview down to details on each specific component. Legacy engineers tend to hate documenting so it may require some effort.
OOP helps resolve issues of efficient use of code so that development efforts aren't wasted on modules that may already exist created by previous developers no longer with an organization. A clear naming schema and again, documentation on each class and how it works is very helpful.
Structured programming practices. Documented code. Standards such as variable naming conventions and efforts to maintain code uniformity.
I personally like Version Control with Subversion, we use it in our China office and everything there takes very well to it.
We have learned a lot from our China operation for the organization I am with. They make extensive use of Wiki's too. This lends itself well to the documentation task.
I believe the rest is management style and your corporate culture.
That's what my old boss told us to do.
Also, "If you can't finish it by the deadline, work faster."
fsking brain surgeon.
Karma: It's not just a good idea. It's the law.
- Get a development database, a testing database and production database. Yes, you need all three.
- Write a few docs explaining each system. Make these are detailed as you possibly can. (This will save you weeks in the long term)
- Use software revision control. CVS, VSS, whatever, use one.
- Use a bug tracker. BugZilla, Jira, CityDesk, whatever, use one.
- Use whatever coding standards the language reckons you should. If java, use sun's standards. If microsoft, use their standards.
- Write automated unit tests. I don't care if you're not an agile or XP developer, write unit tests. Check out Junit, or Nunit, or just write your own.
- Setup some code so that you can check out ALL code from the source code repository and compile it by ONE COMMAND. Eg, "make" or "ant" or "maven" or whatever. This will take time but is worth it.
- Have a naming standard for database tables. This will make your life SOOOO much easier.
- Read thedailywtf.com and don't do anything that is posted there.
- Write specs for your new developers. Please write specs for your new developers. Don't just say to them 'fix this up'.
- Make sure code isn't hard-coded to a particular directory. Everyone does this. Fix it. (Might be part of step 7)
- Create your own standard config files.
- Have code reviewed by peers. Don't be a bastard but be nice when picking on people's code.
- As mentioned, comment your code but use the language standard. Java - javadocs, Perl - perldocs, etc. These are cool, but don't get too carried away. Nothing can replace a good spec.
- Ignore what most people say on Slashdot. (Except for me, of course).
That'll keep you busy for a couple of months! Doing thiswill make you well on the way to having a pretty high level of coding quality. Most companies don't do all of them. Good luck.One word.. doxygen. I had been working on a program by myself for a few years and was really the only one who knew the guts of it. We got a new person on it so I could move on to other things, and rather than spending a week or two showing her what she needed to know, I spent a few days adding doxygen comments to the project, and she was able to read the generated documentation for herself and picked it up in no time. It plugs in to Visual Studio very nicely if you use that, and if not, you can easily write a batch file to update your documentation. I just can't say enough good things about this tool. If you can get your developers in the habit of documenting in the doxygen format, your documentation will basically write itself.
Segfault
A few other details that I'd like to add. K&R braces were invented, not by K&R but by the guys who typeset their book. It is a severe roadbump to try and read code where the braces are at the end of an if statement instead of vertically alligned.
Try spinal alignment for variables. Most people align their variables like this:
int something;
void somethingelse;
longobjectname theThirdThing;
Those with more of a clue align them so that you can find the variable name easily in a mess of them:
int something;
void *somethingelse;
longobjectname theThirdThing;
This puts some major space in some cases between names and short type declarations. Try aligning them like this:
The problem with this technique is that, if you ever post your code on Slashdot, you'll have to replace spaces with dots and spend fifteen minutes trying to get it to render correctly because SD doesn't support a simple PRE tag.
Other tidbits that have helped. camelNotation rules. Don't use hungarian notation, it doesn't work in a severely object oriented enviornment. Instead, preceed your variables with a single letter that tells you where it's declared. l for local, m for member (of a class or struct), g for global, that kind of thing. I've seen "my" used for member and "the" used for static very effectively, also, but stick to one.
Most of all, good luck. Remember that a lot of people's beliefs in this matter have no foundation except for what they've been doing for years. I have faith in my standards simply because I've seen what happens when you don't follow them, and that's mostly confusion.
Wake up - the future is arriving faster than you think.
> 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).
Uh, then might I suggest holding off on pressing the submit button for a few minutes while you go find them? Can just imagine this new project lead in meetings. "Well guys I was going to unveil our new features, but I can't remember what they are off the top of my head."
Little preparation goes a long way.
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.
I'm trying to teach myself to set people on fire with my mind... Is it hot in here?
1) Every project of significance would have a serious requirements document. By that I don't mean heavy on details, but enough there so that everyone know _why_ we are doing what we are doing. Identify stakeholders, customers etc. Vision statement!
2) Every project will have a preliminary design review. Take the requirements, interpret them, come up with a 'solution' and give a presentation to all the stake holders (or representative stakeholders) and make sure that they understand what they are going to get. Don't just e-mail this around and say "If you have any comments make them now or forever hold your peace"
3) Once the code starts comming together, a critical design review. This is for the technical people. Again, no e-mailing. This is a boring meeting where you pick the brains of experts to make sure you have your bases covered.
4) I'm not big on coding standards. A loose one that governs naming and maybe indentation. I would add perhaps a template for things like header files etc. Maybe the standard copyright notice.
5) Up front, think about unit testing. Having working on a project where the only way you could unit test was to litterally include/link in _all_ the libraries (a hell of a make file) I would think that 'modular' should be in the volcabulary early on.
6) All projects need a follow up plan. Software people need to observe, in the field, how their product works. Hearing about complaints once they've been raised high enough is not effect learning. For me, just recently found out that since one of my dialog boxes was too complicated (it had too much backup information) it was simply being ignored... The title "Database Exception" and the first line "Failed to update database" was being lost (and ignored) in the noise. I would have found out later when the data was all coorupted... fortunately I caught it early. Rather than fixing the code, I instituted a policy of training and beatings for those that didn't comply (in case you were curious).
TODO: create/find/steal funny sig.
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.
boakes.org
I dunno, there aren't too many software companies been around 35 years and still going strong. I'd say go with what's been working. The best "coding standards" are: simplicty, adaptability and readability.
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.
None. Boss decides at will, changes mind every other day, cow orkers feel numb. Anybody anything to offer, career-wise?
Force the programmers not just to comment the code, but to write usable docs for classes and functions.
... this is pretty much "everyone knows" but pretty much missing from many places ...
Some programmers do not have to understand what's in, just to call a function
Technically sometimes you spend days just to figure the mess out until you can even start typing a line, while with decent docs, you can start fast....
Also diagrams, flowcharts and the like might help others to see thru a system faster...
I mostly worked as a sysadmin, but even at relatively large installations I sometimes missed a simple network map..... I remember at least 2 places where my work started manually discovering (mean, room by room, flashlight in hand, cable end to cable end between routers, hubs, firewalls) what the hell was happening at the place.....
The funniest (or most sad) was when I found a firewall at a new place, connected into itself. The "admin genius" kept the owners beleive that they are protected by a firewall, while in fact it was just connected to a hub with all 3 interfaces, default config 10.0.0.1-2-3......
I have also been to a place, where 3 programmers/designers (web project) worked on a project for half a year (no docs, no nada, no software) and all they did was surfing the net and waiting for it to turn out.
This is a bit extreme, but actually no one noticed, as management had no clue how long it took what they did, until we estimated it 4-5 days of work for a team of 2 max. I don't know if I felt sorry for them at the end, but the whole office got fired alltogether 3 days later.
My point is: make them document what they do, that also tells if they do anything at all (in case you have a non tech manager, or you are not in their field).
I'm a year into a job that sounds very similar to what you're describing. I took some advice from friends and instated some of the following procedures:
1) Meet with the relevant stakeholders in the new project. Come up with a detailed list of requirements.
2) Meet with the staff who will be implementing this project, go over the requirements and come up with a rough estimate of the time and resources required to complete EACH requirement. This estimate can be plus or minus 50%. Identify areas that will require additional research or testing in order to refine the resource estimates.
3) Meet with the stakeholders again, go over the time/resource estimates. Deal with any ambiguity in the requirements and get their buy off on the current estimates for time and resources.
4) Meet again with the development staff, spec out the entire project with milestones and completion estimates ( this estimate can be plus or minus 10% ).
5) Codify the requirements and the specs for the project into a single document. Include all time and resource estimates. Have the stakeholders (including any relevant middle or upper managers) each sign this document with the understanding that any deviation from the requirements will immediately void all estimates.
I realize that this seems top-heavy with meetings, but once you've gone through it a few times you'll see why its necessary. Having all the stakeholders agree to the requirements and their estimates will protect your staff from scope-creep and unreasonable deadline changes. You'll also find that the more you plan in advance, the easier the implementation will be and the more robust the end result is likely to be.
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.
Use python.
.NET which is suck anyway.
Then you automatically get the code standard. Well, if you are going to be strict of it, you will have to set some *standard* too but, usually many of python codes have very similar way of coding style unlike C or C++ that should have to be explicitly defined. Above mentioned PHP isn't such a good choice since it sucks.
If you are going to use ALL linux or ALL windows, platform independent isn't such a big concern anyway so you don't have to consider mono if you are going to use
You can have C extensions with python. When C only to be used, it is pretty much of suck but when it's used with python you get very clean structure of code since you will code it with C when only it's bottlenecked. There's good optimizer/profiler called psyco. And many numerous such extensions.
What makes python so structured is, it's almost *configurable* structure, not being compositable. So you already have a basic structure, only you change the small pieces even it seems like making a graphical theme of a skinable applications.
Since everyone already know about middle picture, people only have to read the big part and super-little part(C extensions). Middle part is defined, and little part is configurable thus it's standard.
I get the point though, coding standards are critical so that people aren't confused when they look at someone else's code and it is following completely different conventions. It doesn't matter which coding standard you use as long as everyone agrees with it. Try to create consensus on the conventions and allow them to evolve. Forcing things down peoples' throats won't work.
Focus on getting peer reviews into your process as early as possible - like the same day the code is written - maybe even at the same time the code is written. If you wait too long to review code, the author gets a little attached to it and often too defensive. Constructive criticism is more easily accepted before someone has traveled a long road and doesn't want to backtrack.
We have been dealing with this in our organization. In the past, we have been programming by the seat of our pants -- we get requirements, program what we think our Customers want, do a little testing, then throw it into production, then wonder why we have problems in the middle of the night.
Sarbanes-Oxley plus the competition is putting an end to this method of coding. In the past year, we have hired real Project Managers and have begun doing real Project Management.
We now require a Functional Systems Design (FSD), a document that details what the customer wants at a high level. A Computer Systems Design (CSD) document is then written. This document is the actual design of the system that Developers and Programmers use to design the system, design and build databases, and determine what programs need to be written and computer system(s) (PC, Mainframe, Unix)they will live on. Once the programs are written and unit tested, we have a QA department to do real testing. We currently use Microsoft Project, TrackRecord (a Compuware defect tracking tool), and Bugzilla (an open source tracking tool) to track what has been done, what defects we have run into, and how they were resolved.
We still have a long way to go, and have faced opposition from some Managers, but support from Upper Management (and auditors) has helped to pave the way.
Implementing change is tough, but it is starting to pay off in better designed and implemented software which helps keeps our customers around (which means no layoffs, at least for now). Getting requirements in writing is a big help when it comes to analysis and design -- it by no means eliminates problems, but it sure does help reduce them.
Beware of Sleestak
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
I just checked in code that crashes eclipse on File/Open. All the other monkeys opened it. Now what?
Hire developers who know what a brace means, regardless of whether it's at the end of the if statement, or on the next line.
From my limited experience, if they don't have to jump into the code to figure it out, they have to instead jump into the documemtation and correlate it with the code. It's time consuming in another way. At least the programmer doesn't have to re-learn so many things, and can instead focus on the more high level stuff faster.
The more coding standards you have, the more time consuming coding can potentially become. For example, for vertical apps, the more structured (or layered) the app is, the more understandable it is, but it takes longer than normal to code through the layers even after you understand it (compared to not having all the layers and structure in place). Layers tend to make everything within them look similar, more often than not, because each layer has a more specific purpose -- that's good. However when you run into limitations of the many layers, you have a lot more planning to do create a solution that's efficient AND still uses the layers properly. At this point you normally want to start taking shortcuts, but that just starts eating away at the original foundations.
A library of common data structures is good. E.g. .NET strongly-typed data sets in the data layer. Or maybe the Microsoft Enterprise Library for some pre-made, commonly-used enterprise class patterns that you can extend and use. This means developers don't have to re-invent the wheel.
Of course my story is not done yet, so time will tell the outcome of the coding standards pool I find myself swimming in right now ...
enum is your friend!
...
;-(
enum {LOAD_DATA, SAVE_DATA, DESTROY_DATA}
Paul B.
P.S. And of course my all-caps enum values were considered too lame by lameness filter...
heh
"MY APOCALYPTIC TENOR HAS NOT BEEN DISPELLED!" - T-Rex, qwantz.com
The best description I've ever come up with for the Geek mindset is this: a Geek can hold a complex structure in her head and manipulate it with ease. A History Geek can hold the structure of a historical event and see motivations and causes from every angle; a Carpentry Geek can plan an entire piece of woodwork and see every cut and join vividly; a Programming Geek can hold a program's structure and its data and event flows and manipulate it as an idea.
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.
I have discovered a truly remarkable
My moral code is iterative, but the moral code of most of the people I encounter is not.
Mercury is an industrial strength, state-of-the-art
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
For small operations, less than seven people, establishing up front standards and processes just get in the way. Just get the rudimentaries such as source control, automated builds etc up and running and adapt when neccesary. If you have any problems swivel your chair and ask the relevant person. When you notice the same problem coming up again and again create a policy to avoid that problem.
Use a centrifugal chiller for any load over 300 tons.
AND
If you finish the pot, you have to make the next.
That should cover it. Wait, what is coding again?
If they have survived 35+ years doing whatever they are doing it doesn't sound like they need your advice.
Its for wussies!
-USe tons and tons of goto statements.
-Make sure you use particular letters capped for variables of different types to make them more confusing for the losers who can't read the code and remember what each one was.
- always make calls by reference using pointers as arguments. Don't use call by values.
- Hell user other pointers that use other pointers to make things more interesting. Reassign them all over the place
- Never use a three tier model when developing client/server apps. This only creates redundancy and gets in the way of solving the problem.
- When linking to a database always use vendor specific extensions and avoid a database layer using something like odbc. It makes use of the advanced feature set by the particular RDBMS.
- Be a man! Show how much you know perl. Alot of one linners can save tons of time with exotic line switches
Oh last... make tons of money and gain job security because no one in Earth will be able to understand or work on your projects after doing all of these things. Enjoy
http://saveie6.com/
without wasting a couple hours just to figure out the code.
A couple hours???
Look, no offense, but you either only deal in "toy" code, or you have such high expectation that you will fail, and quite spectacularly.
A new coder, even an experienced one, takes days or even weeks after coming into an existing project before he can contribute anything but the most trivial of changes. For a truly massive project, or one that requires intimate domain-specific knowledge in a niche industry, extend that to months.
If you can find a way to get an unfamiliar newcomer up to speed on any "real" project in a matter of hours, consider your talents wasted in your current position.
Bah, extreme programming isn't as good as the coding practice we started at our lab: SUICIDAL EXTREME PROGRAMMING!
:D
Code for weeks, without even trying to compile. When you think your code is good enough, start compiling and fixing it. Well, it is working yet...
Right now I'm more concerned about trying to set up coding standards...
Coding Standards? A good thing. Which ones? Doesn't really matter. Read Ken Arnold's Style is Substance for a good opinion. His point is that you shouldn't spend any time arguing about which style is best; just pick one of the few well-documented standards and enforce it as heavily as possible.
Unless we're talking about really well designed, really well documented and really well commented code, this sounds like a pipe dream to me. Maybe I'm just not skillful enough, but attempting to absorb any non-trival amount of code that was written by someone else is going to take a few hours. You're better off assuming that will be the case.
As far as general software development practices, I think you have two viable choices:
The one thing you shouldn't do is quickly review a few random articles, pull out a couple of the buzzwords, then never think about it again. The number of development groups out there that say they're following a certain process when they're really just winging it is astounding....
Oh, and take all suggestions from strangers on Slashdot with a big, chunky grain of salt :)
--Mid
In addition to some of the suggestions made so far I would add a good automatic regression-test system which runs every night, and reports problems (build failures or result diffs). I've made mine so they "find the guilty" (whoever committed code since the last good regresstion test).
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.
May not make sense to a different person.
You may need these developers on a different project later and want to use a Jr. to maintain your code.
In fact, I would say you need to watch the standards more closley because a small group is more likly to make assumptions.
NOt to imply you need draconian standards, but just letting coders ' do there thing' usually goes very bad in the long run.
The Kruger Dunning explains most post on
I'm sorry, but I think you might have the wrong priorities here. Coming up with standard coding practices should only be your first concern if bad coding practices led to the creation of you new position. Still then, I wouldn't start there.
You've got to realize that your company just added a layer of management, and therefore, complexity, to every in-house project. You should be most concerned with not doing anything that overly complicates the internal development process. Like a doctor, your motto should be "do no harm".
Second you've got to find out what the real problems are (and I will bet you real money, it's not a lack of comments in code, although, they are important, yes). Is the real problem that management can't get realistic information about active projects? Is it that the company is spending too much on maintaining proprietary stuff when they can buy an off the shelf solution? Is it that they're spending too much on off the shelf solutions when they could be developing better solutions in-house?
These are the question you should be asking first, not looking at coding standards.
Because, my argument was, if I have to wash my car then I'm not coding. The general manager agrees, now an AP gets the keys and six bucks every Friday afternoon.
Make sure you use plenty of whitespace. Put blank lines between functions. Don't put numerous statements on one line.
In C (C++, etc), always use {} around the bodies of loops/conditionals. Too many times I've seen people add more code to the "body", without adding in the necessary {} around it. When they test it, it often works anyway because they test the "true" condition and not the false, or the false condition still "mostly" works right.
Comment major blocks. It helps break a function into smaller logical blocks, making them easier to understand.
No silly comments. The "you won't understand this" comment is often wrapped around bad code, and isn't helpful anyway. Add comments to help me understand it, not to be silly.
Use consistant indenting. Also don't indent based on the length of the loop/conditional statement. If the loop is modified, you don't want to have to spend a lot of time re-indenting the code.
Periodically go through the code and remove "#if 0" (or related) when it is used to comment out sections that were re-written, but the old code was left in, in case the new code wasn't any better. It ends up as useless clutter.
name them well, and the code becomes drastically more readable. Don't use ambiguous abbreveations. Set up a system for naming functions based on what they do. Also, in C++, include the variable names in function prototypes, even though they are ignored by the compiler.
// Returns true if ... False if ...
bool descriptiveFunctionName ( int lowerBound, int upperBound );
By naming functions and variables clearly, less comments are required to completely explain what a variable/function does.
"Scud Storm!" -- Jeremy of PurePwnage.com
"Without wasting a couple of hours"?
It is a joke.
"Let programers do what they want. "
thats great, assuming they all want to do it the same way.
"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."
well done, now you have developers constintly changing the same code. there goes stability.
"
Don't comment your code. Make the code so damn readable that a comment is superfluos"
not possible in the real world. No matter how well you code, it can never catch the intent of what you are writing. Only by stating intent can someone know if there is a problem.
"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."
there's a great way to waste time and money. 'Feels right' isn't the same to everyone.
"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."
how about you get fired for being too damn stupid to set up your IDE to conform? Other tools besides your IDE may be looking at that code.
The Kruger Dunning explains most post on
Do you have a citation for the source of this statement?
It is a severe roadbump to try and read code where the braces are at the end of an if statement instead of vertically alligned.
I agree.
Did you intentionally give a nonexistent web url?
When will /. provide a method of contacting a comment submittor that does not require posting a comment or the author supplying a public address?
I know what you mean about coding standards. I have worked in so many places and have been asked "Do you have any coding standards that we can use". So instead of carrying around stacks of documents, I have placed them all on one site. Go to Delphi Coding Standards this is a Delphi coding standard I follow, but I'm sure you can apply it to all languages as required.
I'm sure many others here have already gone on and on about coding practices, so I'll go in other important directions.
:)
Beanbags. Very useful. Especially when you've got those incredibly stubborn bugs, and feeling careless and jumping about and falling. *grin*
Food and drinks (coffee). Increases productivity greatly.
I've also appreciated how the QA team is ideally located in separate offices from devel. Things get pretty messy.
It is not exactly a coding standard but sort of related. My department used to have a policy of no check-ins until you are submitted to the test : building a small (~20 pieces) Lego toy. You could even use the instructions if you couldn't figure it out :-)
You only passed the test once your boss thought you were ready.
(copy paste as much as possible)
C# - The C# Coding Style Guide, Mike Krueger(SharpDevelop). This is probably the most widely used one (Novell). It largely agrees with Microsoft's internal coding standards, with a few exceptions. .Net Coding Standards, part of the SDK. This is not comprehensive though, like the C# doc mentioned above.
VB -
Version Control -
Server: Subversion + Apache
Client: Tortoise SVN (Excellent) [We also use Perforce, CVS, VSS(Commercial apps)]
Continuous Integration - Cruise Control.Net
Intranet, Knowledge Management - DotNetNuke (www.dotnetnuke.com)
Project Management - dotProject (PHP) (www.dotproject.com), MS Project
Unit Testing - NUnit (www.nunit.org)
Life is just a conviction.
1. Everything in source control. Everything.
... they have needed expertise, and no one else can learn it on schedule. ... someone else is leaving. ... you JUST shipped the last version and have plenty of time to bring the new folks up to speed.
1.1 Source control on RAID.
1.2 Occasional offsite backups.
2. Get everyone on the same page as far as who's going to do what, and how the parts will talk to each other, before anybody writes a line of code.
3. Never add manpower unless:
3.1
3.2
3.3
4. (This is a more personal-level tip) No AIM, no IRC, no email while coding.
5. Use Ruby. Or Python, even.
Save time now so you can waste it later
Have your developers read this fantastic set of course pages:
http://osl.iu.edu/~lums/swc/
The course is sponsored by the python foundation, so there's a lot of python embedded. Still, its one of the best and most complete collection of best practices and resources I've come across.
It's most certainly not a quick/easy answer, but if you write-up your own plans/procedure/standards based on the guidance it contains, and then have competent people follow them (and audits that verify this are pretty much required), you'll most likely produce a very good software product. That said, it will also almost certainly take longer and cost you more because of this additional overhead. I work for the FAA, and their perspective is that this is a required expense since a failure at the wrong time could have very serious consequences, but I suspect a subset would still be useful in most environments (if nothing else, you'll probably reduce your long-term maintenance costs on large/complex projects).
This is a subject near and dear to my heart. I have a history of coding in small shops, from 1 to 7 programmers. I currently work with two other programmers at a company that has had 4 programmers before us that are no longer available to us. My coding style is very different than my coworkers'. My code is very dense, with few comments, because I believe the code is the comment, and frankly, I think if a compiler can understand it I should be able to also. But that's not important here. I think it is useful that we all have different coding styles. In an environment like mine that has only a few players we learn each others style and know who did what just by the way it looks. It's also nice to see where one person has modified another person's routine.
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.
1) Use standard containers (e.g., STL or boost data structures) and algorithms as much as possible. ;)
2) Use smart pointers whenever dealing with dynamically allocated data (auto_ptr, shared_ptr, shared_array, etc.)
3) Use a standard, easy-to-use error checking mechanism for error checking during development (assert or a custom version thereof). Make it easy to comment out for the finished product.
4) Use a standard, robust method to handle error conditions in finished code. Don't confuse these errors with development phase errors (see point 3). It's not nice when a finished app just crashes and spits incomprehensible garbage on the console.
5) Devise a standard way to handle input errors. Either use C++ exceptions consistently, or have functions return error codes. Try to stick to one method or the other.
6) Look into using SVN instead of CVS (this applies to all languages).
7) Insert geeky jokes into the comments whenever appropriate.
It's funny. I work very closely with two other programmers, although we work on almost disjoint bodies of code. Our coding styles vary widely. One of us uses Hungarian notation, one of us does not, one sometimes does and sometimes doesn't. We use different indentation styles, different nesting styles, different personal styles for naming variables.
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.
"How to Do Nothing," kids activities, back in print!
Read The Pragmatic Programmer. If I ever start a company, this is going to be required reading for every employee.
RAD Dude! Nuff said.
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
Build it, and they will come^Hplain.
In C++ we use Doxygen. Basically as you write comments inline you use a few shorthand markers (kinda like HTML tags, sorta, not really) to tell Doxygen what to pick up. Generates pretty good documentation and graphical class charts, etc. Works pretty slick, Doxygen is then pure HTML + png documentation of your code.
-everphilski-
and NOT This is something you learn when you first start writing code so its a preference thing. The engineer put it loud and clear that he wanted it this way, to avoid controversy.
Along with useful variable names, method signatures and plenty of comments where needed. It really doesnt matter to me, Im not Visual Studio does it by default
I have recently aquired the book "C++ Coding Standards - 101 Rules, Guidelines, and Best Practices." ISBN 0321113586 or http://www.amazon.com/gp/product/0321113586/103-00 42056-9954216?v=glance&n=283155/
Mountain Dew and coffee, mainly.
Coding standards are language standard, or language specifications.
A developer who does not understand any piece of code does not understand the language and hence is incompetent.
Of course one can write obfuscated code, and developers should be encouraged not to. If your developers are not capable of writing meaningful code in a language, change the language, change the developers, or as a last resort change careers, your company stinks.
Setting coding standards would be the same as restricting the English language to a subset in which, for example, George W Bush would be capable of forming a meaningful and consistent sentence.
Don't mandate Hungarian notation; what a waste.
/* this loop counts from 0 to x */
Keep procedures short and simple and use a lot of them.
Don't repeat code when possible.
Comment where things really are confusing, but don't waste comments on things like
Don't nest if statments too deep, and when you do nest them, don't put 400 lines of code between the if and the next else. Use functions.
Use preprocessors to let the compiler work for you, but don't put ifdef's inside your actual code if possible.
Get a good set of base functionality and let everyone utilize it. Its a lot easier to optimize 10 functions than it is to consolidate 5 versions of those 10 different functions and fix all the code.
a) Use lots of goto statements
b) make sure not to check buffer lengths
c) put knock knock jokes in my comments
d) name my variables after dragon ballz characters
Oh btw work for Microsoft and on the windows vista development team.
" and finding out that those things no longer apply because somebody changed a 1 to a 2."
Comments lie. Code never lies.
Need Mercedes parts ?
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!
I've worked on several "standards" documents and I've found that they are mostly ignored because there are too many items. After you compile your list of items you want to control whittle the list down to the top ten that you expect people to know and follow and that you are willing to enforce in code walk-throughs. (You do code walk-throughs don't you?) Another suggestion is to let the developers vote on some of the items, they are usually more willing to follow conventions if they have some input and feel that there is a consensus.
Everyone has pointed out most of the stuff you need to know from the development side. CMM and CMMI will give you most of the project standards you need - pick up a starter book and in about a day you'll get the basics. Maybe something like Information Technology Project Management by Kathy Schwalbe - very generic. The big key to take from here is to get the proper scope before starting and have everyone sign-off at the beginning of what they expect and at the end that you satisfied their criteria. Nothing else anyone said here will matter if you don't do those two things.
Secondly I come at this from the support side, because our developers write stuff and dump it on us. We also have developers that document the program and spend a day with the support team going over how to use it effectively - showing them tips and tricks. So the best code can be viewed as a failure if the users and support staff start knocking it because they don't know what they're doing. If you get them up to speed though, they'll support you 100%.
In both cases the key factor is public relations and cya. The larger the company you work for the more you need to worry about things like that unfortunately.
However, I would like to say this. From my software engineering experience (which includes big companies, medium sized ones and startups), too much emphasis on coding style, development process, code reviews, bug tracking systems, naming convention, etc., may hurt the team's productivity.
To do everything perfectly, engineers need to spend time indenting code, changing variable names, making sure correct information is in the bug tracking system, waiting for somebody's code review, etc. That adds a lot of hours to development time, in addition to the time to actually develop software. You may also need to hire a manager to make sure everything is OK.
Worse yet, if too much focus was put on to such things, the team's mentality may eventually shift to "let's code everything right and clean", rather than "let's develop something great and innovative and help our customers". That's not a winning formula.
So my advice is, learn the current infrastructures your teams have. Chances are they already have some kind of systems and they may be fine to a certain degree. Listen to your engineers, the lowest level ones included, on what is broken and should be improved. Fix only the broken things that are hurting productivity. Fix them in the least intrusive manner. Sometimes, the laziest engineering manager is the best one.
Good luck and let us know how things go.
Magic numbers are the worst thing you could ever put into code. They are even worse than hungarian notation...
You need only Version Control System, this is the only one thing that matters.
It can be CVS, SVN, ClearCase...
You have to use it religiously.
Insisting on coding standards assumes that you treat programmers as they are idiots. If not strictly enforced the coding standards will be just ignored.
Steve McConnell's Code Complete is an excellent source for coding standards and a good read for any developer. I don't agree with everything in the book but it is comprehensive. Ignore that it's published by Microsoft Press, it's a good one.
It might go over better than dictating.
You should also worry about development practices. Just having good coding pratices will not gain you much in the way of robust and easily changed systems. Having good development pratices will.
Specifically, I'm referring to having a complete system of specifying the requirements for any system. Too many coders these days start a project by hacking up the first thing they think is necessary, then the second, then the third, etc. While this ends up working out for most small projects, big projects can quickly become unweildy. Not to mention, if you bring in a new developer after years of working like this, the learning curve for that developer is very steep.
Enter Hatley & Pirbhai's Strategies for Real-Time System Specification. In this book, the authors outline a set of strategies for developing complicated systems and making them as robust as possible. Now, you may be thingking "Who are these guys and why should I care what they have to say?" Well, they used to work at Boeing and they developed their strategies while working on designing a plane. (I think it was the 777, but I could me wrong.)
You should definately read the book, but the strategies they present basically boil down to defining the whole system from the perspective of what, how and when--separately. Here's how it works:
This may seem like overkill, but it's not. I've been working like this for a few years at college now and it has huge advantages. Development tends to go faster, problems can be fixed faster and--most importantly I think--new developers can sit down with the specifications and get up to speed very quickly.
Overall, I think using strategies like Hatley and Pirhbai have developed is far more important than all the coding practices and code commenting in the world.
Of course, YMMV, etc.
--JamesCoding styles are one thing. Version control is another. But you need to step even further back if you are managing the entire development process. What am I coding? What are the requirements? How will my design fufill the requirements? Without answering these questions, all the proper coding in the world won't matter. Your boss/customer will want their requirements met, and if you aren't managing the development efforts from the beginning incorporating a solid design, you've failed before you write your first bracket. Being a development lead is one thing, being a project lead is another. If you aren't responsible for the project aspects, make sure somebody is.
comments everything.
segment everything, make sure the code has distinguishable parts.
Less of a specific approach and more of a "this guy can help you learn about your options" is Jack Ganssle (website: http://www.ganssle.com/ )
He focuses on firmware, so its not highlevel application stuff, but if your lowlevel his insight and suggestions are pretty useful. The core of his work is presented in lectures he gives, both publicly and privately for specific companies.
He also writes monthly for Embedded Programming, normally something funny but with a serious point. And to cap it all, he's a pretty nice guy.
Check it out, see what you think. He helped me improve my coding and my team quite a bit.
That's 4-space indents, and spaces not tabs. Function and file headers, file headers basically for what the entire program does (not big ones, mostly perl or Cadence skill language scripting), and intelligent as I can comments of what I'm doing and more importantly WHY I'm doing it, so I can make sense of it myself long after I've forgotten what was going through my mind at the time.
My company doesn't really have any "standards", and most people don't format much at all and rarely, RARELY, comment anything whatsoever. The first thing I do when getting into someone else's code is to reformat it to my personal indentation style, as I get a better view of code flow with 4-space indents than single-space indents. I think single-space indents are pretty much meaningless as it's hard to follow without really paying attention to it, and sometimes you want to get a feel for where you are at a glance instead of at a study session.
I wish there was some company requirements, but we're electrical engineers not "real" programmers, and I guess no one else in the office cares if they can read their own code 6 months later.
You mention "a couple of hours" for a developer to get up to speed? So what? You want to add incremental work to every trained developer's workday so that you can save a little bit of a newbie's time?
The reality is that company that treat developers as interchangeable modules that can pump out standardized units of effort get crappy results. Regression to the mean and all that. Everyone wishes the "other guys" would conform to standards, but there are real reasons that cookie cutter code is not at the top of the list of success factors for a good project.
The best thing you can do is to identify your key lead developers, keep them happy, and make sure they are doing a halfway reasonable job of spreading the knowledge around. Oh, and recognize that if they leave you will take a hit. It comes with the territory.
The alternative is to use process and standards as a club to force conformity, which will make your shop into a place that most folks with talent don't want to work.
Premature optimization is the root of all evil
Snowden and Manning are heroes.
In my experience, the last thing that people that worry about coding practices should worry about, are coding practices.
Unless you have procedures in place for testing, deployment, version control, code sharing, change request system and more, then those are bigger concerns than how you indent your code and what naming conventions to use.
I'm not saying that coding practices aren't good. Just that you likely will achieve better productivity by focusing on other things.
If you are hiring, make sure that you hire a seasoned software engineer and not a code monkey next time. If you aren't hiring, then research the web for ways to improve how your team builds software. What is best for you will differ quite a bit depending on your exact situation.
If you want code practices, then focus on "best practices" or patterns over cosmetic rules. Try to centralize code that support common patterns, such as error handling, database access, GUI components and so on.
Think about it this way. Your team can only absorb a certain amount of improvements. How much this is depends on the individuals on your team and how well you are able to introduce these new things. Think about the improvements that you want to make and prioritize them.
Man, this ended up sounding like I think I'm the best thing since sliced bread. I'll post anon.
I apologize if this is a stupid question (I am an MBA) but what is wrong with Hungarian Notation? I thought it was supposed to help people keep variable and object types clear? What am I missing? Thanks.
Coding standards??? HAHAHAHAHAHAHAHAHAHAHA!!!! Coding standards... hehe... that's a good one.
Let's see, I'm an independant contractor & while nowhere near the best, I feel that I'm more competent than the average coder- I'd say 90% of the companies I've contracted myself out to the code ranges from incompetent to criminally insane. I can actually group this into two subcategories further- coders who have no skills with relational database theory background, and DBAs with no coding background- and then there's the odd web programmer with neither.
My advice (the worst vice)- keep your comments simple & to the point (just like your code should be) AND don't create two different variables with the same value and use them arbitrarily. Yea, you know who you are.
nUthinG wOrse tHan hUngArian nOtashioN. You only need to look at typical MS Windows code to understand why Hungarian notation is a really, really bad idea.
Oh well, what the hell...
We use Accurev. Don't *EVER* use Accurev. It's the worst piece of software I've ever seen written.
Read and apply the Pragmatic Programmer.
Two things that have helped me a ton as a developer:
1. A good revisioning system. Being able to look back at a previous version of a piece of source code, compare revisions, etc., is a big help, as is being able to manage branches for easy concurrent development of different versions.
2. Invest in some VMWare licenses. You can set up standard development or build environments so everybody's working from the same page. Also, using snapshots is a HUGE boon for debugging. When something crashes or otherwise doesn't work, you can run through it again in exactly the same state, over and over, until you find the problem.
I see a lot of comments in this thread about coding practices and the like. That is fine, but I think you would do well to think about practices that matter more. You have indicated that your environment really doesn't offer much of an IT infrastructure, which means that you will more than likely play an appreciable role in many of the following processes: requirements management, quality, change management, project management. There may be many instances of your behavior causing projects to succeed or fail, and they will have nothing to do with whether your people are commenting their code.
If you can, put together a process that specifies how all of you can define a product, start a project (get a suit to sign off on it too), deal with changes in requirements without tanking the project, assure quality, and ship. The code will take care of itself because it is the only thing you will have a decent amount of control over. Everything else is cross-functional, which adds a great deal of difficulty -- hence the need for policy.
Just remember the "ship" part. Don't get stuck too long in defining a process because none exist which are universally indicated, completely effective, or free from ruinous meddling and circumvention. Worry more about what can keep you from shipping and try to set a policy that will prevent those things.
And most of all, watch your cornhole -- technical leads are sh*t magnets.
As a software process expert, I can give you the secret three best practices that every programmer must follow:
1) Find someone to blame for failure. Usually it's the new guy. Keep him stupid and drop hints to the project manager that he might be messing up the code
2) Try to make your programming complicated. Hey, if anybody can do it they are liable to hire some Indians to do it at three bucks an hour. Try using ancient Egyptian for your comments. Name all your variables something like A1 and A2. Catch and throw away your errors -- you don't make mistakes anyway. Let the calling code bomb, not yours
3) Get a week ahead on your status reports. What did you accomplish this week? Put that as your goals for next week. Every week you'll hit your targets dead on. The other guys will flail. Try to be sympathetic to them. Offer to help out with their programming.
This is my blog
All the of the PHB's just make use do lots of TPS reports.
Figure out the code in a couple of hours? I'd be happy if I could find the code in a couple of hours.
If you have the time, have a second programmer take a brief look at the code and evaluate it. If they are able to read the comments/code and give an accurate description of what the code does, then pass it. If not, send it back to the first programmer to be cleaned up.
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
Huh. I'v ehad to figure out someone else's code before, while I actually was working in software before my hardware design job. My employer licensed sources from a partner company for merging into my employer's larger system. One component of the messaging system had no documentation and virtually no commenting, and what rare comments were there were wrong. My task was to document the messages, their structures, and what each message type was used for so my coworkers could fill in the two ends of this communications system.
It was 2-space indented, which I had to change to my favorite 4-space indent, so I could see the flow of the code. 2 days. Understanding the flow, 3 days. Picking out the details of each message type, 4 days. Adding comments as I went along to help remember what I figured out earlier. 3 or 4 more days to type up a document for the thing for other coders to use. There were only 6 or 7 functions, and less than 10 message types. Still took a heck of a lot longer than a couple hours to ficure out what was going on in there.
it definitely works!
But seriously if you want to have readable code you really need to have useful commenting, where you don't comment every line just the ones that are out of the norm or do somethign crazy. I find that using a naming scheme for variables works extremely well. For instance, if you have an object of any sort o_objectName, an integer i_intName, a String s_stringName, etc. It lets the reader know what the variable is for and what type it is when you are looking at it. I hate when people assign dumb names to variables, makes code a pain to read.
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.
So they asked u to create standards? Well basically they put u in one hell of a shitty position since most people are no longer going to like you. From the sounds of it u work for a company where IT is a supporting role, not a Money Making role. If i were u I would create the simplest standards to get the job done. The most important thing to do is be PRODUCTIVE! if you are not productive who cares what standards you have, cause u ain't gonna have a job. So if I were u, make is SIMPLE. ONLY put commects in areas of code that are NOT intuitive. put all code in same place, have a testing environment and production environment. Anything else the tradeoff is time used will not be worth it to the time away from pure development. Any coders worth there salt will perform very well with minimal standards. Besides the previously mentions, on a need only basis for everything else, such as backtesting etc... in non software shop they are of VERY VERY limited value. Productivity is what matters ... and beisdes, no one likes the guy who makes lots of standards and makes there lives miserable.
:)
Thinking about it again though I should probably reconsider my advice, the more standards you guys put in the more of a chance you wont deliver and the company will get desperate and hire a high priced whore like me to come in and get shit done and pay me lots!
My Web Site - www.ocean-liners.com
If code is written well, it should have few comments as the logic should be fairly obvious. In the case of if (x == 456), this should really be something like "if (STATUS_BUFFER_FULL == statusCode) ..." now it's obvious what is going on. Descriptive variable names and method names mean less comments are needed.
>> refrain from cursors/temp tables
Try running a data warehouse type application without them, smartass.
Put code that goes together, together. If a section is long or coded sloppily, make a comment summarizing what it does. If it's coded too sloppily, delete it. If it makes sense, do nothing except more of the same. There is your guide.
My boss encourages us to use extreme programming tactics such as daily status meetings, recording and tracking stories and tasks, estimating hours and code refactoring. In addition, we have a continuous build system in place (Cruise Control) and version control software (Subversion with Tortoise client). Also, we're encouraged to use a Test Driven approach and the unit tests are executed within Cruise Control. We comment our code, but I've noticed that this environment really encourages quality code, not the code commenting. So, my suggestion is to read up on agile development, scrum, and extreme programming before trying to pursue coding standards. I think you'll find those more useful in creating quality, maintainable code. That's my 1 cent.
jg
I am a big fan of having a standard coding style. By this I do mean having developers follow a fairly strict set of rules on comment style, where spaces belong, spaces vs tabs, indentation rules, naming conventions, ect. There are many different ways you can do each one of these points, but the important thing isn't which way you choose, but that your code is consistent. That said I would apply these rules only to new projects and leave the old projects as they are. Cleaning up active projects makes diffing for differences in files nearly impossible.
So long as we don't end up on dailyWTF it's all good.
"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"
HAHA bra haha
Good one!
HA!
hehe
Ok seriously - WTF? A couple of hours? What color is the sky in your world? Even the best commented code in the world is going to take a couple of hours to understand. Exactly what kind of trivial software are you thinking of developing?
Some things are really in the motherhood and apple-pie categories: revision control, a build system architecture, bug tracking, documentation of the codebase. A lot of other things like coding standards and naming conventions are, to me at least, less valuable. I'll articulate on why that is later on.
The real important point: All of these things are tools to used to produce something hopefully useful. Having a killer bug-tracking system or a great coding standard won't keep your company in business. It won't even guarantee that you'll produce a great product. Lots of successful companies have been arguably successful without those things. Lots of software we all use and love has rather repulsive code at its heart, and even the cleanest projects have their dank corners. I've worked for lots of companies that aren't around anymore that did have excellent coding standards and even followed them, though.
Far more important is making sure that the people writing the code and the people who know the requirements are able and willing to talk to each other. Preferably over many beers. This is even more important if they are the same people.
About coding conventions and comments: we humans tend to see what we expect to see when reading source code. I'm usually a naive, trusting person and if the comments say that the code does X, I assume that it does X. Even if it doesn't, really. And figuring out what it really does when the comments are out of sync of the code (and face it, that always happens -- smart people have been writing buggy code for decades now, and having the code out of sync with the comments is just another bug that there is no way to detect except through unpleasant experience) is often harder than dealing with no comments at all. On the other hand, if I come into a project and am handed 50k lines of C++ from someone just fired for an act of workplace violence and no comments except copyright notices I know I'd better put my thinking cap on and pay attention.
Follow this document and you'll be irreplacable.
Most of my coding practice uses the keyboard. I tried just using the mouse for a while, but the keyboard really makes it easier to code.
...but the margin of this posting is too small to contain them.
I have worked on a number of big projects in a number of organisations and 'coding standards' are one of those issues that are always contentious and divisive. Even in my current job I have been pestered by individuals who insist that K&R style indenting is 'our policy'. These same individuals seem to spend more time on these relatively trivial matters than actually co-operating effectively and maturely in our collaborative efforts.
I think team communication and an environment that nurtures and repects all members' opinions and contributions is the most fundamental aspect of successful software development. Of course decisions need to be made and here is where you will need some benevolent despot or despots to act. But these decisions should be made after consulting with the group.
I would forget about coding standards for now and concentrate on your development process, namely how do we decide, communicate, feedback etc in order to get the job done. When all members of the team feel they can contribute effectively to this process you'll be amazed at how productive they will be and how easily they will accommodate slight differences in coding standards.
Having said all that, you could of course all agree that code will be commented and use certain methodolgies, components, etc. But these will be easy to do if the group comunicates well.
I'm not really one for coding standards, just make each person maintain a certain level of consistantcy and make damn sure they make good comments. You might want to institute some common variable naming scheme. Here are a few rules I've come up with over the years.
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
We are using Dosygen for documentation on my current project. Doxygen works fine.
:)
However, the project lead has decreed "No Comments In Source Code". ! So for the last release, we hires a batch of Interns to document the source, ran Doxygen, then threw that code set away. For this release, I am adding comments back to a new source tree. Which will be thrown away.!
Don't let anyone become as powerfull as this 'leader'. (Even yourself!) Make sure that everyone agrees to the standards, then follows them.
Even so, this is better than the geek I once worked with who wrote 'self documenting assembler code'. Think about it.
Every file should compile cleanly with a specified set of warnings on. With gcc, I use -Wall -Werror (with some other flags like -Wshadow that aren't turned on by -Wall).
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.With that said, I would just pick a standard for each language that you use at your place of business. How are you going to enforce the standard? I assume that there will be peer reviews, right? Ok, good.
Oh, by pick a standard I mean a conventional programming style is all. I believe that Steve McConnell has some good ideas on this in Code Complete.
(brother or sister)!
to which I would only add one caveat: don NOT be overly clever. Write code for maintainabilty NOT for a clever solution. Maintaining code can cost much more than writing it. stupid and clear is better than clever than obscure.
putting the 'B' in LGBTQ+
Most standards are relatively meaningless. Indentation, Spaces not Tabs, "All class names must be descriptive", "Comments are required" - really this is all hand waving. Let individual groups figure out what's best for them. And stop thinking like a boss, or you'll find yourself with no one to manage pretty quick.
------ Tim O'Brien
I wouldn't work for any company that tried to tell me what "coding style" to use. I'm a retired programmer with 35+ years of experience BTW.
9/11 Eyewitnesses to Explosive WTC Demolition 1 of 2
Avoid writing any comments that have to be changed when the code changes. Act as if the people who will maintain the code will never update the comments. It's not that they never will, if they're any good at all they always will, but in a lot of environments it doesn't. Comments that have to be changed with the code make the code harder to maintain because of the volume of change that has to be made. They make changes more error prone for the same reason -- the bigger the change the bigger the chance that something will go wrong. Furthermore your compiler will never complain when the comments aren't updated and faulty comments will never cause a test to fail.
Source code can be very expressive and that expressive power ought to be leveraged to its maximum extent before being augmented by comments. At that point it should be augmented by comments, but those comments should be all about things that can't be expressed in the code like exactly where I can go to read about the algorithm you are using (title, author, revision, page number, URL -- be specific), implicit preconditions, class comments describing their single responsibility, non-obvious side-effects, the reason for some complicated piece of code (only when the code itself really can't be made simple -- like for a profiler driven optimization for instance), your email address. Anything that I as a maintainer could possibly need to know that I can't find out by studying the code should be in a comment somewhere. And nothing else should be. The information that can only go into a commment is too valuable to be obfuscated by other gratuitous comments.
If you want code that can be readily understood you need something other than coding conventions. Coding conventions only make the code all look the same. You can get almost all of the benefit (without most of the arguments) by saying only that each file must be written with the same coding convention throughout. The code will get prettier and prettier with tighter conventions and developers will waste less time reformatting each others code. But it won't do a thing to make your project more understandable.
For that you need an understandable design and the best advice I've ever seen for that is in Eric Evens' "Domain Driven Design" http://domaindrivendesign.org/. The advice there will work for both Agile and non-Agile projects and its core themes are pretty much unavoidable truths about how to write code for a project that is also written about the project: use language that comes from the projects domain, insulate code from each domain or sub-domain from the rest of the world, keep each method at the same level of abstraction (that's big) and make implicit concepts explicit, to name a few. The key is for your developers to consider themselves to be authors and to strive to keep each little piece of code they write on-topic. Not only will it be easier for new developers to come up to speed but the code will work a heck of a lot better too.
People here seem to focus on coding rules but in my experience developers don't follow coding rules. The better the developer, the less likely he/she will follow coding rules. IMO what's more important than coding rules is the environment. I would first standardize compilers, tools and OS between all developers.
That depends on what you expect it to tell you.
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.
Advanced users are users too!
If it compiles, ship it. If it doesn't compile, ship it. If the users complain, ignore them (they are always complaining). If the users complain moreso than normal, work all day and night and fight with QA and the admins and the VPs to get a patch in.
Repeat until app becomes unmaintainable. Repeat furthur. Repeat.
I will be giving seminars on how to implement Sisyphusian Unified Process throughout the year down at the bar. If I happen to be unconcious, please leave me be - that's my "comp time".
Use indent for C and C++
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.
Also, I find that hungarian notiation, while sucking to write, is very easy to read.
- I voted for Nintendo and against Bush
Statistics, Politics, and Code Comments
One man's pink plane is another man's blue plane.
1) don't code before you have to
2) draw pictures
3) consider extreme cases
4) only use the data you have
Of course, there are plenty of other practices, but those are some good ones to start with, especially if you have relatively new folks.
How about striving for a CMM Level for the IP department of your company. That will actually put you on course for a streamlined process.
Coding standards won't help.
DESIGN standards are what you need.
Just hand out a blessed indent(1) configuration and get on with making sure people design and implement understandable software instead of spazzing about indents and brackets.
Besides commenting code, running a code review (comments included) on every change to the code is key to maintaining quality and keeps people more up to date on changes. Implicit in this is using a decent versioning system and having a set of standard practices.
If code has a consistant style and format, it is far easier to read. Also, forcing a team of coders to regularly "eat their own dog food" cuts down on hack and cruft and encourages good code housekeeping.
Don't allow pillage and paste coding. Duplicated code should be refactored.
bon chance
"None are more hopelessly enslaved than those who falsely believe they are free." -- Goethe
As someone with 20+ years of professional programming under my belt, a lot of it doing maintenance and enhancement of existing code, I'll say this: most of what's considered "coding standards" doesn't much matter. Indentation, brace positioning, type prefixes on variables, underlines vs. StudlyCaps, capitalization in general, most competent programmers can pick up on any variation quickly. The few things that count are more general:
We all have better things to do than make sure we use "var=value" here and "var = value" there. That's just overhead. The nature of the standard doesn't really matter - even hungarian is perfectly readable once you get used to it. But committing to a project-wide standard gives everybody a lot less bother in the end. Except for people like you I guess.
I've never met someone like you in the 15 years I've been in this business. Maybe that's because I wouldn't work for a company that indulged egos like yours.
I think that you should ask yourself if you only want to enforce coding standards so that you could feel more "in control" of things.
Especially if you are yourself a non-coder, this might make the coders feel like you want to boss them around instead of listening to them. It might very well be that they themselves have excellent suggestions on how to improve the things overall. They might also wish that you could forward these to upper management.
to books like Bob Martin's Agile programming. It presents few hints from real-life experiences, test-driven programming, refactoring code etc. It also introduces rules of thumb to avoid pitfalls from code to uml-design by experiences from real-life projects.
Use what you and others have made before; code as if you'll be using it again later.
Yes, I am the one with the legendary sig.
If the comments disagree with the code, they are both wrong.
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.
DOes that mean that I have to accept the crap that some people put forward as code.
Standards should at least set a minimum. meaningful comments, code that is structured, etc.
MOst good programmers think this is common sense, well it is.
Mostly these threads focus on comments and naming conventions. One of the most important coding styles I've adhered to for the last decade is to always encapsulate new and delete within a class. This ensures every new has a corresponding delete called when the class's destructor is called. Use C++ automatic variable declarations to control object lifetimes.
The only time I've had a memory leak in the last 10 years was when I had to break this coding standard (eg for library compatibility).
The second most important coding style is to use pointers only when necessary - some graph algorithms need them, and so do some "legacy" C libraries. Otherwise, use references - there in the language for that purpose.
The 3rd most important coding style is use standard library container syntax whereever it makes sense. Even if you write your own container libraries - follow standard library conventions. Makes it much easier for other coders to follow.
After this follow a bunch of useful stuff - eg ensure that meaningful default, copy constructors and assignments are available for your class, use the const keyword wherever it makes sense
On the subject of naming conventions - naming conventions can lie! Tools like doxygen will quickly tell you what a particular indentifier refers to in a particular context. If not, then grep is pretty handy at working it out. However, often one wants to use the same name for type names and instance names - a convention like first letter upper case for typenames, or appended _t can help the addled brain.
Throw open a question now - any good tips for organising namespace names, and macro names to avoid the inevitable clashes?
replace a stupid name with a sensible name:
messages_processed++;
This actually makes sense without the comment.
The most important standard to enforce strictly is that everyone should use emacs (vi) and absolutely shun using vi (emacs).
There are three categories of standards:
;-)
1) First, there are arbitrary choices where uniformity across the company is more important than having a perfect fit for each project.
A perfect example is the choice of information management tools and formats. Unlike an indentation style, a source control or bug database learning curve can be a significant barrier to a developer helping out another team for a few days. It's also important to ease access for non-development personnel. Pick some tools and make everyone use them.
"Every project shall use Subversion as its source control system, BugZilla as its bug tracking system, and DocBook for user documentation."
Depending on the size of your company, the choice of a unit test framework or a build tool might be standardized. Keep in mind the benefit of diversity in these matters, though.
2) Second, there are matters of practice that can be fairly unambiguously stated and checked.
A few examples:
"Every project shall version its acceptance tests."
"Every project shall archive acceptance tests and test results for every software release."
"Every project shall publish a current schedule, updated daily, and a summary of outstanding defects, updated at least weekly, to the IT intranet."
"Every project shall maintain a system of peer review, so that all code must pass by a second pair of eyes within a week of being committed."
"Every project shall automatically generate API documentation."
3) Third, there are matters that may be important but shouldn't be included in your standards.
There are two good reasons for being so picky. First, you want your standards to be as short as possible so people actually read them. Second, you don't want to publish standards that you can't or shouldn't enforce.
An example of a good coding rule that doesn't fall into the first two categories is "Document intent, not mechanics." Everyone should do it, but checking and enforcement should be done among project teammates, not by a higher level of management.
Another example is "Test everything that can break." The extent of test coverage can only be determined by people actually working on the project, so you can't enforce this rule. It's a great rule, but it doesn't belong in your standards.
Since so much attention has been paid in other posts to matters of code formatting, I might as well add my two cents. For languages where there is One True Way, such as Java and Python, there's no good reason to deviate from the One True Way. Is it really your job to point out and enforce the obvious? I don't think so. Let the project managers handle it.
For other languages, such as C++, there are a variety of accepted styles. Uniformity is good, and every project should certainly pick a style and use it consistently. Whether to pick a uniform style for the company is a judgment call. Professional C++ programmers are used to dealing with variety and shouldn't have problems switching when they jump from project to project. For your company the right rule for dealing with C++ projects may be this:
"Every project that uses C++ shall adopt and publish a uniform brace and indentation style."
Or it may be this:
"All C++ code shall be formatted as in The C++ Programming Language, Special Edition."
A final note: Be firm about setting standards, but talk to people first and don't issue any orders that you don't have the muscle to enforce. Find out what people's prejudices are and eagerly defer to them when it doesn't make much difference. Migrating CVS users to Subversion should be no big deal, but if a bunch of stubborn CVS users refuse to migrate, and you fail to make them, all the rest of your standards will go out the window as well. If your authority is shaky, the best way to shore it up is to avoid controversy and issue a bunch of commands that nobody minds obeying
Actually, code can also lie with all he optimization the compilers do nowaydays.
So: comments lie, code sometimes lie, disassembly never lies.
In my previous position we drafted a coding standard based on the recomdendations on this book, then we had a peer review with several of the senior developers changing the rules and recomendations. (I personally disagree with some of the unqualified statements made in the book - then again, for every rule there is always going to be an exception)
It really annoys me where I work now, where developers have a bit of a freedom on naming conventions on variables - you want to access a member of the structure, you know it is called "Memory ID" - you have no idea whether it is actually spelt m_memoryId, m_MemoryID, memoryID, MemoryID, all of which are used in the (large) code base.
The thing is though, there is no way of correcting these problems - it is not really possible to go back and re-write code based on the new coding standards, only new things that are created can really be expected to adhear to the coding standard.
If you are dealing with a large legacy code base (as I am now) there is not much hope for change, sadly. The developers will resist changing from their own style of coding as that is what they are most comfortable with.
We had to maintain a big repository of C and C++ code that was cross-platform; that meant that you opened the same file with visual studio and it looked ok, changed a like and when you opened it under solaris the indentation got all wrong because VS inserted tabs instead of spaces.
One of our rules was to set all editors to put 4 spaces for tab length and never use tabs.
Make sure naming conventions are allways followed. The best way to do this is to have an approver/reviewer of all changes (we had senior developers do that).
If using hungarian notation use the Apps Hungarian notation instead of the Systems notation. The reason for this is that while systems documents code functionality Apps documents code purpose. And make sure to have your coding conventions well documented and used consistently.
Make sure to fix changes where code is wrong and where feasible, don't use work-arounds. When using workarounds the project becomes un-maintainable and developers get to hate it. Also, never leave in code blocks that never get executed; We have an old project around here that is full of code like:
if(0)
do_something
else
do_something
It's a nightmare to maintain: you have to go through lots of useless garbage because some nameless programmer in the past was affraid of deleting the wrong code.
Make a practice of enforcing the rules: i've seen an office where the people breaking the build had to buy the team some snacks the next day :).
Forbid spagetti code constructs (like goto) and enforce consistency of look and feel (for example we had all if statements being followed by braces even when there was a single statement under it, and all 'case's in a switch had to have a break statement).
Make sure every change is well documented and as speciffically as possible; create a standard for documenting changes in your version control system that should describe the purpose of the change and the contents of the change; For example:
Purpose: fix defect ID12345
Description: Added new function int Foo(int); centralized ID length to local constant ID_LENGTH;
Make sure every change is clean: If you diff two revisions of the same file with any file diffs utility you should be able to see only the semantically different code; Like this it's easy to follow when the code causing you problems was added and for what purpose. This is a dream come true when maintaining code: then you can see what defect/enhancement it was introduced for and you can follow that by ID to some external documentation.
Enforce refactoring: If a change requires the same two lines of code used elsewhere add a new function for them.
Tie two birds together: although they have four wings, they cannot fly. (The blind man)
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?
A lot of time you try to figure out what the variable is supposed to deal with:
For example;
int d=0;
means nothing but:
int gross_sales_cents=0;
can help you to understand its purpose and avoid any useless comment.
Use heavily javadoc and the like.
Object should have common method's name too.
For example, when you have to stop a runnable object, I've seen to many stupid stuff like object.stop_whatever() instead of a simple object.stop(). So you don't have to think about the correct method you have to use.
Olivier
1. Realize from the beginning that standards have to change regularly in order to fit the needs.
2. Allow people to decide for themselves what is the best way to code. Define a small set of minimum requirements, but keep it simple and easily achievable. Comments are good - but it is better to take the time to write proper code:
a. Proper code is well indented.
b. Proper code is simple - this means small functions, no macros and short symbol names.
c. Proper code is well abstracted: this is often the most difficult part of coding. Abstraction means that the code solves a whole class of problems rather than just one. Well abstracted means that it is not taken too far; there has to be a balance.
d. Proper code is easy to maintain.
3. Provide the proper tools - that is: tools, not toys. Some people will want an IDE like Visual C++, others prefer vi and make. Make sure the entire production system and the standards allow for this. For version control, use something that has both a CLI and a GUI etc etc.
Can I asked why you called your counter "counter"?
If your code read
processedMessageCounter++;
in the first place, then the code itself would tell you what it was doing. That way there's no way you can update the code and forget to update the comments, because the code itself _is_ the comments...
My Journal
Use named constants so we can understand what you are doing without a comment.
If you have a lot of constants that are related, encapsulate them statically in a class (if you are using an object oriented language) or in an include file.
For every method, function, or procedure make a comment header describing what it does and what the parameters and return values should be.
Keep line length shorter than 80 characters so human beings can read it without scrolling left and right.
Use white space within the line to improve readability.
Match braces vertically like this when indenting:
{
{
}
}
so that you can match braces easily with a straight edge (even though your editor can help, you might need to do this on a printout.)
Keep code blocks less than 1 page in size.
While I love unit tests etc, I think the above are the most critical parts. I also like setting up a Wiki and logging what people actually do when they do repeated tasks. These are second to the above, though.
Eivind.
Doubting the existence of evolution is like doubting the existence of China: It just shows that you're uninformed.
Better tell them to read http://wyoguide.sf.net/guidelines/coding.html or even better read http://wyoguide.sourceforge.net/guidelines/content .html.
O. Wyss
Just pay hommage (And large amounts of dough) to Watts Humphreys and SEI and use PSP/TSP. :)
Then watch how fast your projects go nowhere!
That rathole is a luxury you cannot afford yet. "Coding standards" are something that it's hard to enforce without a relatively uniform environment in the first place, and lots of things will get in the way of programmers adhering to these.
So, your principle goals should be to create uniformity in the development and deployment environments. That means build engineering and software layout, automation, etc. It doesn't necessarily mean mandating a particular IDE or toolset (although that can help) - it _does_ mean getting your infrastructure in place so that a programmer can shift to a project, get hold of the code, build and deploy to a test environment (their workstation or a testing box), look at the check-in history, look at the bug and feature lists, and so on. And they should be able to produce software that's laid out in a way that "just another project" can be deployed much like any other, wherever possible.
If you manage that, then worry about the coding standards!
As to this: a decent set of stock tools will help getting a programmer up to speed far better than coding practices which might not be adhered to. So, make it easy to test and check in code that works. Make it easy to run tests. Find a decent code comprehension tool and give your developers training with it. Find the most popular IDE and automate project layout and deployment in that IDE. Ensure that programmers can ask "what broke?", "what changed?" and fire up a debugger against different versions with minimal hassle. Keep your sysadmins happy, and ensure that these processes are scriptable.
Above all, involve the developers. Consult! Find out what tools they use, what they're lacking. Organise a regular informal technical get-together where people can show off tools; it's the best way of developing a consistent practice, and "consistency" is a key factor in local "best practice". Find your champions. Finally, don't be afraid to invest in developer training with the new tools.
Always measure the areas that your are about to address by some simple yardsticks: estimate the effort, the cost, the benefit, the likely takeup, the risks. Is it worth it?
Surprisingly, Wikipedia talks about the difference between Systems Hungarian and Apps Hungarian... each one being named after the division of Microsoft that primarily used it.
The difference between them boiled down to a misunderstanding by the Systems team as to what the author of Hungarian Notation actually meant.
An issue that sometimes gets skipped is brace style. Some people prefer the "one true brace" method, where things look like this (pretend the code is indented properly):
and some people prefer opening braces on the same line, like this:Having one style for braces makes it easier to follow.GLaDOS for President 2016! "Well here we are again. It's always such a pleasure." -- GLaDOS, 2011
So your company is developing software for 35 years now. They must be doing it right.
Dont't ruin it just to save a couple of hours here and there, and to appease some bean counters with fancy reports about hours saved, and projects bungled in the process. Find out how they have worked in the past, and maybe try to improve slightly once you absolutely understand it, but do not just put down standards. It will only hurt.
Don't change a working system.
ps. Yes, we do this here: this isn't theoretical. Yes, decent build engineering takes time and talent. Programmer management takes other, political skills. It's hard work but absolutely worth it for our environment.
Has anyone mentioned modelling yet? If a system has been planned and designed with UML or a similar modelling tool before coding it makes it much easier for someone to jump in and start work on a particular module. Reading code is painful. The more you can explain how your code works with simple diagrams and pseudoc-code the easier it will be for people to relate the actual code to the purpose it is intended for.
It's not all about getting the developers to use the same code formatting and indenting. Often it's in the simple things you can think up to solve spesific problems.
Good things to consider could be small, easy and quick things, like creating a small text document detailing the structure of the source directories.
And if you're not already doing it, by all means use a source revision control system. Not only do you get the revision controls, the advantage of more easily being able to have multiple developers working on the same source set, but you get the advantage of making it easier to keep an eye on what's going on with a project.
Both of these things will lead to quicker returns, for a lot less work, than changing the developers coding habits.
Terje Elde
Wimp.
9/11 Eyewitnesses to Explosive WTC Demolition 1 of 2
I just love Linus's Style guide where he says that the functions should be small with large tabs (8 char),
and the function should have less than 7 variables.
I think this is the holy grail. All these three are so intermingled that if you follow all these you will
realize how much it improves your code.
If you use large tabs you cannot do too many nestings forcing you to break the function. If you have too
many variables your function must be very complex or else you must use a structure. This also foces you
to break up a function. This forces you to define new functions.
If you have few local variables then you don't need descriptive names for local variables.
I have found this set of advice to be the most important coding style requirement.
We don't have any standards at my company, but we're small. We've tried all sorts of documentation systems such as wikis, READMEs, CVS comments, bug tracker and nothing has worked as well as blogging about it. It's not really a standard (answer to your question) but if you skip the strict rules of standards and just ask production people to blog about it, then you'll easily build up a wealth of information that is sort- and searchable to help anybody get involved in a project. For bug tracking we use issuetrackerproduct which is great too for making sure the communication between various parts (client and production team) happens in a consistent standardised manner.
home http://www.peterbe.com/
Aaah, what a beauty. The real questions that should concern this are more in lines of the following:
:)
- 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!
Here's what I like:
:) The team lead can then decide on a policy, e.g. "there will be no discussion on this point, everybody can do it how he/she pleases", "everybody will do it *this* way", something like that.
1. As for code comments, rely on "Use The Source, Luke" as much as possible. Force people to write readable code, so that this actually works. Logical variable names, no unnamed magic numbers, no cryptic constructs. No loop bodies consisting of only a semicolon, e.g. "for(...;...;...);". Comment only on the things that aren't obvious. Any extraneous comments are bound to be outdated by the code, and will confuse more than help.
2. Write down the design in comments in the source files, as a readable piece of prose containing all of the design considerations and decisions. Design of an algorithm goes in the function body, design of a class goes above the class definition. Programmers are aware that designs are often outdated, so when they read them this is not a problem. Having the design in the code has the advantage that you can actually *find* the design for the code you're looking at. There have been too many times where I've been looking for a design document that was "somewhere on the network". Or that I've been looking at a design document on the network that had been superseded three years ago. Having your design under source control fixes that.
3. Build at least every day, or even better: continuously.
4. Automated testing. Run automated tests on every build, if possible.
5. Code reviews. Sit together once a week with one other team member who then reviews all your code for the last week (all of it, based on reports from source control). That shouldn't cost more than an hour or something, it's a good way of keeping the knowledge going around, it works as a very good "desensitization therapy" for those programmers who can't handle criticism, it increases communication within the team because people get to understand each other's work better. The only downside is that there is usually a lot of opposition against this -- I know a *lot* of programmers who don't like to have their code criticized. And there's a very clear risk that people will get into endless discussions about very small details of style ("should there be a space between the if and the parenthesis?") or other inconsequential things. To prevent these issues hogging the review, there should be a formal "escalation procedure", where the issue is passed on to an arbiter (team lead) with arguments from both parties. If a disucssion on an issue seems to go in this direction, either party *or* somebody else in the room whom the discussion irritates the hell out of should be able to cut off the discussion and "escalate" it.
Note that I'm currently working in an environment where we have (1) to (4) implemented. I'd like to have (5), because there is too many crap code being committed, and there's no check on that. It's been all too often that we've had to replace the *entire* work of a team member after he/she left, because the team member had been able to commit crap code without check during all the time (s)he was on the team.
I would expect developers to spend less than 20% of the time coding because the should be busy doing:
Requirement Analysis.
Design.
Requriment reviews.
Design reviews.
Test Plans.
Testing.
Requirment-Design-Code-Bug tracking.
Thus, when the time come to code, if you do all of the above right, the code part is
not some obscure obfuscation that later on has to be reverse engineered..right?
- these are not the droids you are looking for -
Sometimes I begin to think all we do is practice writing code. We seem to not follow standards and we tend to repeat a lot of the same functionality over and over again with different code.
Of course, we don't practice writing documentation ever, so that might be the problem.
Except for me.... the non-programmer who's supposed to somehow reverse-engineer documentation out of this code. Yeah.
Linux - because it doesn't leave that Steve Ballmer aftertaste.
The most important thing is to get everyone coding the same way. If you've had no structure in the past, this is extremely hard to do. No one will want to listen to you, and each programmer will feel their creative freedom has been compromised. If you can get people writing code in almost identical styles, then you'll find cooperation between them will improve greatly, easily justifying the effort. In my experience, most often these efforts fail, and you'll be the guy they blame, while also saying how dumb the whole idea was to start with.
So, the easy thing that most people do is practically worthless: force everyone to use a complicated header over each piece of code that describes the author, purpose, I/Os, etc. This will make your bosses happy without seriously changing anybodies coding style. It's the wimp approach and does nothing to improve productivity.
Or, you could take the hard road: force everyone to use a common coding style. For example, if you're a C++ shop, pick a set of templates (like STL, or others) and force everyone to use them. Pick a code format and make everyone use it. Do you use case or _'s to separate words in identifiers? Pick one and enforce it. It's so much easier working with code that your fingers know how to type.
My advice is to keep the 'official' coding style simple. Many of your company's programmers will hurt their brains trying to understand aspect oriented coding. You'll be lucky if they can use abstract base classes properly. Remember that the less than average programmer will likely be in charge of your code some day. Target the coding style to help him succeed. The geniuses in your group could succeed in FORTRAN, so don't worry about them.
As for details... there are so many coding styles, and each takes a book just to describe it. We document our data structures with entity relationship diagrams and have separate internal and external header files for modules. We all use the same collection classes. We use access functions to access fields of objects, rather than accessing them directly. We use an old CASE tool that automates memory management and generates virtual recursive desctructors for us. Every funtion has a comment, and we keep functions small. We improve quality with data structure self-tests, and an automated run of many data sets through our system each night. We use SVN. We make everyone code in EXACTLY the same way. We use capitals in identifiers, keep braces on the same line as the 'if', indent by 4 spaces, and have 50 other rules for how code should look. Sometimes we can't remember who wrote what code, and there's no way to know!
Beer is proof that God loves us, and wants us to be happy.
Part of the problem is because we came from different backgrounds (Some delhi people...
Was that a typo (Delphi) ?
Or a Freudian slip? (I believe it's called New Delhi now, btw)
I'm notoriously bad at writing very long variable names and such while debugging. counter++?
for ( ii = 0; ii < MAX; ++ii )
{
(code here)
}
and debug it through until it work and *then* I do a search & replace on the function for ii with a long variable name, e.g. "messagesProcessed". Otherwise I end up being majorly pissed at the places where I wrote "messagseProcessed" instead. That way it seems very reasonable to the next guy, wihtout going overboard on typing.
for ( messagesProcessed = 0; messagesProcessed < MAX; ++messagesProcessed )
{
(code here)
}
Live today, because you never know what tomorrow brings
I make sure that every new technical hire to our company reads this book by Kerninghan and Pike. Then, I give them a copy of our coding standards which really just outline the syntatic sugar. If the person was bright enough to get hired, they are more than capable of understanding and applying the concepts presented to them through these two sources.
I suggest a recommended standard from the top, but it is important to give each team the flexibility to reject parts of the standard or the include things that are not part of the standard.
The GNU Coding Standards were written by Richard Stallman and other GNU Project volunteers. Their purpose is to make the GNU system clean, consistent, and easy to install. This document can also be read as a guide to writing portable, robust and reliable programs. It focuses on programs written in C, but many of the rules and principles are useful even if you write in another programming language. The rules often state reasons for writing in a certain way. Best, url80
Best,
url80, The Bounty Network
Read this thoroughly, and try to do the opposite.
...I know I've heard this one before. I think it starts with "You find three letters from the previous manager. The first one says 'open me now'....."
Do not fold, spindle or mutilate.
if (iCurKey == iLastEntry) pRec->SetKeyTag(szUsername);
:)
Notice how my deviation of hungarian notation never uses more than 2 characters, and I treat the record like a class (Use strncpy if you prefer). Hungarian notation has made our company code easier to manage for me because I don't have to scroll up to determine what types the variables are. However, H.N. IS NO SUBSTITUTE FOR CODE COMMENTS. H.N. isn't supposed to tell you how the gears turn; it's supposed to tell you whether you're using phillips head screws or flat head screws.
I also don't normally read code out loud when I'm doing maintenance; I think it would upset my co-workers
Our companies coding standards can be described in one word - outsourcing.
I think it's a good idea to limit the number of coding languages. If everyone knows Perl, and one new programmer wants to use Ruby for a few scripts, don't let them. Who is going to maintain the Ruby script?
Of course, if you decide that from now on, Ruby will be your main scripting language, then it would be fine to start with a few random scripts here and there. Or if you decide to try Ruby on one isolated project and see how it goes, that's OK too.
The decisions about which languages to use should be made on what's good for the business, not what's good for the programmer's resume.
disassembly can lie if the operating environment or hardware is bugged (either error or with malicious code)
the only truely trustworthy code is code hand compiled to run on a tube CPU which you have personally blown the glass and formed every tube.
Snowden and Manning are heroes.
Most people who advance coding standards talk about how braces should be put and whether there should be used braces in one-line if's, maybe they even mention the horrible and feared Hungarian Notation. I have yet to find out how any of this *actually* helps understanding code.
Readable code is a prerequisite for understandable code, education is a prerequisite for understanding.
Coding-standards is trying to apply a method of syntax to an education-problem, it's not gonna work. Don't think that coding-standards will give you readability, much less understanding.
My advice is to get a few people with experience, solid, broad knowledge of the language and a pragmatic attitude to sit down and pair-program with the people who write hard-to-understand code and those who have a hard time understanding code that should have been easy to understand.
Let people present idioms, discuss patterns and create a place where "readability" is a code-quality and a goal. (BTW: Don't fall into the "everthing is a pattern"-trap) This is not a coding standard, it's an education of "this-way-works-well-for-this-and-that".
Promote knowledge of the language standard-library, instead of duplicating it yourself. Learn to shun "wrappers". Use the language-features for what they were meant to do, not for insert-really-cunning-hack-here. Model things as they are, instead of cutting coreners or adding complexity.
Check out c2.com http://c2.com/cgi/wiki?WelcomeVisitors it's really a place worth knowing. Read the dialogs, they may not all be truly insightfull but they provide you with excellent examples of what people think about in development and why it's not that easy to do-the-right-thing.
One specific thing i've found is that most people write code by copying (atleast a skeleton) from somewhere else. Accept this, and to give them something *proper* to copy from, short, complete programs -- taken from real situations, Not crappy code-project articles where people try to show off how complicated a technique they can master.
SLOGEN [ http://ungdomshus.nu : Sebastian cover music]
I once came across a ~1400 line function of complex maths transformations with one comment /* increment i */
;)
i++
What's i? and more importantly why increment it?
Well if you're using the term complex maths in the same way I do, I have no idea why you'd want to increment the square root of negative 1.
Mature projects either have all of the above, are in deep trouble or some combination of the above ;-)
Cheers,
Toby Haynes
Anything I post is strictly my own thoughts and doesn't necessarily have anything to do with the opinions of IBM.
If you want to turn out a professional product in a professional manner, buy the following pubs and follow them:
- IEEE/EIA 12207.2, Software Life Cycle Processes - Implementation Considerations, from www.ansi.org
- The Software Project Manager's Handbook, published by the IEEE Computer Society
- Code Complete, Second Edition, by Steve McConnell
Of these, the Software Project Manager's Handbook is the most important. It'll save you a lot of heartburn. I used it on my first two development projects and they were both successful, which doesn't happen very often in this business.
If you're doing software maintenance, Tom Pigoski's Practical Software Maintenance is the best book available.
Go to the Software Engineering Institute's CMMI web site and read what they have on Software CMMI Level 2. Implement as many of the procedures as you can.
Go to the Systems and Software Consortium's web site, www.software.org, and see if your company is a member. If it is, get an account! There's an unbelievable amount of free best practices material available.
Good Luck,
Bob Mosher
Principal Engineer
Computer Sciences Corporation
Comments often get in the way of code readability. I often get annoyed looking at comments like these:
// initialize index to zero
// if string is null return an error
// get the next index
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.
In the unlikely event that any of your projects involve Perl (even if just peripherally as build tool scripts and whatnot), I'd highly recommend setting your company's Perl coding standards to just be "follow the Perl Best Practices book". It just came out this summer, and it's pretty much all you need for a fairly rigorous and insightful set of coding practices for Perl.
http://search.barnesandnoble.com/booksearch/isbnI
11*43+456^2
After reading a few posts on this article, I've confirmed what I've believed all along.
There are A LOT of bad programmers out there.
I think the best practice you can champion is the use of Test Driven Development. It will lead to high quality, simple design. In addition it will allow your new developers to quickly figure out what the code is designed to do and when they start to change the code they will have the confidence of a full suite of unit tests to protect them. Maintenance work should always be done with TDD. For instance, fixing a defect:
You are essentially asking for a cradle-to-grave process, of which coding standards and software peer reviews are only small pieces. Everyone here misses the point, because, of course, they're developers, and typically don't see things from the big picture perspective.
Make sure that you writeup your process in a software development plan beforehand (SEI Level 4 is all about having a well-documented, repeatable process). This document should describe the process you will use for software requirements derivation from higher-level system requirements, software architecture and design, as well as risk abatement, artifact reviews, code reuse, configuration management, implementation, unit and integration testing, and eventual deployment. Sound like a bitch of a document? Yep, but going in without a plan absolutely increases your chance for abject failure. Write it well and make it sensible and rational, because it will be your bible.
Once you have it written and blessed by management that THIS is "THE PROCESS" (i.e. it's now policy), use it to your defense. Getting new or updated requirements rammed down your throat? Point to your process for software requirements updates and point to your section on how you will deal with this. If you were smart enough to put in "doing this will cause x schedule slip and will cost booku $$$ and require N new personnel" ahead of time (this is now a policy doc, mind you), guess they'll think twice before arbitrarily tossing in new requirements and compressing schedule and all the other evil things that upper management does to try and throttle the creative process.
If your company is at all mindful of ethics and maintaining integrity, they won't take policy violation lightly.
Me: "Ok." [tap tap tap
[six days pass]
Me: "Alright, that's done."
IT Manager: "Wait, this isn't what I wanted."
Me: "You asked me for xxx."
IT Manager: "Well, I guess what I really wanted was yyy."
Me: "Ok. I'll do yyy, if you're really sure that's what you want."
IT Manager: "Yeah do that. You'll still deliver that tomorrow right?"
Me: "No, I spent all week working on code that does xxx that I have to throw away now. I will need another week to write yyy."
IT Manager: "But then I'll look bad!"
Aaaah coding practice.
perl -e "eval pack(q{H*},join q{},qw{70 72696e74207061636b28717b482a7d2c717b343 637323635363534323533343430617d293b})"
They had a few guidelines about writing variable names that make sense, and being consistent with your camel-casing and whatnot, but their biggest and first guideline was this:
Never waste time rewriting someone else's code just because you don't like where they put their braces.
Honestly, a consistent way of naming public interfaces is very helpful, but knowing whether the call is Size() or size() doesn't help you when it's actually called Length(). You're going to have to look at it anyway. But time spent making someone else's code comply to your standard, or to any standard, is time spent not actually fixing what's broken in it.
Of course, everyone in this small company actually wrote decently readable code naturally, or they wouldn't have been hired. Not sure how consistent that is with other workplaces.
Please format your code so it is easy to read! I've worked with people who edit code in notepad and never indent or use capitalization consistantly. I spend half my time trying to identify big loop begins/ends and if-then blocks when working with other people's code.
It is by the juice of the coffee bean that thoughts acquire speed, the teeth acquire stains. The stains become a warning
Im glad comments lie and code does not was posted for all to see. For it is the truth. Comments are not needed IMO at all. If your a good coder you do not need comments you can read code as if you are reading english
I will not disclose a 0 day again I will not disclose a 0 day again I will not disclose a 0 day again I will not disc
> (...) my company has run for the past 35+ years with no form
> of central IT department (...)
I bet you must be working for Microsoft.
echo "getuid(){return 0;}" > e.c; gcc -shared -o e.so e.c; LD_PRELOAD=./e.so sh
i.e. where I work, it seems like they were written by somebody who isn't familiar with writing software (or they're not very good at it) and it values code readability over efficiency. Just be sure in creating your standards that you review them with other seasoned developers for input and that you balance the readability things with practical needs (i.e. here, your loop vars can't be called "i," they need to be "index"...wtf?!). Bad coding standards simply result in frustration and developers who will willfully not follow them and then have to fix things later...which will only cost you more time and effort.
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.
This sig has absolutely no significance and serves only to take up screen space and waste the time of the reader.
And the code always tells you why something was done... oh wait... no it doesn't.
1. Set up a development process for projects that will be improved iteratively.
2. Start your next project.
Step 1 is a lot harder than it would appear. Check out Steve McConnell's websites and books http://www.stevemcconnell.com./
but what if aliens replaced your glass tubes with dynamite when you weren't looking?? it's better to just not code at all, and spend your life hiding in a cave armed with a pointy stick.
You don't work for Microsoft, do you?
Yes, it's short to write i in a simple loop. And in a very simple loop, it's ok. But when you then nest another loop and use j, it drives me crazy. Why not use records as the outer loop var and fields as the inner loop var, or something like that? I always use variable names that try to show what the logical purpose of that variable is.
Long live code generators!
But if you really must, just run "indent" as code is checked into the SCM.
Please make sure you tell anyone that tries to return ints that have meaning that you'll kill them unless they use enums. There's nothing worse than having to try to sort through a ton of code to determine what '2' means in a given context. Additionally, tell those that use spaces instead of tabs to stop doing so immediately. I'm assuming you're using a dev environment that supports setting tab widths for coding. I have a coworker who only uses 1-space tabs. The hardest part is dealing with how awful his code looks when you bring it over to a 4-space tab environment to find out that sometimes he used a tab for an indent, and sometimes he just hit the spacebar. Force code reviews. They're very useful in the long run since more people will have familiarity with the code. Code reviews aren't needed for small tasks obviously, but for large tasks, they can be invaluable for finding those hidden little gotchas. Just a few things.
I don't know if this is a joke, prophecy or an honest testimony. The only difference is that we keep code on one big NFS volume and nearly everyone uses vi, so providing they don't open file ../foo, or bar/foo, the swap file kinda acts as a file lock. Creepy. *shiver* Oh, also, we don't add informative comments here.
I'm quite surprised that I haven't seen it mentioned in any of the posts yet (maybed I missed it), but I think it's important to use the Software Development Life Cycle (SDLC) when designing, implementing and maintaining projects. Not only does it improve the quality of your project, but it also helps out others who will be working with the project in the future, by providing them with documentation. There's plenty of SDLC documentation online.
Which is it?
Almost no company I've ever worked for has had 'em, and the few that did either didn't document those standards, or didn't follow through ("I glanced at your code. Looks ok, that's your peer review.")
What would *I* put in?
Standards:
1) peer review includes full review with comments. "Looks ok" doesn't qualify.
2) institute a central index of functions/programs written in-house or F/OSS that have been brought in and approved, and developers are to use them whereever possible.
3) follow all the "good coding" standards that have been taught in school the last 25 years - no spaghetti code, short functions that do *one* thing, and do it well (encapsulation), etc, etc, etc.
4) "and in chief place": written specs, signed by management and developer. "But I wanted yyy!" "Sorry, I did what you signed off on, and what it says *here*. You want yyy, it'll take almost the same amount of time it took me to do xxx." "here, sign here...."
mark
Take the writing the comments first a step further and write the tests first too. Test-first development is not just for the agilists in the house, many projects are realizing the benefits of doing it. It is a big paradigm shift for most developers but once you make the change, you'll be surprised how natural it becomes. It gives you all the benefits mentioned by Webmoth (getting it clear in your mind, knowing your inputs and outputs, having an outline to follow) and extends that to your whole API. You start with all your tests, which should all be failing because there is no code yet, and check your code in once you're passing your tests 100%.
The September issues of both IEEE Computer and IEEE Spectrum have articles about this and other software development practices I encourage you to check out, such as agile development.
Even if you don't choose to take a test-first approach, don't do like so many projects do and put testing to the very end either. Testing should happen throughout your project. You cannot test in quality later. Software maintenance accounts for more than 90% of the total costs for a project. Do something to help your company to reduce that amount by making testing a routine part of development from the beginning.
Everything is "Bob".
Seriously... I'm not joking. It was only 7 years ago. In fact, I think it was even worse: we didn't have a "single samba-shared volume"; I had to shout "WHO HAS THE LATEST VERSION OF FILE X AND WHERE CAN I GET A COPY?"
In general, you will want to do this in such a way that most of the changes (at least initially) are for the purpose of making sure things are consistent. Some examples...
First, take a vote on how to handle multi-word variable names (with_underscores, camelCase, or whatever), and officially adopt whichever one gets the most votes as the official way that you name variables at your organization. It doesn't matter which one you pick, as long as you standardize on one specific convention for this. Also be sure to specify whether Hungarian Notation is to be used or not. (All else being equal I prefer not, but if most of your code uses it, it'll be easier to standardise on that.)
Second, you want to standardize on where the comments go that describe the inputs and outputs of each subroutine. Before the function header? Right after it? You can stick with however most of your code currently handles this (assuming most of your code _has_ such comments), but designate one way and make it official. If you currently have a mishmash, take a vote or something, but standardize it. Word the document that describes this standard in a way that does not allow for said comments to be omitted.
Third, if you don't already have a version control system of some kind, set one up, and make sure that it prompts for a changelog comment on every checkin, automatically filling in a list of the touched files. Now, make sure that the supplied comment is automatically appended to the changelog. (Don't take this for granted; not all version control systems that prompt for a changelog comment will necessarily add it to the changelog. Make sure yours does.) Make it policy that the comment has to make note of the reason for the changes. (The reason can be brief, like "added sanity check for improved robustness", but require a reason, and it should be more specific than "bug fix". If you have bug-tracking software, a reason like "bug 17043" is good enough.)
These are the sorts of things you want to start with. Obviously you also want some general wording about how clarity is to be preferred over other considerations, optimization only to be done when profiling has targetted a specific block of code and then always commented, and so on and so forth.
Cut that out, or I will ship you to Norilsk in a box.
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.
Successful Strategies for Commenting Code By Ryan Campbell
The Fine Art of Commenting by Bernhard Spuida
How To Write Unmaintainable Code
In my first job, years ago, I learned that developers will not usually keep any external documentation (e.g. some document-only file other than foo.c, whether troff, LaTeX, or MS-Word) current, but those same developers will usually keep internal documentation (e.g. documentation embedded inside foo.c or foo.cc) current. Back in those days, we were using a DEC VAX 11/750 and the embedded documentation used troff markup, but similar and more modern tools are available today for a wide range of platforms.
So folks should consider using open-source tools like HeaderDoc or Doxygen or (in the case of Java) JavaDoc to embed the software documentation inside the actual source files.
Mind, this is not a substitute for good coding or good documentation or good software enginering practices, rather this is a tool to help people write good code, have good documentation, and follow good software engineering practices. :-)
"I once came across a ~1400 line function"
This is so fucking wrong and wicked the programmer who did it should go straight to hell. I'm sure there's no functional coesion in there: most likely there are many disparate tasks that should be each in its own function and called from there. I'm sure there is a lot of cut-n-paste in there that should be each in its own function and called from there.
I'm sure you can guess where i'm willing to get to... more important than hungarian notation, comments or documentation in PDF format is abiding for these 2 simple rules: KISS -- keep it simple, stupid -- and DRY -- don't repeat yourself. Once you do it, coding and reading code is a lot easier.
So, my advice:
* Give meaningful names to important, global, business rules variables ( local variables like i or c are ok, since they are mostly irrelevant ) or functions/methods/procedures/subroutines
* Write short, highly coesive functions/methods/procedures/subroutines
* Stop the cut-n-paste madness! If you do it a lot, it's obvious the copied code if begging to be parametrized and be given a name. Programmers altering your original code will be thankful
* Write modular code, not a plain, huge, stupid monolithic wall of letters. Even in languages with no namespace support ( C/PHP etc ) a good naming convention for functions of a certain module/header can do wonders...
* and please: meaningful names don't mean phrase-like names like thisLocalVariableIsCool. Conciseness go a long way towards good readability...
I don't feel like it...
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!
I18N == Intergalacticization
The one unmentioned coding standard that needs to appear:
Always use constants as the first element in an if expression.
Thus, never write
if (x == 0)
instead write
if (0 == x)
Doing this consistently will always catch the = versus == error. This may only catch one in a hundred errors, but it is the most easily missed and hardest to find error.
While you might find this funny, it's not really a joke. I work multiple sites (some where the machines are a pain to hike back and forth to) and I definately notice that having my daily requirement of coffee or green tea both gives the heat (it's cold around here), energy fluid and possibly caffeine that sees me through the day. Otherwise, coding while dehydrated/tired causes a performance loss, and the hikes up to the machine tend to cut into my concentration.
Alternately, having a local coffee machine might give you an indication of who is regularly buzzing on the edge of a razor blade (living on caffeine)...
Of course, this is a workplace environment practice, but it definately affects my ability as well as that of some others.
http://subversion.tigris.org/
In July 1988 a colleague proposed a hefty set of programming style conventions for C. I objected to almost everything. He challenged me to propose conventions I could happily follow. I accepted the challenge, and came up with eight "Rules":
Coding Style Complete in Eight Rules
Clarity Rule
Programs must be clear and easy to read.
Wherever possible, clarity springs from the code itself;
in other cases, including marginal cases, clarity requires supporting comments.
Exceptions: None.
Comment Rule
Comments must provide (or reference) whatever information
a competent programmer needs to grasp quickly the code's intent and method.
Exceptions: None.
One Page Statement Rule
Every statement (including compound statements) must fit on a single page.
Exceptions: None.
One Page Function Rule
Everyfunction definition must fit on a single page.
Exceptions:
1. Function header may occupy more than one page in furtherance of the Comment Rule.
2. Other exceptions only if in furtherance of the Clarity Rule.
Indentation Rule
Statements at the same grain of resolution must have the same degree of indentation.
Exception: Two or more consecutive statements may occupy a single line,
if in furtherance of the Clarity Rule.
Compund Statement Rule
When a compund statement occupies more than one text line, all
subordinate statements must be indented with respect to their parent statement.
Exceptions: None.
Long Statement Rule
When a statement extends over more than one text line, each continuation line must be indented w.r.t. the first line, and line breaks must partition the statement harmoniously.
Exceptions: Permitted only in furtherance of the Clarity Rule.
Example: If the second line of a compound C or C++ statement begins with one of the brace characters ("{") enclosing the subordinate statements, then this line may have the same indentation as the first line if you think clarity is served thereby.
Interchange Conventions
Certain conventions facilitate sharing code both on screen and on paper:
1. Both ends of lines are visible under normal conditions. (80 character max suggested.)
2. A page must fit on a standard printer page. (60 lines max suggested)
3. Pages are delimited by form feeds.
4. Tab stops should be uniform. (3 spaces per tab is suggested.)
Exceptions: None.
Alright. Since your company has been able to run for the past 35+ years with no form of central IT department, you should not suddenly start to dictate standards for developers to abide by. At least things work now, so your primary objective should be to not break things.
Instead you should try to understand what the different groups are doing, and see how you can improve their processes incrementally. Some of the development teams might have very efficient practices in place. Some might have less efficient practices. Make them communicate and learn from each other.
One of my tasks is to set up standards in how projects will be implemented and produced.
Since your company has been doing this for 35+ years, no doubt your company is using the waterfall model. Your first task is to educate the medium and higher management on modern development practices. Your developers already know that stuff, but can't use it.
A company with 35+ years of development experience have plenty of talented people. You do not know what's best for everybody. Your job is to find out what works, and what doesn't work within the company, and preach the benefits of what works.
By assuming that "you know what's best", you ignore 35+ years of experience of a lot of talented people. Before you can "set up standards", you need to find a reasonable set of standards to implement.
There exists plenty of literature on how things should work in theory, but the fact is that within a given corporate environment (such as yours), those methodologies would barely work even on paper. Without a proven track record within the company, there is no way you can force people to do it your way! At best, you can encourage people to do it in a better way, but you can't force people to do it "your" way.
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.
Why on earth are you more concerned about that? While a "coding standard" can give some cosmetic feeling of order, you are in fact at a company with 35+ years of software archaeology to administer. There are more important issues right now than deciding how people should indent their code...
What do people like/dislike about how projects run in the company? How can it be improved? Which projects exists, and remains active? Should some of them be tossed? Can we toss some more old code? Can we get people to communicate better? Perhaps with a shared version control system? What are the needs of the developers with regard to IT services? Which corporate procedures creates the most hassles for developers? Etc...
A "coding standard" is a document that dictates developers to write their code in a certain way. It can either be ignored or followed. If it's ignored, it's harmless, but of no benefit. If it's followed, it can be a recipe for disaster. A bad coding standard is infinitely much worse than no coding standard at all. It is a straightjacket that forces the programmers to work in a certain way, whether it's productive or not! If, on the other hand, it's a good coding standard, it's benefits are little more than cosmetic. It might save a few hours here and there (as you claim), but those hours might be lost in having forced developers to follow it.
Besides being of limited benefit, writing a coding standard is one of the hardest things you can do. Different things work best for different people. You can't dictate what's best for them. You need to hear their opinions, find out what works best, and try to encourage people to do it in ways that are proven to work well within the company.
I've come across some documents in this area from a few sources (of
My favorite was the entire huge module with only one comment: /* Make sure j != 2 !!!*/
No sign of a variable named j anywhere...
When I first started with my current company over 3 years ago, I was asked to put together a coding standard. I started with:
http://www.ganssle.com/fsm.htm
If doing embedded/firmware it's a great start; though it's a great start for any code work.
Here's my opinions:
1. Good comments are valuable. Comments that tell you why something was done the way it was are invaluable.
2. Use a code repository. CVS is what we use. And use the thing, check-in frequently.
3. Backups. 'nuf said.
4. Don't worry about specific code style issues (especially brackets). Just make a requirement that people follow the style already in a project (or file if you want to get that granular) as they add and modify. Be flexable, there's really much more importaint issues (like vi vs. emacs).
5. make and other automated ways are your friends. Automate as much as possible; it's too easy to forget that one silly commandline incantation you have to do to build the major product and end up having to re-release to fix something.
6. Templates. Have a project in CVS of standardized file templates. Make one for each file type you've got: header_c_template.h, header_cpp_template.h, module_c_template.c, module_template.cpp, Makefile_template, etc...
Saves time and avoids unnecessary rework. Also, new people to your organization will know what you expect in your files.
And then variables that describe what you're going to use them for? Thats probably helpful. e.g. It is no use using a variable called $no_of_donkeys to use in a tax calculation. Probably better using something like $tax_amount. Nesting is good so that people can see where ifs end and start as well as loop statements etc... See how code from Open Source software HotcakesCMS is written, it uses named variables that make sense. Downloadable from Sourceforge or below: http://www.hotcakes.co.nz/
http://www.webexperts.co.nz
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.
Whenever I hear about this sort of thing... I'm reminded of the genuine crap that's been published on this topic. I don't have any sources to cite... just an anecdote.
I was once told on a project that my code should be written such that any manager, with no programming experience could just jump in and start changing the code.
As to formatting in a coding standard ... this is usually a religious issue with developers, and in my experience, it's best to let them do what they feel they're most comfortable with. When *you* - as someone who does the same - want to look at *their* code, you run it through something like 'indent' (http://www.gnu.org/software/indent/indent.html) - i.e., so that you see it how you want it - and so do they. I'm sure it's even possible to shell apps like indent as source is checked out of your repository.
;-)
... IF - you have the source code for the non-standard functions/libraries AND IF they can be compiled by an ISO compiler AND IF they don't do anything platform specific (i.e., stuff that won't/can't port) - well, I say, if they agree with all these IF and BUTS, use them. If portability isn't an issue, well, you just use them - what's the point of not?!
...) output - so, no one can check-in their code if it fails the lint check.
You should also read some books - for example, if you're writing in C or C++ read stuff like 'Expert C Programming: Deep C Secrets' (although it's a bit old, it's still a pretty good read!) - then you'll perhaps mandate that fgets() is always used in preference to gets() etc. You'll also probably build an input file to grep or sed etc - so that you can scan source code for things like gets() - it's easy to forget to use fgets etc - esp. when such functions require extra args - that in turn, require extra time consuming keystrokes
Some folks will also say 'only use standard functions' (I'm talking mainly about C here again of course). Anyway, IMHO, that's 'potentially pants'
Lastly, you might also want a lint-ing strategy, e.g., come up with 'stuff' that's to be corrected if it appears in lint's (flint,
@peetm
Make them read The Daily WTF regularly, lest they end up on there.
Oh, and like eveyone else says: get them to read "Code Complete".
My Karma: ran over your Dogma
StrawberryFrog
When I took over the internal application development at Computerworld, I tried to do something similar. This is what I put in place for us. I'm not saying this is the only way to do it, but it works for us. The framework is key. By using a framework like CSLA http://www.lhotka.net/ The developers will always know that there will be standard method names for all CRUD operations. You will also know that more complicated "plumbing operations" like data serialization will be handled efficiently. Additionally, a framework facilitates the use of code generation techniques because things are handled in a standard manner. Hope this helps. Computerworld IT Development Process Plan This document is intended to outline the software development goals of the Information Systems Group at Computerworld. It is intended as an internal document for clarification of group purpose and is not intended to dictate development efforts in other parts of the organization. It is useful however in explaining how we intend to carry out our business and to interoperate with other development and non-development groups. Defect Tracking All Defects should be logged and stored in a defect tracking system. This will facilitate work prioritization, keep track of which features are in a new release and document decisions. We will evaluate whether IDG's TrackReccord Defect tracking system (from Compuware) is appropriate for Computerworld's use. Other alternatives include Bugzilla. Expertise Developed on a limited number of technologies We will develop primarily with Microsoft Technologies (.Net, SQL Server, Source-safe etc.). There are plentiful amounts of affordable developers, training, and code samples for the .NET development environment.
I would also like to standardize on a set of windows and web control libraries. This will allow us to deeply understand the object structure of these controls and to write code generators that speed development (see later section on code generation). Specifically, I would like to standardize on the Infragistics web and windows controls.
Limiting the number of technologies will allow us to develop deep expertise. With a small group, I think this is a cost effective approach.
Source Control
Implement this as soon as possible. We should be able to tag releases to be used during code promotion. We should also be able to script against the source control engine to facilitate code builds.
Code Promotion
All Systems should have a Development, Test, Staging and Production Area. This will allow us to properly test and isolate changes to our code as well as to test dependent software upgrades.
Object Oriented Framework
CSLA http://www.lhotka.net/ArticleIndex.aspx?area=CSLA% 20.NET
A standard framework or model will facilitate code generation and reduce maintenance labor. Goals of the framework are:
Logically organized code
Easier Maintenance
Better reuse of code
Better Team Development
Increased code clarity
Performance
Scalability
Fault-Tolerance
Security
Code Generation for standard code
"Plumbing" code should not consume great quantities of time. Stored Procedures, Objects with properties and standard CRUD (Create, Update, Delete) operations should be easily generated. This facilitates a "data driven design". .Net reflection, in conjunction with a standard format for serialization should allow us to generate grid controls based upon our generated objects. This should allow software to be assembled and coding effort to focus on the unique business rules of the application being written.
System Integration
I would like to develop with, and purchase packages that facilitate a Service Oriented Architecture based upon open XML based standards such as SOAP. This will promote code reuse across development groups and possibly across companies such as IDG, IT Careers etc. This will also facilitate the interoperation of multiple development enviro
- MemeRot $live{free} || die ""; Either is correct for Perl, I was just making light of your stated love of hungarian notation by noting that your hash variable was used in a boolean fashion ans should therefore be prefixed accordingly
It must have been something you assimilated. . . .
Back when structured programming methods were gaining popularity
we began creating our own standards covering the design phase
through coding (all in C but applicable to anything). Sandia
National Laboratories published a set of papers describing how
they do this in great detail. It is quite extensive and worth
reading. Depending upon the size of your company and teams
you may want to use all of it or scale it down.
I'd also recommend making "The Elements of Programming Style",
by Kernighan and Pauger required reading by all involved.
The processes work.
Hi ho silver
In many years of programming I have seldom found organizations that could create any kind of coding standard and then get even a few of the programmers to adhere to said standard. And, these organizations created mountains of truly awful code. So, more power to you. I wish you luck.
.h, .lib .dll) so that the entire project can be backed up by copying ONE folder and its subfolders to CD. Do a backup each time the code reaches a stable state. Data on disk is subject to instant distruction without warning. Source code control systems eat files. Keep your own copy.
I would skip over the traditional religeous wars on curly brace placement and indentation. As long as the programmer is reasonable consistant, the code can be read.
Modules and functions ought to have header comments. "Purpose:" is the most useful of all header comments. Next are descriptions of inputs and outputs. And each module ought to have the name of the author and a date. Placing header comments between the function declaration and the opening curly brace makes it clear that the header goes with this function, and saves typing in the function name as part of the header comment.
Good variable and function names go a long way toward understanding of the code. Good variable names are pronouncable to permit discussion of the program over the phone. I personally detest Hungarian notation, it obfusticates the code and preventing type clash is a chore best left to the compiler. Function names ought to be verbs, since a function is supposed to do something. Variable names should suggest the meaning of the variable. Variable names that suggest the units of measurement (Volts, Watts, etc), the axis of the variable (X, Y, roll, pitch, yaw) the source of the data (disk, network, gui, RS232 comm link) add flavor and meaning. Short variable names are a pleasure. No variable name should exceed the length of the longest word in the English language. I dislike mixed case variable names, you have to remember the capitalization as well as the spelling to type them correctly. The C convention of constants in ALL CAPS has much to recommend it.
Code ought to compile warning free, with the compiler on its pickiest setting.
The number of bugs is proportional to the number of lines of code. Anything that shortens the code makes it more robust. Rather than writing out repeatative code sequences in-line, create a function and call it repeatedly. Delete dead code. Pull common operations out of switch cases.
Avoid global variables at all costs. Likewise global typedefs, enumerated constants #defines and the like.
Don't load hexadecimal (or decimal for that matter) numbers into hardware control registers. The resulting code is unreadable. Assign meaningful names to the various control bits using #define or bit fields, so that the effect of the control register loads is obvious by reading the code.
Things should be defined once, in one place, so that when they need to be changed only one line of code need be edited.
Use the sizeof operator to prevent array over write. Use strncpy rather than strcpy for the same reason. Never use an external input to control a loop without checking said input to make sure it will not cause array over write.
Don't nest #include files.
Organize the project files (.c,
Use a source code control system. Don't allow two different programmers to check out and modify the same module at the same time. Avoid Clearcase, there are many better source code control systems. Have just ONE main branch of code under source control and insist that everyone base their "sandbox" versions of code off the main branch. Update the sandboxes at least weekly. Don't develop and test a module against an
Coding practices are generally the BANE of good programming! I've spent more hours in code reviews arguing and wasting time correcting violations of a companies rigid coding guildlines and then spending a few minutes at the end actually fixing a design or coding problem. DON'T STIFLE CREATIVITY! Therefore here is what you do: First code reviews are intended to one: find design flaws, two: Find bugs, Three: allow experienced staff to review the decisions and prevent a tactical solution from causing a strategic train wreck. If you have a standard language, then get your programming staff together and get them to agree on an automated code formatter. It is a total waste of staff time to spend 20% of their time manually conforming to a coding standard (what a productivity killer!). Second find a documentation generator (JavaDoc rules, but if your not a Java shop then there are plenty of other code specific options). All the desktop cpu's spinning around should be doing the basic grunt work and the programmers should be adding the icing to the cake. Comments should supply EXTRINSIC information period! They are there to let people know what is not already obvious from the code! Intrinsic information should be imbedded in the code itself (it doesn't become obsolete). This means good naming of global variables, avoiding magic numbers, etc. Interfaces between code components should be independly defined from the particular implementation in the program itself and ideally designed and concocted by senior staff in reviews of what needs to be communicated between components. All programs which cross communicate MUST use these interfaces period! Interfaces should be peer-to-peer in that only the information needed to facilitate the communication is defined in the interface definition. Peer specific information should be passed in opaque objects that the peers can revise at will. This allows the peers to rapidly develop without causing ripples throughout the rest of the components. Follow History: 1: Understand and comply with Structured Code concepts (all basic line code within an object should be formally structured). Any Generic directed Graph can be put into a structure and at least informally proofed. Please try to design modules with one entry - one exit! Error handling should be based on the following concept: If the predicate logic for the module is not violated then continue to the normal exit. If the predicate logic is violated then exit via an exception mechanism and cascade up until you reach a level where the predicate logic is again valid. 2: Use the new Object oriented concepts for container design. 3: Put as much of the logic in the static structure as possible so the dynamic coding pieces are small, concise navigations of the structures. 4. Each thread should work internally as if it were a stand alone serial program. Finally check out: The Elements of Programming Style (Paperback) by Brian W. Kernighan, P. J. Plauger The object of coding practices is to facilitate the efficient writing of good solid code, not imposing intentionally or unintentionally a bureaucratic nightmare. Stroking the ego of an autocrat does nothing for the company but stroking the ego of the autocrat.
And your rant about indentation for "if
Depending on the language you are using, find a large open source project that documents their coding standards and base it off of that. Gallery's Coding standards, http://codex.gallery2.org/index.php/Gallery2:Codin g_Standards comes to mind. It's VERY detailed and gives explanations on some things. Even if you don't go by all their rules, or none of them, that page at least gives you an idea on how to structure a document on coding standards, which is more important than the actual coding standards themselves. If you can take whatever you do now, document it, then any new hires you can just give them that document so they understand everything. And yes, comments are really importantant, especially in more complicated sections, and at the end put your name so you know who to ask if you have questions on that section, and of course update the byline if someone else touches it. It's one thing our company can improve on. Even me, If I do something really complicated I usually end my comments with "sorry" :)
Just how much would/could documentation of a codebase affect your fourth point about programmers not being 'interchangeable'?
-Thanks for any input.Just how much would/could documentation of a codebase affect the fourth point about programmers (not) being 'interchangeable'?
-Thanks for the input.Thank you for your generous reply.
Would you mind if I shared this, and your previous post, with the ACM chapter at my university (http://acm.uta.edu/)?
After Kernel Trap did their interview with Hans Reiser, we have been looking for good advice from experienced programmers. While we were originally looking at forming a base of questions to use in interviews, I think this sort of exchange is just as helpful.
Again, thanks for your input.