How do you tell someone they're writing bad code? [closed] - coding-style

Closed. This question is off-topic. It is not currently accepting answers.
Closed 10 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I've been working with a small group of people on a coding project for fun. It's an organized and fairly cohesive group. The people I work with all have various skill sets related to programming, but some of them use older or outright wrong methods, such as excessive global variables, poor naming conventions, and other things. While things work, the implementation is poor. What's a good way to politely ask or introduce them to use better methodology, without it coming across as questioning (or insulting) their experience and/or education?

Introduce questions to make them realise that what they are doing is wrong. For example, ask these sort of questions:
Why did you decide to make that a global variable?
Why did you give it that name?
That's interesting. I usually do mine this way because [Insert reason why you are better]
Does that way work? I usually [Insert how you would make them look silly]
I think the ideal way of going about this is subtly asking them why they code a certain way. You may find that they believe that there are benefits to other methods. Unless I knew the reason for their coding style was due to misinformation I would never judge my way as better without good reason. The best way to go about this is to just ask them why they chose that way; be sure to sound interested in their reasoning, because that is what you need to attack, not their ability.
A coding standard will definitely help, but if it were the answer to every software project then we'd all be sipping cocktails on our private islands in paradise. In reality, we're all prone to problems and software projects still have a low success rate. I think the problem would mostly stem from individual ability rather than a problem with convention, which is why I'd suggest working through the problems as a group when a problem rears its ugly head.
Most importantly, do NOT immediately assume that your way is better. In reality, it probably is, but we're dealing with another person's opinion and to them there is only one solution. Never say that your way is the better way of doing it unless you want them to see you as a smug loser.

Start doing code reviews or pair programming.
If the team won't go for those, try weekly design reviews. Each week, meet for an hour and talk about a peice of code. If people seem defensive, pick old code that no one is emotionally attached to any more, at least at the beginning.
As #JesperE: said, focus on the code, not the coder.
When you see something you think should be different, but others don't see it the same way, then start by asking questions that lead to the deficiencies, instead of pointing them out. For example:
Globals: Do you think we'll ever want to have more than one of these? Do you think we will want to control access to this?
Mutable state: Do you think we'll want to manipulate this from another thread?
I also find it helpful to focus on my limitations, which can help people relax. For example:
long functions: My brain isn't big enough to hold all of this at once. How can we make smaller pieces that I can handle?
bad names: I get confused easily enough when reading clear code; when names are misleading, there's no hope for me.
Ultimately, the goal is not for you to teach your team how to code better. It's to establish a culture of learning in your team. Where each person looks to the others for help in becoming a better programmer.

Introduce the idea of a code standard. The most important thing about a code standard is that it proposes the idea of consistency in the code base (ideally, all of the code should look like it was written by one person in one sitting) which will lead to more understandable and maintainable code.

You have to explain why your way is better.
Explain why a function is better than cutting & pasting.
Explain why an array is better than $foo1, $foo2, $foo3.
Explain why global variables are dangerous, and that local variables will make life easier.
Simply whipping out a coding standard and saying "do this" is worthless because it doesn't explain to the programmer why it's a good thing.

First, I'd be careful not to judge too quickly. It's easy to dismiss some code as bad, when there might be good reasons why it's so (eg: working with legacy code with weird conventions). But let's assume for the moment that they're really bad.
You could suggest establishing a coding standard, based on the team's input. But you really need to take their opinions into account then, not just impose your vision of what good code should be.
Another option is to bring technical books into the office (Code Complete, Effective C++, the Pragmatic Programmer...) and offer to lend it to others ("Hey, I'm finished with this, anyone would like to borrow it?")

If possible, make sure they understand that you're critizising their code, not them personally.

Suggest a better alternative in a non-confrontational way.
"Hey, I think this way will work too. What do you guys think?" [Gesture to obviously better code on your screen]

Have code reviews, and start by reviewing YOUR code.
It will put people at ease with the whole code review process because you are beginning the process by reviewing your own code instead of theirs. Starting off with your code will also give them good examples of how to do things.

They may think your style stinks too. Get the team together to discuss a consistent set of coding style guidelines. Agree to something. Whether that fits your style isn't the issue, settling on any style as long as it's consistent is what matters.

By example. Show them the right way.
Take it slow. Don't thrash them for every little mistake right off the bat, just start with things that really matter.

The code standard idea is a good one.
But consider not saying anything, especially since it is for fun, with, presumably, people you are friends with. It's just code...

There's some really good advice in Gerry Weinberg's book "The Psychology of Computer Programming" - his whole notion of "egoless programming" is all about how to help people accept criticism of their code as distinct from criticism of themselves.

Bad naming practices: Always inexcusable.
And yes, do no always assume that your way is better... It can be difficult, but objectivity must be maintained.
I've had an experience with a coder that had such horrible naming of functions, the code was worse than unreadable. The functions lied about what they did, the code was nonsensical. And they were protective/resistant to having someone else change their code. when confronted very politely, they admitted it was poorly named, but wanted to retain their ownership of the code and would go back and fix it up "at a later date."
This is in the past now, but how do you deal with a situation where they error is ACKNOWLEDGED, but then protected? This went on for a long time and I had no idea how to break through that barrier.
Global variables: I myself am not THAT fond of global variables, but I know a few otherwise excellent programmers that like them A LOT. So much so that I've come to believe they are not actually all that bad in many situations, as they allow for clarity, ease of debugging. (please don't flame/downvote me :) ) It comes down to, I've seen a lot of very good, effective, bug free code that used global variables (not put in by me!) and great deal of buggy, impossible to read/maintain/fix code that meticulously used proper patterns. Maybe there IS a place (though shrinking perhaps) for global variables? I'm considering rethinking my position based on evidence.

Start a wiki on your network using some wiki software.
Start a category on your site called "best practices" or "coding standards" or something.
Point everyone to it. Allow for feedback.
When you do releases of the software, have the person whose job it is to put code into the build push back on developers, pointing them to the Wiki pages on it.
I've done this in my organization and it took several months for people to really get into the hang of using the Wiki but now it's this indispensable resource.

If you have even a loose standard of coding, being able to point to that, or indicating that you can't follow the code because it's not the correct format may be worthwhile.
If you don't have a coding format, now would be a good time to get one in place. Something like the answers to this question may be helpful: https://stackoverflow.com/questions/4121/team-coding-styles

I always go with the line 'This is what I would do'. I don't try and lecture them and tell them their code is rubbish but just give an alternative viewpoint that can hopefully show them something that is obviously a bit neater.

Have the person(s) in question prepare a presentation to the rest of the group on the code for a representative module they have written, and let the Q&A take care of it (trust me, it will, and if it's a good group, it shouldn't even get ugly).

I do love code, and never had any course in my live about anything related to informatics I started very bad and started to learn from examples, but what I always remember and kept in my mind since I read the "Gang Of Four" book was:
"Everyone can write code that is understood by a machine, but not all can write code that is understood by a human being"
with this in mind, there is a lot to be done in the code ;)

I can't emphasize patience enough. I've seen this exact sort of thing completely backfire mostly because someone wanted the changes to happen NOW. Quite a few environments need the benefits of evolution, not revolution. And by forcing change today, it can make for a very unhappy environment for all.
Buy-in is key. And your approach needs to take into account the environment you are in.
It sounds like you're in an environment that has a lot of "individuality" to it. So... I wouldn't suggest a set of coding standards. It will come across that you want to take this "fun" project and turn it into a highly structured work project (oh great, what's next... functional documents?). Instead, as someone else said, you'll have to deal with it to a certain extent.
Stay patient and work toward educating others in your direction. Start with the edges (points where your code interacts with others) and when interacting with their code try to take it as an opportunity to discuss the interface they've created and ask them if it would be okay with them if it was changed (by you or them). And fully explain why you want the change ("it will help deal with changing subsystem attributes better" or whatever). Don't nit-pick and try to change everything you see as being wrong. Once you interact with others on the edge, they should start to see how it would benefit them at the core of their code (and if you get enough momentum, go deeper and truly start to discuss modern techniques and the benefits of coding standards). If they still don't see it... maybe you'll need to deal with that within yourself (especially on a "fun" project).
Patience. Evolution, not revolution.
Good luck.

I don a toga and open a can of socratic method.
The Socratic Method named after the Classical Greek philosopher Socrates, is a form of philosophical inquiry in which the questioner explores the implications of others' positions, to stimulate rational thinking and illuminate ideas. This dialectical method often involves an oppositional discussion in which the defense of one point of view is pitted against another; one participant may lead another to contradict himself in some way, strengthening the inquirer's own point.

A lot of the answers here relate to code formatting which these days is not particularly relevant, as most IDEs will reformat your code in the style you choose. What really matters is how the code works, and the poster is right to look at global variables, copy & paste code, and my pet peeve, naming conventions. There is such a thing as bad code and it has little to do with format.
The good part is that most of it is bad for a very good reason, and these reasons are generally quantifiable and explainable. So, in a non-confrontational way, explain the reasons. In many cases, you can even give the writer scenarios where the problems become obvious.

I'm not the lead developer on my project and therefore can't impose coding standards but I have found that bad code usually causes an issue sooner rather than later, and when it does i'm there with a cleaner idea or solution.
By not interjecting at the time and taking a more natural approach i've gained more trust with the lead and he often turns to me for ideas and includes me on the architectural design and deployment strategy used for the project.

People writing bad code is just a symptom of ignorance (which is different from being dumb). Here's some tips for dealing with those people.
Peoples own experience leaves a stronger impression than something you will say.
Some people are not passionate about the code they produce and will not listen to anything you say
Paired Programming can help share ideas but switch who's driving or they'll just be checking email on their phone
Don't drown them with too much, I've found even Continuous Integration needed to be explained a few times to some older devs
Get them excited again and they will want to learn. It could be something as simple as programming robots for a day
TRUST YOUR TEAM, coding standards and tools that check them at build time are often never read or annoying.
Remove Code Ownership, on some projects you will see code silos or ant hills where people say thats my code and you can't change it, this is very bad and you can use paired programming to remove this.

Instead of having them write code, have them maintain their code.
Until they have to maintain their steaming pile of spaghetti, they will never understand how bad they are at coding.

Nobody likes to listen someone saying their work sucks, but any sane person would welcome mentoring and ways of avoiding unnecessary work.
One school of teaching even says that you should not point out mistakes, but focus what is done right. For instance, instead of pointing out incomprehensible code as bad, you should point out where their code is particularly easy to read. In the first case you are priming others to think and act like crappy programmers. In the later case you are priming for thinking like a skilled professional.

I have a similar senario with the guys i work with.. They dont have the exposure to coding as much as i do but they are still usefull at coding.
Rather than me letting the do what they want and go back and edit the whole thing. I usually just sit them down and show them two ways of doing things. Thier way and My way, From this we discuss the pro's and cons of each method and therefore come to a better understanding and a better conclusion on how should we go about programming.
Here is the really suprizing part. Sometimes they will come up with questions that even i dont have answers to, and after research we all get a better concept of methodology and structure.
Discuss.
Show them Why
Don't even think you are always right.. Sometimes even they will teach you something new.
Thats what i would do if i was you :D

Probably a bit late after the effect, but that's where an agreed coding standard is a good thing.

I frankly believe that someone's code is better when it's easier to change, debug, navigate, understand, configure, test and publish (whew).
That said I think it is impossible to tell someone his/her code is bad without having a first go at having him / her explaining what it does or how is anyone supposed to enhance it afterwards (like, creating new funcionality or debugging it).
Only then their mind snaps and anyone will be able to see that:
Global variables value changes are almost always untrackable
Huge functions are hard to read and understand
Patterns make your code easier to enhance (as long as you obay to their rules)
( etc...)
Perhaps a session of pair programming should do the trick.
As for enforcing coding standards - it helps but they are too far away from really defining what is good code.

You probably want to focus on the impact of the bad code, rather than what might be dismissed as just your subjective opinion of whether it's good or bad style.

Privately inquire about some of the "bad" code segments with an eye toward the possibility that it is actually reasonable code, (no matter how predisposed you may be), or that there are perhaps extenuating circumstances. If you are still convinced that the code is just plain bad -- and that the source actually is this person -- just go away. One of several things may happen: 1) the person notices and takes some corrective action, 2) the person does nothing (is oblivious, or doesn't care as much as you do).
If #2 happens, or #1 does not result in sufficient improvement from your point of view, AND it is hurting the project, and/or impinging on you enough, then it may be time to start a campaign to establish/enforce standards within the team. That requires management buy-in, but is most effective when instigated from grass roots.
Good luck with that. I feel your pain brother.

Related

What are some good strategies to fix bugs as code becomes more complex?

I'm "just" a hobbyist programmer, but I find that as my programs get longer and longer the bugs get more annoying--and harder to track. Just when everything seems to be running smoothly, some new problem will appear, seemingly spontaneously. It may take me a long time to figure out what caused the problem. Other times I'll add a line of code, and it'll break something in another unit. This can get kind of frustrating if I thought everything was working well.
Is this common to everyone, or is it more of a newbie kind of thing? I hear about "unit testing," "design frameworks," and various other concepts that sound like they would decrease bugginess, make my apps "robust," and everything easy to understand at a glance :)
So, how big a deal are bugs to people with professional training?
Thanks -- Al C.
The problem of "make a fix, cause a problem elsewhere" is very well known, and is indeed one of the primary motivations behind unit testing.
The idea is that if you write exhaustive tests for each small part of your system independently, and run them on the entire system every time you make a change anywhere, you will see the problem immediately. The main benefit, however, is that in the process of building these tests you'll also be improving your code to have less dependencies.
The typical solution to these sort of problems is to reduce coupling; make different parts less dependent on one another. More experienced developers sometimes have habits or design skills to build systems in this manner. For example, we use interfaces and implementations rather than classes; we use model-view-controller for user interfaces, etc. In addition, we can use tools that help further reduce dependencies, like "Dependency injection" and aspect oriented programming.
All programmers make mistakes. Good and experienced programmers build their programs so that it is easier to find the mistakes and restrict their effects.
And it is a big deal for everyone. Most companies spend more time on maintenance than on writing new code.
Are you automating your tests? If you do not, you're signing up creating bugs without finding them.
Are you adding tests for bugs as you fix them? If you do not, you are signing up for creating the same bugs over and over.
Are you writing unit tests? If not, you are signing up for long debugging sessions when a test fails.
Are you writing your unit tests first? If not, your unit tests will be hard to write when your units are tightly coupled.
Are you refactoring mercilessly? If not, every edit will become more difficult and more likely to introduce bugs. (But make sure you have good tests, first.)
When you fix a bug, are you fixing the entire class? Don't just fix the bug; don't just fix similar bugs throughout your code; change the game so you can never create that kind of bug again.
Bugs are a big deal to everyone. I've always found that the more I program, the more I learn about programming in general. I cringe at the code I wrote a few years back!! I started out as a hobbyist and liked it so much that I went to engineering college to get a Computer Science Engineering major (I am in my final semester). These are the things that I have learned :
I take time to actually design what I am going to write and document the design. It really eliminates a lot of problems down the line. Whether the design is as simple as writing down a few points on what I am going to write or full blown UML modeling (:( ) doesn't matter. Its the clarity of thought and purpose and having material to look back at when I come back to the code after a while that matter the most.
No matter what language I write in, keeping my code simple and readable is important. I think that it is extremely important not to over complicate the code and at the same time not to over simplify it. (Hard learned lesson!!)
Efficiency optimizations and fancy tricks should be applied at the end, only when necessary and only if they are needed. Another thing is that I apply them only If I really know what I am doing and I always test my code!
Learning language dependant details helps me keep my code bug free. For instance I learned that scanf() is evil in C!
Others have already commented on the zen of writing tests. I would like to add that you should always do regression tests. (i.e. Write new code, test all parts of your code to see if it breaks)
Keeping a mental picture of code is hard at times, so I always document my code.
I use methods to make sure that there is a bare minimum dependence between different parts of my code. Interfaces, class hierarchies etc. (Decoupled design)
Thinking before I code and being disciplined in whatever I write is another crucial skill. I know people who don't format their code so its readable (Shudder!).
Reading other peoples source to learn best practices is good. Making my own list is better!. When working in a team, there must be a common set of them.
Don't be paralyzed by analysis. Write tests, then code, then execute and test. Rinse wash repeat!
Learning to read over my own code and combing it for mistakes is important. Improving my arsenal of debugging skills was a great investment. I keep them sharp by helping my classmates fix bugs regularly.
When there is a bug in my code, I assume its my mistake, not the computers and work from there. That is a state of mind that really helps me.
A fresh pair of eyes aids in debugging. Programmers tend to miss even the most obvious errors in their own code when exhausted. Having someone to show your code to is great.
having someone to throw ideas at and not be judged is important. I talk to my mom (who is not a programmer) , throw ideas at her and find solutions. She helps me bounce my ideas back and forth and refine them. If she is unavailable, I talk to my pet cat.
I am not so be discouraged by bugs anymore. I've learned to love removing bugs almost as much as programming.
Using version control has really helped me manage different ideas I get while coding. That helps reduce errors. I recommend using git or any other version control system you might like.
As Jay Bazzuzi said - Refactor code. I just added this point after reading his answer, to keep my list complete. All credit goes to him.
Try to write reusable code. Reuse code, both yours and from libraries. Using libraries which are bug free to do some common tasks really reduces bugs (sometimes).
I think the following quote says it best - "If debugging is the art of removing bugs, programming must be the art of putting them in."
No offense to anyone who disagrees. I hope this answer helps.
Note
As others Peter has pointed out, use Object Oriented Programming if you are writing a large amount of code. There is a limit to code length after which it becomes harder and harder to manage if written procedurally. I like procedural for smaller stuff, like playing with algorithms.
There are two ways to write error-free programs; only the third one works. ~Alan J. Perlis
The only way for errors to occur in a program is by being put there by the author. No other mechanisms are known. Programs can't acquire bugs by sitting around with other buggy programs. ~Harlan Mills
Obviously, bugs are a big deal to any programmer. Just look through the list of questions on Stack Overflow to see this illustrated.
The difference between a hobbyist and an experienced professional is that the pro will be able to use his experience to code in a more "defensive" way, avoiding many types of bugs in the first place.
All the other answers are great. I'll add two things.
Source control is mandatory. I'm assuming you're on windows here. VisualSVN Server is free and maybe 4 clicks to install. TortoiseSVN is also free and it integrates into Windows Explorer, getting around the VS Express limitations of no add-ins. If you create too many bugs, you can revert your code and start over. Without source control, this is next to impossible. Plus you can sync your code if you have a laptop and a desktop.
People are going to recommend many techniques like unit testing, mocking, Inversion of Control, Test Driven Development, etc. These are great practices, but don't try to cram it all into your head too quickly. You have to write code to get better at writing code, so work these techniques slowly into your code writing. You have to crawl before you walk and walk before you can run.
Best of luck in your coding adventures!
This is a common newbie thing. As you get more experience, of course, you'll still have bugs, but they'll be easier to find and fix because you'll learn how to make your code more modular (so that changing one thing doesn't have ripple effects everywhere else), how to test it, and how to structure it to fail fast, close to the source of the problem, rather than in some arbitrary place. One very basic but useful thing that doesn't require complex infrastructure to implement is to check the inputs to all functions that have non-trivial precondtions with asserts. This has saved me several times in cases where I would have otherwise gotten weird segfaults and arbitrary behavior that would have been near impossible to debug.
If bugs weren't a problem then I'd be able to write a 100,000 line program in 10 minutes!
Your question is like, "As an amateur doctor, I worry about my patients' health: sometimes when I'm not careful enough, they sicken. Is patients' health a problem for you professional doctors too?"
Yes: it's the central problem, even the only problem (for any sufficiently all-inclusive definition of 'bug').
Bugs are common to everyone -- professional or not.
The larger and more distributed the project, the more careful one must be. One look at any open source bug database (ex: https://bugzilla.mozilla.org/ ) will confirm this for you.
The software industry has evolved various programming styles and standards, which when used right, make wrong code easier to spot or limited in its impact.
Therefore, training has a very positive on code quality... But at the end of the day, bugs still sneak through.
If you're just a hobbyist programmer, learning full bore TDD and OOP may involve more time than you're willing to put in. So, going on the assumption that you don't want to put in the time on them, a few easily digestible suggestions to cut down on bugs are:
Keep each function doing one thing. Be suspect of a function more than, say, 10 lines long. If you think you can break it into two functions, you probably should. Something that will help you control this is naming your functions according to exactly what they are doing. If you find that your names are long and unwieldy then you function is probably doing too many things.
Turn magic strings into constants. That is, instead of using:
people["mom"]
use instead
var mom = "mom";
people[mom]
Design your functions to either do something (command) or get something (query), but not both.
An extremely short and digestible take on OOP is here http://www.holub.com/publications/notes_and_slides/Everything.You.Know.is.Wrong.pdf. If you get this, you've got the gist of OOP and are quite frankly ahead of a lot of professional programmers.
The prevailing wisdom seems to be that the average programmer creates 12 bugs per 1000 lines of code - depends on who you ask for the exact number, but it's always per lines of code - so, the bigger the program, the more the bugs.
Subpar programmers tend to create way more bugs.
Newbies are often trapped by idiosyncrasies of the language, and lacking experience tends towards more bugs too. As you go on, you will get better, but never will you create bug-free code... well I still have bugs, even after 30 years, but that could be just me.
Nasty bugs happen to everyone from pros to hobbyists. Really good programmers get asked to track down really nasty bugs. It's part of the job. You'll know you've made it as a software developer when you stare at a nasty bug for two days and in frustration you shout, "Who wrote this crap!?!?" ... only to realize it was you. :-)
Part of the skill of a software developer is the ability to keep a large set of interrelated items straight in his/her head. It sounds like you're discovering what happens when your mental model of the system breaks down. With practice you will learn to design software that doesn't feel so brittle. There are tons of books, blogs, etc. out there on the subject of software design. And Stack Overflow of course for specific questions.
All that said, here's a couple of things you can do:
A good debugger is invaluable. Often you have to step through your code line by line to figure out what went wrong.
Use a garbage-collected language such as Python or Java if it makes sense for your project. GC will help you focus on making things work instead of getting bogged down by maddening memory errors.
If you write C++, learn to love RAII.
Write LOTS of code. Software is somewhat of an art form. Lots of practice will make you better at it.
Welcome to Stack Overflow!
What really changed my odds against code complexity and bugs was using a coding standart - how to place brackets an so on. It may seem like just boring and useless thing but it really unifies all the code and makes it much easier to read and maintain. So do you use a coding standart?
If you're not well organized, your codebase will become your very own Zebra Puzzle. Adding more code is like adding more people/animals/houses to your puzzle, and soon you have 150 various animals, people, houses and cigarette brands in your puzzle and you realize that it just took you a week to add 3 lines of code because everything is so inter-related that it takes forever to make sure the code still executes how you want it to.
The most popular organizational paradigm seems to be Object Oriented Programming, if you can break your logic down into small units which can be constructed and used independently of each other, then you will find bugs far less painful when they occur.

How to justify to your colleagues that they produce crappy code?

I am finding somewhat difficult to carry on working in my current job.
The codebase has become a bit wild lately (but definitely not the worse I've seen), and I'm having a hard time dealing with some parts of the code. I could be stupid, but most likely it's just that it demotivates me a lot to start working on something that is hard to reason about.
My boss is already aware of my thoughts - I expressed what it feels like to work like this. He asked me to provide examples of what was wrong. When I pointed out two or three small issues, he said "yeah, ok" but that refactoring costs him a lot of money, and that we have to get the product out (not the first time I hear this).
I have to admit that the examples were not the most compelling, but the problem is actually tough to explain. It's made up of a lot of tiny "bad decisions" throughout the codebase. (We also see this issue is absolutely subjective). For instance, bad naming, dealing with nulls, boilerplate, not making code reusable (or the opposite) and so on. It can be tiring to re-think someone else's code over again to justify I would have done it differently.
Do you have thoughts on how to deal with this?
I am a bit fed up of having to go hacking around a quick 'n dirty codebase every time!
Sometimes your fellow programmers do things very differently than you, and things you might feel are way wrong might actually have positive aspects. We all have our schools we come from. I think I've come across programmers who complain about things I don't understand equally as often that I myself have felt something needs to be complained about.
Make sure you can deduce what you complain about into a concrete disadvantage. If for no other reason so that you can motivate middle management about improvements to make. Things that are hard to deduce into measurable facts usually originates from difference in taste/style rather than quality (there are boooks to read about this subject). The answer posted by smacl have good and concrete advice!
If you can deduce your concern into a real disadvantage, then I really do not agree when people say that one have to "accept" situations like this. I've been exposed to this problem more than once, and let me tell you, refactoring is not the solution to the problem. Refactoring only fixes the symptoms.
Accepting a situation like this is the same as saying "bad quality product lines and expensive and frustrating maintenance is something my company can live with". This is ofcourse seldomly the case. However management (i.e. those with the go/no-go on what projects to prioritize) are very often not technically aware of what the problems are, or why development is expensive. They shouldn't have to be for that matter.
That's why you need a development organization with technical leads, chief architects, a good organisational structure and tiered model etc. Experienced software professionals who have seen where the road leads to if you ignore certain aspects of development. It's about changing the "culture" of your team(s).
Either you stick with your company and try to change how you do things from the roots, or you find another place to work and make sure you find out during the interview exactly how they work in every-day development.
Good luck
I recently faced a very similar problem and a friend gave me some advice that helped a great deal. He said: "keep yourself out of it."
What he meant was, that you must communicate the problems because they are real, costly problems with consequences in terms of time and money. But when you do communicate, talk only about the consequences for the organization. Do not mention the consequences to you, because then it just sounds like whining and will be ignored.
For example:
Not keeping yourself out of it:
"The other developers use these obscure, misleading identifiers and then I have to spend hours going over the code trying to discover what they meant. It's taking up a lot of my time."
Keeping yourself out of it:
"It would be very helpful and cost effective to do some refactoring of class and variable names and also establish some coding standards around identifiers. The immediate payoff will be an easier-to-understand codebase for everyone, leading to better productivity. The longer-term payoff will be that later we'll be able to modify the code and fix things faster. If a critical bug is discovered right before a release, an understandable codebase will be really important."
I hope that helps.
1) Make the problem more visible and get management buy-in
Keep a very detailed diary of the time spent on various coding tasks over the period of about a month. At the end of the month analyse and summarise the contents for your boss, i.e. time wasted and hence money wasted, to illustrate that change of some form is necessary.
2) Think of a cost effective way of moving forward
For example; Rather than refactoring the entire code base, seperate interfaces from implementations, and enforce tighter standards, including unit tests, naming conventions, etc.. at an interface layer. Thus each programmer can have confidence in using code that they have not written. While this is sweeping the crap under the carpet to a certain extent, it is a good way of preparing for larger scale refactoring.
It is important from a management perspective that workflow is not interrupted, and positive results are visible, so plan accordingly.
3) Agree longer terms improvements with your co-workers
Sit down and agree reasonable coding standards for future code with the other programmers.
Perhaps you could setup monthly meetings and at those meetings you could demonstrate good and bad code. Obviously you don't want to point fingers so you'd want to use generic code examples that are based off of stuff you saw in your project. This way you can constructively gather support from others in your style. You might want to compile these after the meetings so people can easily reference them.
I think it is real easy to point out issues, and complain but to mentor people and help them change requires effort. It isn't an easy task but if you are having trouble being motivated with your job perhaps this would give you a nice burst of motivation. You might learn some things a long the way.
You'll find that this is common-place. What you can do is accept that things are done differently by different people. As you fix bugs or add features, you'll get a brief window into a sub-section of the application that you can improve. When you work on the code, you can make it better, and they don't need to know that you're piecemeal improving the code.
Be very careful though. Sometimes code is written in a way that looks 'hacked', but solves a bug that is not easy to discern. Especially if it is older code which has been tried and tested.
On another note, complaining will only get you viewed as a complainer. Think about what outcome you want, and what actions will most likely produce that outcome. You will always hear the answer 'No' when you ask, 'Can I do X-days of work for absolutely no noticable result?'
You could quit and hope to find something better.
Or, you could stick it out and try improve the code that you can control, when you can control it. No matter how well intentioned the developers are, if there is more than one developer the code base will be "ugly" by a competent developers standards. Work with the other developers to improve their abilities and refactor code as you make enhancements.
For starters:
Enforce the use of static code analysis tools. Every language has a few well known tools.
Show some before and after refactored code examples, and explain why you think it's better. Try not to put any one person on the spot.
Code reviews by experienced developers.
keep in mind, some developers can't be helped no matter how much you try...
If someone critiques your code be polite and open minded, you might learn something.
Cyclomatic complexity / number of changesets/bugs. Complex code is more likely to break, cause more bugs which causes more changes, which cost more money!
99% of the time you never get to choose the people you work with. Not all relationships work out, be they work or otherwise.
It would be best if your project was broken up enough so that each developer can contribute to a spec of what the other needs, so programmers don't step on each other's toes.
Getting people to change their coding style is hard. It takes a cast iron technical lead committed to such things and will help when you bring it up. Management types can't do this, leadership needs to provide technical details.
It sounds to me like you don't have a problem with the code so much as your coworkers. It will probably be very difficult for you to force the changes you want to see. Your best bet would probably be to start updating your resume and keep your eyes open for other opportunities
I think that once you're in the middle of the weeds, you do not really have a good chance of getting things done right, you just have to get them done. I would say most developers do not like firefighting and want the ideal code base, but in my opinion this requires you to spend the time up front planning the system out.
I'd recommend trying to work with your manager to ensure that the areas you feel are lacking now are not lacking in the next project. Maybe its putting you on the lead, having more code reviews with peers, maybe it is further training for the entire team.
Either way, I think this is something that most of us go through. I do agree with the other person advising some caution on this. I know that code I wrote yesterday seemed great at the time and looking back on it, can probably find 10 other ways to do it and make it look cleaner.
Have you considered maybe adding fxcop to the automated builds to enforce coding style? Other than that, you could try suggesting TDD which would give the power to whomever writes the test to enfore that the interfaces for each class are structured in a particular way.
Off the top of my head, that's all that I can think of.
Things in life are not perfect and if you start nitpicking, feathers will be ruffled and relationships soured.
The best method is to pick your battles carefully. If something is small enough ignore it and live with it. If it is big and worthwhile (i.e. the management sees ROI in backing you) go for it.
This is apt for your situation...
God, grant me the serenity to accept the things I cannot change courage to change the things I can and the wisdom to know the difference.
One thing I try to do and it may help you. If a part of code is bad, and the idea you propose to fix it is agreed as best but "no time" excuse is given, why dont you rewrite it? say on your own time? If you decide on sticking around at that job for a while it will only help you. And only you will learn and become a better programmer.
Note that it is a good idea and I would even say required, to do a complete code review of that change before check-in and you should try to time the check-in so that it is before a complete regresion test cycle for a release. That way your refactoring is completely tested out. Over a period of 6 months or so, it will start showing a beneficial impact and you can then ask for time allocation for this, with proof to back it up.
The only thing that has a chance of convincing management is demonstrating that the things you are citing as perceived problems become actual problems.
To try to take advantage of this, try to keep the "complainer" tone down to a minimum, that is, focus on how this affects the bottom line rather than how it makes you feel. Point out possible consequences of poor decisions that you see being made. If those consequences come to pass, and they cost more than an up-front fix would have, gently remind management that you foresaw the difficulty and provide a helpful suggestion as to how future similar costs can be avoided with a little up-front effort.
The problem is, in many organizations, the problems will never cause enough of a problem for management to care, or if they do, they won't see the connection between your perception of the problem and the actual problem the way it occurs. In these cases, you end up seemin like a needlessly persnickety technical person, which isn't a reputation you want to have.
So my advice is, pick your battles. If there is something very egregious that others are about to let slip, then you can speak up and perhaps be vindicated later. For the little details that just grind away at you, I'm afraid there's not much you can do but put up with it.
Show them their own forgotten code disguised as yours for critique.
Take an old piece of their code they have forgotten about
Pretend you wrote it
Ask them to figure out something with it
Make sure they point out how bad the code is for whatever reason
Add your own items. Brainstorm what should be done since it's your fault.
Let them know you didn't know how to bring it up to offend them, but it's their code.
If they recall that they wrote it, they might catch on..
If you have a good relationship with your manager, you might be able to use this to work yourself into a "Senior" or "Lead" Developer role. You could propose that it would be best if one person on the team takes technical leadership of the code base. It would be your job to review the code of others and ask them to make improvements when you feel it is necessary. If you go this route, just make sure to take it slowly. If you ask for a lot very quickly, then you could end up pissing off all the other developers.

The "Should be easy for a junior developer to understand" argument [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
Does anyone actually think this is a good reason to "Dumb down" your code?
When a manager asks you to make your code simple (in terms of technology skills required to understand it) at the cost of more verbose cluttered code what should you do?
I highly disagree. Junior developers will end up being Senior developers. How? By encountering advanced topics that aren't taught in school.
My code base now makes heavy use of Inversion of Control containers. I would never revert my code to the old way because a junior developer had issues groking IoC. Instead I would take them out for a beer after work and discuss it. The more the junior dev learns the less hand holding needs to be done.
Here's a blog post discussing this very topic.
If you're constantly dumbing down your code or designs, it's a pretty good way to make sure your junior developers stay dumb. Challenge them and use it as a mentoring opportunity. Of course, some will never learn, but you've got bigger problems at that point.
It's not just pointy-haired bosses either. As a senior dev, it's often difficult to resist the urge to mommy junior developers. "Oh I'll just do this part because it's way too hard for them", or it'll take them too long, or they'll get way off in the weeds.
And finally, make sure you strike a balance between idiomatic code that uses the full power of a language vs idiomatic code that abuses that power. There's no reason you need to override the || operator just to run its args in two separate threads. At least dumb the code down a little for your older, dumber, future self.
Well, I think it's reasonable to avoid using "clever" language constructs unless they really, really make the code better - at which point if a junior developer sees it, hopefully they'd ask rather than just being flumoxed.
Here's an alternative way of phrasing it though: "Write your code so that it's easy enough to understand that if you get called at 3am and asked to fix a bug in it, you can still understand it."
Seriously, make it as easy to understand as possible. That doesn't mean a comment every other line - it means a comment where the purpose of a piece of code isn't obvious, and only then where the preferred choice of "well make it obvious then" doesn't work.
There's a difference between puzzle code and complex code.
I've found that the single biggest issue is that there is a big difference between "easy to understand by reading" versus "well-factored", and that the two goals are often in direct tension with one another. In well-factored code, there is a lot more jumping around between classes and a lot of virtual dispatch, so the path through the code is very non-linear.
Yes readability and being able to easily understand code is a big part of maintainability in my opinion.
Well if you intend to maintain your code forever, never change jobs, never feel the urge to work on something new, and can assure everyone you will never be hit by a truck, then sure there is no need to dumb down that puzzle code.
No. In the past, I've learned a lot from seeing the tricks of more experienced developers. I'd much rather have had the opportunity to learn something new from them than have had them dumb things down for me.
Its a balancing act...
If any 3 people on your team can 'read' your code and know what its doing... no need to change. However if you're the only person who can understand your code (no matter how rad/clever you think it is).. maybe you should take it down a few notches.
Another guideline to help would be to 'Try the simplest thing that works.' All the latest buzz words are nice to know however what it is even more important is having the skill to spot where you could get by without using them. You don't need to spray paint your code with IOC or Frameworks or Design Patterns...
The manager's side of this argument is sorely missed in this thread :) (and for the record.. I'm not one). His/Her major concern being he doesn't want a dark area of code that no one else dares to venture into.. so if you can convince your boss that a few other people on the team can make an arbitrary fix (or better yet.. show an actual bug fixed by someone else) - the mgr should let you off the hook. Disagreeing with your boss is another art :).. but you can talk things out usually.
You dont have to go all the way backward to Lowest Common Denominator.. strike a balance.
Your goal should not be for your code to be easy to understand for a junior developer. Instead, it should be easy to understand for a maintainence programmer.
This means:
Local "complexity" is okay, when needed. If they see the complex code they'll know they need to dig deeper.
Hidden complexity is bad. If you can't see that changing a piece of code will have subtle side effects then maintaining the code will be a nightmare.
New technologies that are visible are also okay, when not taken to extremes.
This is because those that maintain code rarely have the same overall understanding of the system. Or the time to develop it.
I disagree with the manager: What needs to be simple is the code, not the technology used to write it.
I would, however, impose a closely related requirement:
The internal documentation states clearly what technologies are needed to understand this code, and it gives references to places where those technologies can be learned.
For example, even as a senior developer, I find all matrix codes baffling. But if somebody gives me a reference to the right part of Numerical Recipes, I can puzzle out the details.
Yes. It's a very valid reason to take it down a notch. The reality is that a very, very large number of developers (as in most) are at the junior level.
As far as what you should do... Say "Yes Sir" or "Yes Ma'am" and do it. There is only one boss in that relationship.
UPDATE:
As some people seem to think that having a jr dev learning advanced topics while wading through obfuscated code I want to throw one more thing in here.
When ANY developer (jr or otherwise) runs into code they don’t understand, their first approach is to refactor it into something that is understandable. This is called the “Wow that code is crap I must rewrite it!” syndrome. I’m willing to bet everyone on this board has experienced it. So, as a business owner, do I want to pay for code to be developed each time a new person comes by or do I want to pay for new features to be added?
Guess which person I’m going to keep around longer.
If you dumb down your code, you're going to be stuck working with dummy junior programmers who will never be familiar with advanced coding techniques. If there's any verbose code that's trying to express an inherently complex procedure that you wrote, the aforementioned junior developer probably wouldn't be able to see the forest for the trees anyways. And they'd probably screw up if they had to express a complex concept if all they knew were basic primitive constructs whereas if they knew how to express what they meant tersely and elegantly, the code has a better chance of being correct.
Scott Muc said:
"I've found that the single biggest issue is that there is a big difference between "easy to understand by reading" versus "well-factored", and that the two goals are often in direct tension with one another. In well-factored code, there is a lot more jumping around between classes and a lot of virtual dispatch, so the path through the code is very non-linear."
Quoted for truth, and I think this is one of the biggest problems with C++ code in general. If you're the one that wrote the code, it's pretty easy to come up with a very complicated set of stuff that is well factored, makes lots of sense if you already know it, works well, and generally resembles a diamond crystal, etc. but which, from the perspective of someone who's trying to figure out how you got there and why things are the way they are and how things work, and how one might make changes that fit into the existing system and satisfy new requirements, is almost completely opaque and impenetrable.
How does this kind of situation help maintainability? That situation is one of my main beefs with C++ programmers. Far better to have a mess of plain C code which can be hacked upon than a diamond crystal of inpenetrably super-factored code which nearly nobody can figure out how to sensibly modify without smashing the crystalline structure.
One way to "dumb down" code that I actually think is an excellent practice is to use longer variable names and longer function names. Naming variables and functions to make their purpose easily understandable is a significant engineering task, IMHO, and takes extra effort on the part of the original author of the code. Damian Conway has some excellent examples in "Perl Best Practices". Some examples include: Prefer "final_total" to "sum"; prefer "previous_appointment" to "previous_elem", prefer "next_client" to "next_elem". Prefer "sales_records" to "data". Etc. He also pushes for using grammatical templates (Noun-adjective) and staying consistent. Don't use max_displacement one place and then use VelocityMax in another. Index variables need real names too:
sales_record[i] vs sales_record[cancelled_transaction_number]
I frequently "refactor" my code at the end of a development cycle by finding new names for all my functions and variables. In a modern editor it's trivial to change them all, and it's only at the end that I really figure out what I used them for. "Dumbing down" code this way isn't classic C, but it's easier for me when I come back months later asking WTF did I do?
It depends on the code. Is this something being shipped in your flagship product that requires use of the features your manager wants you to remove for performance reasons? If the answer is yes I would try to have your manager let you keep the code and just write up a document explaining in detail the section of code that is hard to understand. If it's an internal app that needs to be maintained by lots of different people and the complex features can be removed with out negatively affecting the program remove them and pick more important battles to fight.
You should just remind your boss that you can build rocket ships or chicken coops, and he will have to pay you the same for either one. Do what they say but generally an environment like that lends itself to people looking for a new environment.
The old quote is appropriate here:
Make everything as simple as possible,
but not simpler.
I've known developers who wrote highly obfuscated code that they felt was advanced but which the rest of the team felt was unreadable and unmaintainable. Part of this involved overuse of advanced language features (in C, the ternary operator and the comma operator) and writing in an obscure personal idiom (for example, replacing ptr->item with (*ptr).item everywhere) that no-one else would ever be able to maintain. The author was trying to outsmart the optimizer (which to be fair, was far from good).
Note: I'm not suggesting that "x = (p == NULL) ? "default" : p->value;" is complicated, but when someone uses ternary operators that span many lines, are nested, and make heavy use of the comma operator, code quickly becomes unreadable.
In this sort of case, "dumbing down" the code would have been a good idea. The problem was not advanced algorithms nor advanced language features, but overuse and inappropriate use of advanced language features, and an obscure personal idiom.
However, in the case you are asking about, where the manager's changes make the code more difficult to read and maintain, I agree with you and the others who have responded. I just wanted to point out the alternative that no-one else has mentioned.
I suggest keeping the code in a "Geeky-level" and comment it well so that the juniors can understand the intention behind the code and simultaneously learn a better way (or a right way) to code, so we have the best of both he worlds.
I think it is the manager's way of politely telling you that your code is too obfuscated/complex/jumbled/puzzle code...whatever you want to call it. Sometimes we get so involved writing our codes that we forget that someone else will have to come along and read it later.
I learned it the hard way and, in retrospect, find that it was the better way. Let the cycle repeat itself.
I agree 100% with the argument. With one major addition: Train your junior developers until they understand your code ;-)
I'm talking about using "unusual" technologies. In this case it's JQuery.
This issue came up when I was writing a wizard control for user registration.
The navigation menu needed to be customised and the current step in the wizard had to have a different css class in the menu. This meant I needed to get access to the currently selected step when generating the menu. My solution was to output the current step index in a hidden html field which could then be read by JQuery in order to customise the css.
I thought that this was much nicer and cleaner than using the databinding syntax in ASP.NET which doesn't have compile-time checking and messes up the layout of the html.
The databinding solutions is "standard" while the JQuery one is "unusual" which means that it's less likely to be understood by a junior.
I'm trying more and more these days to provide the required data for the UI rather than hack it into the UI with databinding which is why I added the hidden field with the current step index.
It is simply impossible to make progress or to innovate in any industry without doing things that others don't understand. Innovation is necessarily blasphemous. Why? Because if you're doing things that make sense to everyone else around you, the odds are you're not the first one doing it. ;)
That being said, there is a significant difference between doing something that is difficult to understand simply because it's a new or complicated problem versus doing something that's difficult to understand because you're trying to show off or you think confusing people will somehow gain you job security (which I've never seen work, but I've heard of people trying).
Should you make things easy to understand? Yes absolutely, as much as humanly possible. However a program that works and does its job well is the higher priority.
The manager's complaint should never be "don't do this because our junior guys don't understand it" -- it should only ever be "do x instead of y whenever feasible because x is easier to read / understand". This also assumes that x and y are equivalent (accept the same input and produce the same result).
I can't stand when managers do that... I've had three different managers bawl me out for using perfectly normal code the way it was designed to work, not because I was doing anything complicated, but rather only because they felt like it was too much effort for the other guys on our team to go RTFM on the language we were using. As a management strategy, that's totally backwards. It's like being the Holy Roman Catholic church and insisting that the laymen are too dumb to be trusted with literacy.
If you want to know really how ridiculous some of these managers get, try this: I had one manager bawl me out for declaring a variable as a type of "boolean" because he didn't feel the other programmers could handle it. Actually when I asked why, his answer was "because we don't do that here", which is a non-answer, but I interpreted it to mean "dumb it down". They were also berating me for that and similar practices as though it should be obvious that good programming habits were actually "bad" and that I should already know why even though they had never expressed a preferred programming style (either formally or informally). Needless to say, it was a bad job.
Make sure you can understand what it does 6 months down the road.
When in doubt, COMMENT your code. That's what comments are for.

What does a good programmer's code look like? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I am a hobbyist programmer (started with VBA to make excel quicker) and have been working with VB.NET / C#.NET and am trying to learn ADO.NET.
A facet of programming that has always frustrated me is what does 'good' look like? I am not a professional so have little to compare against. What makes a better programmer?
Is it:
They have a better understanding of
all the objects / classes / methods
in a given language?
Their programs are more efficient?
The design of their programs are much
better in terms of better
documentation, good choice of names
for functions etc.?
Put another way, if I were to look at the code of a professional programmer, what is the first thing that I would notice about their code relative to mine? For example, I read books like 'Professional ASP.NET' by Wrox press. Are the code examples in that book 'world class'? Is that the pinnacle? Would any top-gun programmer look at that code and think it was good code?
The list below is not comprehensive, but these are the things that I thought of in considering your question.
Good code is well-organized. Data and operations in classes fit together. There aren't extraneous dependencies between classes. It does not look like "spaghetti."
Good code comments explain why things are done not what is done. The code itself explains what is done. The need for comments should be minimal.
Good code uses meaningful naming conventions for all but the most transient of objects. the name of something is informative about when and how to use the object.
Good code is well-tested. Tests serve as an executable specification of the code and examples of its use.
Good code is not "clever". It does things in straightforward, obvious ways.
Good code is developed in small, easy to read units of computation. These units are reused throughout the code.
I haven't read it yet, but the book I'm planning to read on this topic is Clean Code by Robert C. Martin.
The first thing you'd notice is that their code follows a consistent coding-style. They always write their structure blocks the same, indent religiously and comment where appropriate.
The second things you'd notice is that their code is segmented into small methods / functions spanning no more than a couple dozen lines at the most. They also use self describing method names and generally their code is very readable.
The third thing you'd notice, after you messed around with the code a little is that the logic is easy to follow, easy to modify - and therefore easily maintainable.
After that, you'll need some knowledge and experience in software design techniques to understand the specific choices they took constructing their code architecture.
Regarding books, I haven't seen many books where the code could be considered "world-class". In books they try mostly to present simple examples, which might be relevant to solving very simple problems but aren't reflective of more complex situations.
Quoting Fowler, summizing readability:
Any fool can write code that a computer can understand.
Good programmers write code that humans can understand.
'nough said.
Personally, I'll have to quote "The Zen of Python" by Tim Peters. It tells Python programmers what their code should look like, but I find that it applies to basically all code.
Beautiful is better than ugly. Explicit is better than
implicit. Simple is better than complex. Complex is better
than complicated. Flat is better than nested. Sparse is
better than dense. Readability counts. Special cases
aren't special enough to break the rules. Although practicality
beats purity. Errors should never pass silently. Unless
explicitly silenced. In the face of ambiguity, refuse the
temptation to guess. There should be one-- and preferably only
one --obvious way to do it. Although that way may not be obvious
at first unless you're Dutch. Now is better than never.
Although never is often better than right now. If the
implementation is hard to explain, it's a bad idea. If the
implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Code is poetry.
Start from this point of logic and you can derive many of the desirable qualities of code. Most importantly, observe that code is read far more than it is written, hence write code for the reader. Rewrite, rename, edit, and refactor for the reader.
A follow on corollary:
The reader will be you at time n from the code creation date. The payoff of writing code for the reader is a monotonically increasing function of n. A reader looking at your code for the first time is indicated by n == infinity.
In other words, the larger the gap of time from when you wrote the code to when you revisit the code, the more you will appreciate your efforts to write for the reader. Also, anyone you hand your code off to will gain great benefit from code written with the reader as the foremost consideration.
A second corollary:
Code written without consideration for the reader can be unnecessarily difficult to understand or use. When the consideration for the reader drops below a certain threshold, the reader derives less value from the code than the value gained by rewriting the code. When this occurs the previous code is thrown away and, tragically, much work is repeated during the rewrite.
A third corollary:
Corollary two has been known to repeat itself multiple times in a vicious cycle of poorly documented code followed by forced rewrites.
I've been programming for 28 years and I find this a tough question to answer. To me good code is a complete package. The code is cleanly written, with meaningful variable and method names. It has well placed comments that comment the intent of the code and doesn't just regurgitate the code you can already read. The code does what it is supposed to in an efficient manner, without wasting resources. It also has to be written with an eye towards maintainability.
The bottom line though is that it means different things to different people. What I might label as good code someone else might hate. Good code will have some common traits which I think I've identified above.
The best thing you can do is expose yourself to code. Look at other people's code. Open Source projects are a good source for that. You will find good code and bad code. The more you look at it, the better you will recognize what you determine to be good code and bad code.
Ultimately you will be your own judge. When you find styles and techniques you like adopt them, over time you will come up with your own style and that will change over time. There is no person on here that can wave a wand and say what is good and that anything else is bad.
Read the book Code Complete. This explains a lot of ideas about how to structure code and the the reasons for doing so. Reading it should short-circuit your time to aquiring the experience necessary to tell good from bad.
http://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1229267173&sr=8-1
Having been programming for nearly 10 years now myself and having worked with others I can say without bias that there is no difference between a good programmer and an average programmers code
All programmers at a competent level:
Comment Correctly
Structure Efficiently
Document Cleanly
I once overheard a co-worker say "I've always been very logical and rational minded. I think that's why I enjoy developing"
That in my opinion, is the mind of an average programmer. One who sees the world in terms of rules and logic and ultimately obeys those rules when designing and writing a program.
The expert programmer, understands the rules, but also their context. This ultimately leads to them coming up with new ideas and implementations, the mark of an expert programmer. Programming is ultimately an art form.
Succinctly put, a good programmer's code can be read and understood.
In my opinion, a good programmer's code is language-agnostic; well-written code can be read and understood in a short amount of time with minimal thinking, regardless of the programming language used. Whether the code is in Java, Python, C++ or Haskell, well-written code is understandable by people who don't even program in that particular language.
Some characteristics of code that is easy to read are, methods that are well-named, absence of "tricks" and convoluted "optimization", classes are well-designed, to name a few. As others have mentioned, coding style is consistent, succinct and straight-forward.
For example, the other day, I was taking a look at the code for TinyMCE to answer one of the questions on Stack Overflow. It is written in JavaScript, a language that I've hardly used. Yet, because of the coding style and the comments that are included, along with the structuring of the code itself, it was fairly understandable, and I was able to navigate through the code in a few minutes.
One book that was quite an eye-opener for me in the regard of reading good programmer's code is Beautiful Code. It has many articles written by authors of various programming projects in various programming languages. Yet, when I read it, I could understand what the author was writing in his code despite the fact that I've never even programmed in that particular language.
Perhaps what we should keep in mind is that programming is also about communication, not only to the computer but to people, so good programmer's code is almost like a well-written book, which can communicate to the reader about the ideas it wants to convey.
Easy to read
easy to write
easy to maintain
everything else is filigree
Good code should be easily understood.
It should be well commented.
Difficult parts should be even better commented.
Good code is readable. You'd have no trouble understanding what the code is doing on the first read through of code written by a good professional programmer.
Rather then repeat everyone else's great suggestions, I will instead suggest that you read the book Code Complete by Steve McConnell
Essentially it is a book packed full of programming best practices for both functionality and style.
[Purely subjective answer]
For me, good code is a form of art, just like a painting. I might go further and say that it's actually a drawing that includes characters, colors, "form" or "structure" of code, and with all this being so readable/performant. The combination of readability, structure (i.e. columns, indentation, even variable names of the same length!), color (class names, variable names, comments, etc.) all make what I like to see as a "beautiful" picture that can make me either very proud or very detestful of my own code.
(As said before, very subjective answer. Sorry for my English.)
I second the recommendation of Bob Martin's "Clean Code".
"Beautiful Code" was highly acclaimed a couple of years ago.
Any of McConnell's books are worth reading.
Perhaps "The Pragmatic Programmer" would be helpful, too.
%
Just wanted to add my 2 cents... comments in your code -- and your code itself, generally -- should say what your code does, now how it does it. Once you have the concept of 'client' code, which is code that calls other code (simplest example is code that calls a method), you should always be most worried about making your code comprehensible from the "client's" perspective. As your code grows, you'll see that this is... uh, good.
A lot of the other stuff about good code is about the mental leaps that you'll make (definitely, if you pay attention)... 99% of them have to do with doing a bit more work now to spare you a ton of work later, and reusability. And also with doing things right: I almost always want to run the other way rather than using regular expressions, but every time I get into them, I see why everybody uses them in every single language I work in (they're abstruse, but work and probably couldn't be better).
Regarding whether to look at books, I would say definitely not in my experience. Look at APIs and frameworks and code conventions and other people's code and use your own instincts, and try to understand why stuff is the way it is and what the implications of things are. The thing that code in books almost never does is plan for the unplanned, which is what error checking is all about. This only pays off when somebody sends you an email and says, "I got error 321" instead of "hey, the app is broke, yo."
Good code is written with the future in mind, both from the programmer's perspective and the user's perspective.
This is answered pretty well in Fowler's book, "Refactoring", It's the absence of all the "smells" he describes throughout the book.
I haven't seen 'Professional ASP.NET', but I'd be surprised if it's better than OK. See this question for some books with really good code. (It varies, of course, but the accepted answer there is hard to beat.)
This seems to be (should be) a FAQ. There is an ACM article about beautiful code recently. There seems to be a lot of emphasis on easy to read/understand. I'd qualifier this with "easy to read/understand by domain experts". Really good programmers tend to use the best algorithms (instead of naive easy to understand O(n^2) algorithms) for any given problems, which could be hard to follow, if you're not familiar with the algorithm, even if the good programmer gives a reference to the algorithm.
Nobody is perfect including good programmers but their code tend to strive for:
Correctness and efficiency with proven algorithms (instead of naive and adhoc hacks)
Clarity (comment for intent with reference to non-trivial algorithms)
Completeness to cover the basics (coding convention, versioning, documentation, unit tests etc.)
Succinctness (DRY)
Robustness (resilient to arbitrary input and disruption of change requests)
i second the recommendation for uncle bob's "clean code". but you may wish to take a look at http://www.amazon.com/Implementation-Patterns-Addison-Wesley-Signature-Kent/dp/0321413091 as i think this deals with your specific question a bit better. good code should leap off the page and tell you what it does/how it works.
Jeff Atwood wrote a nice article about how coders are Typists first reference:
http://www.codinghorror.com/blog/archives/001188.html
When being a typist you always need to be elegant in your work, having strucutre and proper "grammar" is highly important. Now converting this to "programming"-typing would catch the same outcome.
Structure
Comments
Regions
I'm a software engineere which means during my education i've come across many different languages but my programming always "feel" the same, as my writing does on fekberg.wordpress.com, i have a "special" way for typing.
Now programming different applications and in different languages, such as Java, C#, Assembler, C++,C i've come to the "standard" of writing that i like.
I see everything as "boxes" or regions and each region has it's explaining commenting. A region might be "class Person" and inside this Region i have a couple of methods for properties, which i may call "Access Methods" or such and each property and region has it's own explaining commenting.
This is highly important, i always see my code that i do, as "being a part of an api", when creating an API structure and elegance is VERY important.
Think about this. Also read my paper on Communication issues when adapting outsourcing which explains in rough, how bad code can conflict, Enterpret as you like: http://fekberg.wordpress.com/2008/12/14/communication-issues-when-adapting-outsourcing/
Good code is easy to understand, easy to maintain, and easy to add to. Ideally, it is also as efficient as possible without sacrificing other indicators.
Great code to me is something that is simple to grasp yet sophisticated. The things that make you go, "wow, of course, why didn't I think of it that way?". Really good code is not hard to understand, it simply solves the problem at hand in a straight-forward way (or a recursive way, if that is even simpler).
Good code is where you know what the method does from the name. Bad code is where you have to work out what the code does, to make sense of the name.
Good code is where if you read it, you can understand what it's doing in not much more time than it takes to read it. Bad code is where you end up looking at it for ages trying to work out wtf it does.
Good code has things named in such a way as to make trivial comments unnecessary.
Good code tends to be short.
Good code can be reused to do what it does anywhere else, since it doesn't rely on stuff that is really unrelated to its purpose.
Good code is usually a set of simple tools to do simple jobs (put together in well organised ways to do more sophisticated jobs). Bad code tends to be huge multi-purpose tools that are easy to break and difficult to use.
Code is a reflection of a programmer's skills and mindset. Good programmers always have an eye on the future - how the code will function when requirements or circumstances are not exactly what they are today. How scalabale it will be? How convenient it will be when I am not the one maintaining this code? How reusable the code will be, so that someone else doing similar stuff can reuse the code and not write it again. What when someone else is trying to understand the code that I have written.
When a programmer has that mindset, all the other stuff falls in place nicely.
Note: A code base is worked on by many programmers over time and typically there is not a specific designation of code base to a programmer. Hence good code is a reflection of all the company's standards and quality of their workforce.
(I use "he" below because this is the person that I aspire to be, sometimes with success).
I believe that the core of a good programmer's philosophy is that he is always thinking "I am coding for myself in the future when I will have forgotten all about this task, why I was working on it, what were the risks and even how this code was supposed to work."
As such, his code has to:
Work (it doesn't matter how fast code gets to the wrong answer. There's no partial credit in the real world).
Explain how he knows that this code works. This is a combination of documentation (javadoc is my tool of choice), exception handling and test code. In a very real sense, I believe that, line for line, test code is more valuable than functional code if for no other reason than it explains "this code works, this is how it should be used, and this is why I should get paid."
Be maintained. Dead code is a nightmare. Legacy code maintenance is a chore but it has to be done (and remember, it's "legacy" the moment that it leaves your desk).
On the other hand, I believe that the good programmer should never do these things:
Obsess over formatting. There are plenty of IDEs, editors and pretty-printers that can format code to exactly the standard or personal preference that you feel is appropriate. I use Netbeans, I set up the format options once and hit alt-shift-F every now and then. Decide how you want the code to look, set up your environment and let the tool do the grunt work.
Obsess over naming conventions at the expense of human communication. If a naming convention is leading you down the road of naming your classes "IElephantProviderSupportAbstractManagerSupport" rather than "Zookeeper", change the standard before you make it harder for the next person.
Forget that he works as a team with actual human beings.
Forget that the primary source of coding errors is sitting at his keyboard right now. If there's a mistake or an error, he should look to himself first.
Forget that what goes around comes around. Any work that he does now to make his code more accessible to future readers will almost certainly benefit him directly (because who's going to be the first person asked to look at his code? He is).
It works
It has unit tests that prove that it works
The rest is icing...
The best code has a certain elegance that you recognise as soon as you see it.
It looks crafted, with care and attention to detail. It's obviously produced with someone with skill and has an art about it - you could say it looks sculpted and polished, rather than rough and ready.
It's consistent and reads easily.
It's split into small, highly cohesive functions each of which do one thing and do it well.
It's minimally coupled, meaning that dependencies are few and strictly controlled,
usually by...
Functions and classes have dependencies on abstractions rather than implementations.
Ironically the better the programmer the less indispensable he/she becomes because the code produced is better maintainable by anyone (as stated by general consent by Eran Galperin).
My experience tells the opposite is also true. The worse the programmer the more difficult to maintain his/her code is, so more indispensable he/she becomes, since no other soul can understand the riddles produced.
I have a good example :
Read GWT (google web tookit) Source code, you will see that every fool understand it (some english books are harder to read than this code).

How do you prevent over complicated solutions or designs? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Many times we find ourselves working on a problem, only to figure out the solution being created is far more complex than the problem requires. Are there controls, best practices, techniques, etc that help you control over complication in your workplace?
Getting someone new to look at it.
In my experience, designing for an overly general case tends to breed too much complexity.
Engineering culture encourages designs that make fewer assumptions about the environment; this is usually a good thing, but some people take it too far. For example, it might be nice if your car design doesn't assume a specific gravitational pull, nobody is actually going to drive your car on the moon, and if they did, it wouldn't work, because there is no oxygen to make the fuel burn.
The difficult part is that the guy who is developed the "works-on-any-planet" design is often regarded as clever, so you may have to work harder to argue that his design is too clever.
Understanding trade-offs, so you can make the decision between good assumptions and bad assumptions, will go a long way into avoiding a needlessly complicated design.
If its too hard to test, your design is too complicated. That's the first metric I use.
Here are some ideas to get design more simpler:
read some programming books and articles, and then apply them in your work and write code
read lots of code (good and bad) written by other people (like Open Source projects) and learn to see what works and what does not
build safety nets (unit tests) to enable experimentations with your code
use version control to enable rollback, if those experimentations take wrong turn
TDD (test driven development) and BDD (behaviour driven development)
change your attitude, ask how you can make it so, that "it simply works" (convention over configuration could help there; or ask how Apple would do it)
practice (like jazz players -- jam with code, try Code Kata)
write same code multiple times, with different languages and after some time has passed
learn new languages with new concepts (if you use static language, learn dynamic one; if you use procedural language, learn functional one; ...) [one language per year is about right]
ask someone to review you code and actively ask how you can make your code simpler and more elegant (and then make it)
get years under your belt by doing above things (time helps active mind)
I create a design etc., and then I look at it and try and remove (agressively) everything that doesn't seem to be needed. If it turns out I need it later when I am polishing the design I add it back in. I do this over several iterations, refining as I go along.
Read "Working Effectively With Legacy Code" by Michael C. Feathers.
The point is, if you have code that works, and you need to change the design, nothing works better than making your code unit testable, and breaking your code into smaller pieces.
Using Test Driven Development and following Robert C. Martin's Three Rules of TDD:
You are not allowed to write any production code unless it is to make a failing unit test pass.
You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.
You are not allowed to write any more production code than is sufficient to pass the one failing unit test.
In this way you are not likely to get much code that you don't need. You will always be focused on making one important thing work and won't ever get too far ahead of yourself in terms of complexity.
Test first may help here, but it is not suitable for all situation. And it's not a panacea anyway.
Start small is another great idea. Do you really need to stuff all 10 design patterns into this thing? Try first to do it "stupid way". Doesn't quite cut it? Okay, do it "slightly less stupid way". Etc.
Get it reviewed. As someone else wrote, two pairs of eyes are better. Even better are two brains. Your mate may just see a room for simplification, or a problematic area you thought was fine just because you spend many hours hacking it.
Use lean language. Languages such as Java, or sometimes C++ sometimes seem to encourage nasty, convoluted solutions. Simple things tend to span over multiple lines of code, and you just need to use 3 external libraries and a big framework to manage it all. Consider using Python, Ruby, etc. - if not for your project, then for some private use. It can change your mindset to favor simplicity, and to be assured that simplicity is possible.
Reduce the amount of data you're working with by serialising the task into a series of smaller tasks. Most people can only hold half a dozen (plus or minus) conditions in their head while coding, so make that the unit of implementation. Design for all the tasks you need to accomplish, but then ruthlessly hack the design so that you never have to play with more than half a dozen paths though the module.
This follows from Bendazo's post - simplify until it becomes easy.
It is inevitable once you have been a programmer that this will happen. If you seriously have unestimated the effort or hit a problem where your solution just doesn't work then stop coding and get talking to your project manager. I always like to take the solutions with me to the meeting, problem is A, you can do x which will take 3 days or we can try y which will take 6 days. Don't make the choice yourself.
Talk to other programmers every step of the way. The more eyes there are on the design, the more likely an overcomplicated aspect is revealed early, before it becomes too ossified in the codebase.
Constantly ask yourself how you will use whatever you are currently working on. If the answer is that you're not sure, stop to rethink what you're doing.
I've found it useful to jot down thoughts about how to potentially simplify something I'm currently working on. That way, once I actually have it working, it's easier to go back and refactor or redo as necessary instead of messing with something that's not even functional yet.
This is a delicate balancing act: on the one hand you don't want something that takes too long to design and implement, on the other hand you don't want a hack that isn't complicated enough to deal with next week's problem, or even worse requires rewriting to adapt.
A couple of techniques I find helpful:
If something seems more complex than you would like then never sit down to implement it as soon as you have finished thinking about it. Find something else to do for the rest of the day. Numerous times I end up thinking of a different solution to an early part of the problem that removes a lot of the complexity later on.
In a similar vein have someone else you can bounce ideas off. Make sure you can explain to them why the complexity is justified!
If you are adding complexity because you think it will be justified in the future then try to establish when in the future you will use it. If you can't (realistically) imagine needing the complexity for a year or three then it probably isn't justifiable to pay for it now.
I ask my customers why they need some feature. I try and get to the bottom of their request and identify the problem they are experiencing. This often lends itself to a simpler solution than I (or they) would think of.
Of course, if you know your clients' work habits and what problems they have to tackle, you can understand their problems much better from the get-go. And if you "know them" know them, then you understand their speech better. So, develop a close working relationship with your users. It's step zero of engineering.
Take time to name the concepts of the system well, and find names that are related, this makes the system more familiar. Don't be hesitant to rename concepts, the better the connection to the world you know, the better your brain can work with it.
Ask for opinions from people who get their kicks from clean, simple solutions.
Only implement concepts needed by the current project (a desire for future proofing or generic systems make your design bloated).

Resources