Although I'm a huge fan of Code Complete -- it is my single most recommended programming book for good reason -- there are chapters in it that I haven't been able to digest, even after 16 years.
One of those chapters describes something called the Pseudocode Programming Process. And on paper, at least, it sounds quite sensible. Before writing a routine, you describe what that routine should do in plain English. So if we we set out to write an error handling lookup routine, we'd first write it in pseudocode:
set the default status to "fail"
look up the message based on the error code
if the error code is valid
if doing interactive processing, display the error message
interactively and declare success
if doing command line processing, log the error message to the
command line and declare success
if the error code isn't valid, notify the user that an
internal error has been detected
return status information
Then, when you're satisfied that you understand what the routine should do, you turn that pseudocode into comments that describe the code you're about to write.
// set the default status to "fail"
Status errorMessageStatus = Status_Failure;
// look up the message based on the error code
Message errorMessage = LookupErrorMessage( errorToReport );
// if the error code is valid
if ( errorMessage.ValidCode() ) {
// determine the processing method
ProcessingMethod errorProcessingMethod = CurrentProcessingMethod();
// if doing interactive processing, display the error message
// interactively and declare success
if ( errorProcessingMethod == ProcessingMethod_Interactive ) {
DisplayInteractiveMessage( errorMessage.Text() );
errorMessageStatus = Status_Success;
}
Pseudocode is sort of like the Tang of programming languages -- you hydrate the code around it.
But why pseudocode? Steve offers some rationales:
All compelling arguments. As an acolyte of McConnell, it pains me to admit this, but every time I've tried the Pseudocode Programming Process, I almost immediately abandon it as impractical.
Why? Two reasons:
Of course, PPP is just one proposed way to code, not the perfect or ideal way. McConnell has no illusions about this, and acknowledges that refactoring, TDD, design by contract, and even plain old "hacking" are valid and alternative ways to construct code.
But still -- I have a hard time seeing pseudocode as useful in anything other than possibly job interviews. And even then, I'd prefer to sit down in front of a computer and write real code to solve whatever problem is being posed. What's your take? Is pseudocode a useful tool in your programming? Do you write pseudocode before writing code?
I don't know if anyone has mentioned this already, but why not write a compiler for the pseudocode instead of writing the same code twice? It's much better to write a compiler that compiles from the pseudocode to the real code instead of translating by hand. Writing pseudocode first and then the real code is like manually translating a high-level language to assembly language.
Nate on May 8, 2009 2:11 AMI read Code Complete when it first came out, and this PPP technique is one of the main takeaways I got from it. I use PPP regularly (though not on everything). It's like making a sketch before breaking out the paints.
It requires a little balance to get the right level of detail in the pseudocode. If it's too low level, then you just end up with a lot of useless, noisy redundancy (as shown in the example). But, if the pseudocode is at an appropriate level, then the comments become a great roadmap to the function, and the code contains all the hairy details.
I find it especially useful when pair programming, as it's much faster to come to agreement on how to lay out the logic before getting bogged down with representational details. It's also good when you're in a top-down mode. I find I use it less when working bottom-up.
Adrian on May 8, 2009 2:13 AMWhen reading CC it occurred to me as a nice method as well. However, I almost never got to really try it out in writing code. It did help me however, writing some particularly nasty functions.
Also, I find myself resorting to this a lot more in less expressive languages like C or Java than in languages that allow me to write code that reads more like a description of what I am trying to do than like code (I love LINQ in this respect).
Johannes on May 8, 2009 2:16 AMThe need to keep some pseudo-code comments is a clear sign that the level of abstraction you're dealing with is to low. In the example you gave I the actual implementation is almost identical to what you wrote in pseudo code. In this case you can either rip the comments if you started with the comments. As an alternative (which I use most of the time) you write code using mocked classes and functions that are your pseudocode and implement them later. Eventually add some refactoring to make the code's intent even more clear. I found this approach useful especially when programming test first -- the final test cases are very descriptive and almost a domain specific language.
Philipp Meier on May 8, 2009 2:25 AMWith the small group of programmers I work with often, we prototype directly in code.
However, if we're sitting with a larger crowd - especially with programmers from other groups - we use pseudo code. You would not believe the amount of time spent getting sidetracked bickering about curly-brace style, indentation, variable naming conventions, implementation of design pattern, etc. And this is from people that should know better. Anyway, in those circumstances, pseudo code streamlines things... at least a bit.
PapaBoojum on May 8, 2009 2:27 AMI try to minimize comments by refactoring code into useful pieces. Python is writing pseudo while programming indeed !
Mohammed on May 8, 2009 2:30 AMWe don't often type it out[1] - normally we just converse across the table in pseudo code, and more often join chairs on one side.
[1] the occasional email when working different hours excepted
Then again, most the pseudo code handles design questions, so it comes closer to Beck Cunninghams CRC card sessions. We picture the code and reshuffle responsibilities until there is no / least dissonance left.
At some point we might shelf the discussion as 'need to think about'. In which case I, for me, like to just close my eyes, listen to some music and think up wildly different. vastly simpler or just fun solutions on my daily 2hour commutes.
It really does give you an edge when coding the thing up. Since you already know what the details should look like, you will continue to follow the main thread and move on to the next hurdle once the first one get's nailed.
When I'm on a roll, this really is exciting and gives me the green bar once every five to 10 minutes, and just so many commits.
It made my collegue mutter last week: Wow. You really want to reach revision #1000 before month's end, do you?!
It's all about effective programming...
... and oranges
attempting to using precise English to describe the nuts and bolts of code
It's not about writing down precisely what should happen. It's about getting a general idea of what should happen. It's an overall view. For me, it is how I work out the algorithm before I code it. I usually mix English in with several computer languages (whichever one has the simplest syntax for what I'm trying to express.) For example, if I where writing a routine that returns the sum of the ASCII values of the logged in username, I might do something like this:
' Get the current user name
for each letter in name
ct += value(letter)
That's a mix of VB, C, Python and English. I don't have to worry about the syntax of the language I'm writing in, I just have to worry about getting my idea out.
slapout on May 8, 2009 2:38 AM
I can think of quite a few instances where pseudocode isn't necessary , or impractical, but I can also think of plenty where it's use has been instrumental in the success of writing whatever function I'm working on.
I'd only write out some pseudocode for a block of code that isn't very intuitive to follow or write. For example, I recently had a homework assignment that was to solve the 'Josephus Problem' using a C++ STL list. The Pseudocode I wrote really helped me work through the problem more easily.
Matthew on May 8, 2009 2:40 AMI used pseudo code a lot. It is a great tool for large scale projects where not everyone is a developer, and you have developers who work in very different languages who need to understand design across the project.
I've worked on many projects that had 100 - 200 team members. Not everyone on the project is a developer...sometimes in reading your blog and listening to the stackoverflow podcast I get the impression you have only worked on projects or products that were staffed with 100% developers...what world is that??
We had specialized developers who only did ABAP, C#, HTML/CSS/Javascript, or were DBAs and stored proc developers. No way could they all read each others' code, but they often needed to understand what it was doing to work together and integrate their piece of the project.
Business people can often understand pseudo code, which is another aspect that is valuable.
Pat on May 8, 2009 2:40 AMI do the pseudocode thing a fair amount, especially if I'm coding something that I don't specifically know how to code from the start, or if it's complex enough that I want to get my thoughts in order first. What I'll do is outline what I want the function to do in comments, and then fill in each comment with code. The comments act more like stubs for functionality (and some of them will end up as functions instead. I wouldn't necessarily call it something one must practice, but it's a tool in my toolbox.
Nathaniel on May 8, 2009 2:55 AMI do believe that pseudo code is a powerful technique to visualize the scope of work. Personally I write pseudo a lot specially when I need to design the scope of multiple classes, functions or web pages. It gives me a clear view about the complexity of the work required and it works as an eye opener to highlight the bits and bites of coding level and functions required.
What is the problem in thinking both ways at the same time, if you can think in a general way using pseudo code, then you can embed small parts of technical language specific code in it. But I perceive the pseudo code methodology as an abstraction method of the design (Big Picture of the Small Pictures).
I hope this doesn't come off as insulting, but if you only think about problems in terms of code I suspect the problems you're trying to solve are not very complicated. (Either that, or you're a super genius--but smart as you clearly are, you're probably not a super genius).
Pseudo-code isn't a 1-to-1 mapping of 1 English (or German or whatever) sentence to 1 line of Java/C#/Python/Ruby/blah code. Pseudo-code is much more high-level. You can gloss over details of things that are unimportant to the core task.
In a (freakin' brutal) grad algorithms class, I learned this lesson: explain succinctly the problem you're trying to solve by giving only enough detail to get the point across. For instance, if you need to find the shortest path from one node to all other nodes in a graph that has positive edge weights, how would you do it? You could write out the pseudo-code to do the whole thing line-by-line, thinking in code, or you could do something like this:
for each node in the graph
run dijkstra's algorithm to find the shortest path
That's a lot of *actual* code compressed into two lines (I guess to be fair, you could also just say: run the Floyd-Warshall algorithm, but that's beside the point).
The point, though, is just to think in terms of high level *ideas*, not code-level *semantics*. It really does unleash your ability to think about more difficult problems when you're not forcing yourself to think about unimportant implementation/code-level details. It also helps you to work outside the box into which Language X tends to push you: once you have the idea, implementing it in *any* language is a more trivial operation.
And as a final aside, thinking in terms of recursion--and particularly Dynamic Programming--is helped *immensely* by not thinking in terms of code, but just high level ideas. Once the ideas/pseudo-code is solid, then you deal with edge cases and semantic details of the code. I would go so far as to say one (or: the non-geniuses among us) can't solve difficult Dynamic Programming problems by thinking about the problem at code-level.
Then again, most web development and business apps tend to be fairly straight-forward CRUD apps at their core, so thinking in terms of code is probably sufficient in many/most cases like that.
Andy Roublev on May 8, 2009 3:00 AM
Another brilliant article! You really should title this blog =~ /.*Rebel.*Software.*/
I use this method when I'm coding a very specific algorithm. For example, a function to know if an account is in credit hold: I have to check the expiration date of the account, if the customer paid the monthly fee and if not, how many days has been pass since the last payment... and other steps that needs to be executed in certain order. That's a business rule that needs to be very well commented in case that somebody get the idea to change one of those steps (and it happens a lot).
So the best way to code one of these functions is writing the pseudocode fist and after really code it, leaving the pseudocode comments there.
Antonio on May 8, 2009 3:34 AMGood variable names, accurate method names, thoughtful enumerations, and descriptive boolean tests get me most of the way toward writing code that I can read and understand without too many comments.
If I'm having trouble finding the right names for things, though, I could see the PPP as being helpful.
But to your end, I've felt the same way about that chapter in CC: I've never really gotten into the swing of things with it.
mbhunter on May 8, 2009 3:51 AMI write Pseudo code for all my code, 'cept I call em specs! :0) They are actually executable so there's no way for them to diverge from the code.
~Lee
Lee Brandt on May 8, 2009 4:00 AMI'm also a big fan of Code Complete and I use the pseudo-code technique with great success at times. I find it most beneficial when the code will do lots of stuff, and I don't want to implement it right now, because maybe this is just supporting code to the main task I'm working at. But I normally don't keep it as comments, because they're very obvious comments when the code is implemented, and normally I have to create still other methods to fully implement the functionality.
Jordão on May 8, 2009 4:10 AMSometimes I already know the logic but not really know how to write the code yet. For example, implementing something in a new language I'm not familiar with. In cases like, writing pseudo-code does not prevent me to make progress forward because it separates the concern of implementing the logic from implementing the code.
Hans Sebastian on May 8, 2009 4:23 AMAs the developer of a system that mixes a lot of technology, pseudo-code provides me a perfect starting point. I can drop all the pseudo-code into my .cs file, and then extract the required portions to SSIS/TSQL/SSRS as needed.
Adam P on May 8, 2009 4:31 AMI generally just code the design as needed. But occasionally I run into a logically difficult section that I pseudocode parts of first so that I can make sure I understand what the designer wanted before I code it. Not often but useful at times.
Charles H on May 8, 2009 4:37 AMCode Complete has always seemed to me the most overrated programming book. I picked it up and saw only a collection of obvious trivialities.
The strange thing is that I agree with most of your recommended reading (especially the pragmatic programmer, the mythical man month and peopleware) but I just don't get this one. The pseudocode thing is a great example. I have not seen that since high school.
Pseudo code is thinking about implementation before you start writing code. As you said, if you are thinking about implementation you may as well do it in code. I prefer the BDD/TDD approach which is think about what it should do (expressed as a test or specification) before thinking about the implementation. Otherwise the implementation inevitable influences the design.
Liam McLennan on May 8, 2009 4:54 AMWow, I couldn't disagree with this post more. Stop thinking of the Psuedocode as _comments_... think of how you would be describing the logic to someone as if you weren't even in front of a computer. And, you need to stay OUT of the details (code) when you're designing... even if just a stand-alone method.
(But most of your stuff is great Jeff!)
Lyndal on May 8, 2009 5:39 AMFor significant pieces of work I think whiteboard, design docs, TDD or pairing works best - pick your favourite - but I like to take the following approach with small tasks, like writing a single routine or a new feature:
1. Pseudocode
2. Write the real code
3. Improve code until it expresses my intent as clearly as the comment does
4. Delete the comment
Thinking in code is all well and good, but isn't there a risk you tie yourself to a particular implementation before you've had a chance to think it through?
Matthew on May 8, 2009 5:43 AMI write out the pseudocode, write out the python code, and then once the code is written I delete the pseudocode since the python code looks just like it.
taj on May 8, 2009 5:54 AMYour pseudocode looks like python
Coder on May 8, 2009 6:20 AMAlthough its a matter of preference jeff but i think we cant underestimate the power of pseudocode (keep in mind english is not my native language). I still beleive that this is one of the power full and natural tool to think towards programming problems.
Programming is another name of solving problems, when we try to solve problem how it should be solved pseudoprograming come as native citizine to it.
I admit that we usually sit directly down to the keyboard but i often find myself scribbling on the paper after a while to confirm or clear my complex logic. so i think this is like unit testing which is rather tedious to use but fruitefull at the end.
Pseudocode has its place. I find it useful only when developing complex algorithms that would be difficult to simply straight-up code (i.e. algorithms whose polynomial-time efficient solution is not directly obvious).
Writing pseudocode for anything else seems silly and IMHO a waste of time.
A guy on May 8, 2009 8:03 AMI use pseudocode because I don't have the intricacies of the syntax memorized, just the logic of the language.
I leave the pseudocode in because I'm better at reading English.
Kelsey on May 8, 2009 8:05 AMI have used pseudo-code, but not often.
Mainly when I'm figuring out a tricky algorithm or complex interaction, to clarify my thinking.
I hardly ever use it when I'm doing development where I have a good general idea of what the architecture is going to be, and where the majority of the code is going to be wiring things up.
What would be the point?
nexusprime on May 8, 2009 8:09 AMOn certain complicated new implementations, I'll regularly write comments before any code, right in the editor or IDE. If the process that needs to be followed is somewhat difficult, I'll explain each major step with a comment and move on.
This helps me to be certain that I've got the flow right before beginning a lengthy coding session. Once all my comments are written, I'll add the code under each comment and any methods that are required by that one block. Maintaining a flow of work without having to think too hard about the specifics of what comes next before it's time to tackle it.
So I reject psuedocode, but I'm all for comments before code when tackling a difficult problem.
`Josh on May 8, 2009 8:12 AMExplaining what the code does is completely redundant. Actually, the boss gets upset if he's paying to have the same code written twice...
---
// set the default status to fail
Status errorMessageStatus = Status_Failure;
DUH! This comment should state WHY the errorMessageStatus is defaulted to fail:
// default to fail in case we fall through the if logic below
Status errorMessageStatus = Status_Failure;
---
// look up the message based on the error code
Message errorMessage = LookupErrorMessage( errorToReport );
No Kidding? Really? Is that what that line of code does? (The authors self-documenting code skills are really showing through!) Still, how about something helpful here:
// Notes: All undefined errors return Undefined error.
// LookupErrorMessage() will EndProcess() in test case #4.23
Message errorMessage = LookupErrorMessage( errorToReport );
---
// if the error code is valid
if ( errorMessage.ValidCode() ) {
Is that comment helpful at all to anyone? How about:
// Invalid error codes are RARE! If you find one, please
// build a new test case and reference that case here.
if ( errorMessage.ValidCode() ) {
---
// determine the processing method
ProcessingMethod errorProcessingMethod = CurrentProcessingMethod();
Uh, not too helpful. How about:
// Error handling is different for GUI, CLI and library mode
ProcessingMethod errorProcessingMethod = CurrentProcessingMethod();
---
I'd actually prefer to see most of this code without the comments - it would be much easier for me to read since it's very self-documenting. But, and I know this is just an example, as far as I'm concerned, the only really important block of code here that warrants a comment is:
if ( errorProcessingMethod == ProcessingMethod_Interactive ) {
DisplayInteractiveMessage( errorMessage.Text() );
errorMessageStatus = Status_Success;
}
If I was maintaining this code, I'd sure like to know the technical/business rule behind this one...
Comments should explain, to the greatest extent possible, why the code is implemented in the first place. Every development effort should be justified in some form.
I really loved reading and re-reading CC - but I never embraced pseudo code. Thanks for this discussion, now I know why!
Jupiter Dude on May 8, 2009 8:42 AMI never read Code Complete, but yes, sometimes I write pseudocode.
One of my lecturer in college teach basic programming with pseudocode. She call it 'my language'. We wrote algorithm (in a paper, not computer) using a set of predefined words, so it's not too pseudo after all. But it make a good programmint teaching tools, because we can understand what this code do.
When I write code for work, I put comment in pseudocode for function or section that I will implement later, but I have the idea now, how the code will work. For the function I implement right away, I don't always put comment, but when I put a comment, it in pseudocode form.
Donny Kurnia on May 8, 2009 9:16 AMfirst
Raphael on May 8, 2009 9:17 AMThere's something fundamentally.. unrealistic.. about attempting to using precise English to describe the nuts and bolts of code.
Don't mean to nitpick, but isn't there a grammar error here? Shouldn't it be use and not using?
Figured I'd point it out. *ahem* [/nitpicking][content type=useful]
I don't usually write Pseudo code in that style. Rarely do I ever write it in anything other than C. However, I do typically find it useful when dealing with corporate-level projects with lots of classes and object oriented programming and things. Mainly, it lets me examine the logic of what the functions are *supposed* to do, in order, and think properly about restructuring the whole thing to either make it faster, or more maintainable.
I've recently had the pleasure of starting a giant project (an OS kernel) and one thing I'm making sure to do is document the entire process before writing a single line of functioning code. Sure, I've got a basic bootdisk running right now with some barebones stuff, but my teammates and I have agreed to document what the big picture needs to do (and discuss logic) before getting involved in the mess of code that this project is sure to become.
For small projects or simple routines? No way would I use Pseudo code. I don't even really like to use it on larger projects unless I really don't quite understand what the routines needs to accomplish. If it's a concept that I'm just re-iterating *again* in the language of the hour, there's no point really.
Pseudo code (and other high-level design concepts like flowcharts, ugh, don't even mention flowcharts in the same city as me or I'll shudder) has always come across to me as a big corporation of business men trying very hard to end up with code from their developers that they might be able to either (a) understand themselves, or (b) pass on to other developers with minimal friction. From one good coder to another, that level of deep, intimate commenting isn't necessary, since good developers should be able to quickly make sense out of even poorly commented or written code, TheDailyWTF notwithstanding. Again though, just because I haven't used it and don't prefer to use it (I'm very much a straight to the code sort of guy) doesn't make it bad practice, this is all just my personal opinion from my experience.
Nicholas Flynt on May 8, 2009 9:23 AMI kind of dismissed it as a way of adding a lot of totally redundant comments to code when I first read CC.
Why not focus your efforts on making the comments you do need really good rather than adding comments for stuff that should be self-explanatory in code?
If you like to document your methods I think maybe writing up the Javadoc ( or whatever the .net equivalent is called ) comments before you create the method may offer similar benefits ( and indeed greater ones in terms of IDE discoverability ) and avoid the unnecessary redundancy. I would be more likely to do that than to dabble in pseudocode.
Breakfast on May 8, 2009 9:24 AMDo you write pseudocode before writing code?
Both. At once.. Python \o/
dbr on May 8, 2009 9:27 AMAt my first job, when we were working through new functionality, we'd go up on the whiteboard and everyone would be talking about what was necessary before we sat down to write the code. It was a pretty good way to get everyone on the same page, and make sure we didn't forget anything.
I still do the same thing now - the other day I was designing new SQL tables, and I went to the whiteboard to draw each table, elaborate on its purpose (to myself), and define the relations between them. It also helped me be more certain about all the fields the tables would need. And then it was easy to look at the board as I'm working in Management Studio actually building the tables.
Adam V on May 8, 2009 9:29 AMI use it very sparingly, usually when i'm having trouble previewing the code I'm about to write in my head.
I guess that means I'm still better at thinking in my native language than in code.
Manuel Padilha on May 8, 2009 9:29 AMPseudocode is one of those things I haven't touched since college. I tend to think like you do in that sense - I want my code to be as self explanatory as possible.
On top of that, I'm much more prone (to my demise) to sit down and start writing code than I am to sit down and think through the problem/solution to the point of writing pseudocode. And even when I do, my _pseudocode_ looks like nothing more than modified _regular code_ (calls to functions with parentheses, etc.)
Joe on May 8, 2009 9:29 AMI use pseudocode only when working on an algorithm/business logic that is not strait forward. Good for telling my team leader this is how I will do it.
ANaimi on May 8, 2009 9:32 AMPseudocode is something we all had to learn in computer science... and then quickly discarded as impractical.
It's excess overhead left over from the days when debugging was extremely difficult. When you only had limited time on the mainframe it made sense to try to get everything perfect the first time. Now it makes sense to try to get pieces work at a time and grow the product in iterations.
Trying to code everything up front with pseudocode only works if you know everything you are going to do before you write actual code. Usually what happens is you write the code and then change your design as the picture becomes more clear.
Practicality on May 8, 2009 9:33 AMI'm with you Jeff, code is usually clearer and quicker to write for these kinds of purposes anyway.
BUT, I have had cases where very difficult problems were easier to solve in pseudocode-- because jumping straight to code made me feel like I was really trying to write the final code rather than think through the issue. This is rare though..
Joe L on May 8, 2009 9:34 AMWell, I was never a fan of Pseudo code until today. This is a really interesting way to do more stuff in less time. I guess i should go on an grab a copy of this book!
Mansoor on May 8, 2009 9:35 AMIt's good for a particular kind of function: one that's neither trivial, nor really hard. If it's trivial, it's a waste of time. If its actually hard, then you need to actually design it.
But if you find yourself starting a function that needs a little bit of thought, PPP is a quick way of, essentially, writing an outline. An outline (or pseudocode) is very good at focusing the brain on the parts of the problem you don't actually know (yet) how to solve. No painting yourself into corners.
And as for comments first or last, I find writing comments after code to be boring drudge work, while writing them first is not; perhaps you need to think of each comment as prefaced with And now, Ladies and Gentlemen, I shall... and enjoy the imaginary applause. YMMV.
Mike on May 8, 2009 9:35 AMI see one other benefit to PPP: someone with some technical expertise can write pseudocode, without needing to know what language the code will actually be written in. This can be useful when writing a technical specification without knowing which language will be used, or reusing the same technical specification if during a project it is deemed necessary to use a different language - even for part of the project.
That being said, I am not a fan of PPP. I think like you Jeff - in code. It's probably considered really bad practice, but I actually prefer to simply write code WITHOUT a technical specification. I can work this way, if required, but, in all my experience with technical specifications, there are so many variables (for lack of a better term) once you actually sit down and start writing code. Even small pieces of code end up not working according the specification when attempted - i.e. someone writes pseudocode for a validation script, and then when it's handed off to the developer, the developer realizes that the validation logic has already been written in an existing class, and that can be used. Stop what you're doing! Gotta go back and edit the spec! I feel it just slows down the whole process - and why?...so you can have this pretty document that describes the code??? Just look at the code!!!
Sorry, I get worked about this stuff....
Eric Belair on May 8, 2009 9:36 AMGreat article! I've given it a try before, and while the idea seems really ingenious, I just found that the pseduo code based comments seemed really obvious.
I feel like having a good use case and proper domain analysis in combination with small function sizes, refactoring (when needed), and verbose variable/method names goes a long way in making code easy to follow.
I think if comments read too much like the code then it's a little pointless having them there.
Of course, everyone does it a little differently. :)
Eagan on May 8, 2009 9:37 AMI use pseudocode as I need it: to help map out complex processes and for the problems that stump me. But, if I take the overall tone of Code Complete correctly, pseudocode isn't something that absolutely has to be done all the time for every line of code because it can be impractical in the long run. I'll sometimes even mix pseudocode with actual code when it comes to functions that I commonly use as a sort of shorthand while brainstorming. Everyone has their own style and Code Complete, I think, allows for a wide variety and using pseudocode is no different.
Philip Regan on May 8, 2009 9:39 AMIt seems silly to have these two lines together
//look up error message
LookupErrorMessage(...)
Any programmer would be able to realize that is the purpose of the line.
However, I have found that writing comments can help a programmer in the future (including myself) figure out what is going on. Often I will have a comment that says what a block of code (not just a single line) is doing. So, if it took 6 lines of code to look up the error message, then that one line comment would allow someone to essentially skim over the next 6 lines of code (unless if they are looking for a bug that exists in that block).
I think that as long as comments are meaningful and kept up to date, they do more good than harm, but there is nothing worse than inaccurate or out of date comments.
Brian on May 8, 2009 9:39 AMI haved used it with success only when writing very dense code. It makes no sense for most code, but sometimes the algorithm stresses your ability to keep all the relevant information on your head at the same time.
For example when writing low-level concurrent code or code that deals with transaction boundaries. I've also used it for code that, while not involving concurrency, had many special cases that have to be considered (i.e. implementing type inference in a compiler).
JC on May 8, 2009 9:40 AMPsuedocode is only important in that it forces you to think about the high-level design. I have seen many programmers fall into the trap of going directly to the low-level and never understanding the basic purpose of what they are building. It does not have to be psuedocode, but IMO, making some kind of high-level design document is a requirement in business software development. It also helps people keep grounded, and to not stray too far from the original design. I've seen a lot of cases where programmers didn't take the time to understand a possible solution for their problem, just started hacking away at it, and ended up with bad code that doesn't really meet the need. I see this a lot in SQL, with both the database design, and the queries and stored procedures, and the database is the foundation of your software - taking a little extra time to get it right can't possibly be a bad thing.
Jasmine on May 8, 2009 9:40 AMI started learning a little bit about programming just for fun, and I found myself actually using this thing you're calling pseudocode. I've never taken a computer science class or anything.
I found it useful for coming up with ideas on how to write a program before I knew how to do half the things I wanted to do. I wanted to make a bunch of stuff, but I hadn't yet learned how to do everything, so pseudocode was the only way I could write down what I was thinking.
LearningNerd on May 8, 2009 9:41 AMOne thing to keep in mind is that modern languages tend to be pretty powerful. Someone made a sarcastic comment above about Python being both, but really, lots of languages like the C# code I write looks that way.
Think about whatever coding task you're currently working on, then imagine what it would take to implement the same thing in C. Pseudocode expansion would make a lot more sense.
Clyde on May 8, 2009 9:41 AMStrangely I had almost exactly this situation today at work. I was working on an algorithm to solve a problem I had and I thought 'I'll write this is pseudo-code' so fired up a text editor and started typing. Pretty soon though I realised I was actually writting (Delphi) code, just with a slightly freer syntax to allow me to get thoughts to screen as quickly as possible. The translation to real code will be, obviously, trivial - just making sure I've got variable names right etc.
Mark P on May 8, 2009 9:43 AMI use pseudocode. But, I think you are mistaken, in that pseudocode needs to be very muck like english. Pseudocode can and often make more sense to be a simplified mix of english and code that states what you are going to accomplish and how. Now this is not needed in all functions, that would be over kill. Rather for higher level functions, that are going to be call on other functions to do the work. I use pseudocode to outline what need to be done and what those functions are. Write the code, and then write the other functions. Though I use vim and tend to do top-down development. I can see PPP being more useful in this style, then bottom-up as most IDE force you to do (http://charlespetzold.com/etc/DoesVisualStudioRotTheMind.html).
Gautam D. on May 8, 2009 9:43 AM
I knew exactly why you didn't like PPP the minute I starting reading this blog entry. Why? Because I disliked these ideas for the exact same reasons and I felt the same way when I read Code Complete.
Sadly when I refer back to the book now it seems very common sense. Although I have to say, there are many developers who just don't get it. Look around at your current code base and you will see what I mean.
I think in code when I'm writing code. When I comment something it is at the method/class/package level in the doc standard for the given language. Notice I said when I comment. Yes, I'm sick of working on projects with individuals who argue that they don't have time for comments. That said, other than complex algorithms or strange code barnacles I don't believe comments internal to methods are helpful.
Travis on May 8, 2009 9:45 AMI use a combination method. Write the parts in pseudocode that are complicated as code, and write the parts in code that are easiest as code.
In the above example, I'd write pretty much none of that as pseudocode, since the code is just as simple and legible. But all the potentially confusing parts extracted as separate methods. Namely:
LookupErrorMessage( errorToReport )
CurrentProcessingMethod()
DisplayInteractiveMessage( errorMessage.Text() )
If those were inline rather than separate methods, then you'd want comments to explain them. Or if the if statement had complicated logic.
Now, perhaps you have a programming style of taking anything that's remotely complicated and putting it into its own method or variable. In that case, pseudocode isn't called for, so long as the methods and variables are named appropriately.
David Leppik on May 8, 2009 9:46 AMI suppose a similar reasoning is behind the literate programming: don't bother to write pseudocode when you can write actual and exhaustive documentation around your code and get the code extracted automatically with a couple of tools.
It would be nice to read your take on literate programming if you ever give it a try.
maeghith on May 8, 2009 9:46 AMI'm a junior developer coming from a Sixth Form background in Pascal and a University background in Java, in a professional .NET environment.
I use PPP to have the general flow of a method from start to finish before writing the code. This is useful as a Junior as it helped with a brief review with other developers to make sure I was on the right track for my first bits of work.
I want my code as readable as possible, so having green (depending on the IDE colours) signposts throughout a method shows what it is doing, not how it is doing it. This makes the method readable at a glance.
I'll see how I go when I need to code more under quicker time scales; Psuedocode could be training wheels that come off when C# becomes as readable as English to me and whether these comments become redundant clutter.
When pair programming I find pseudocode to be helpful sometimes. Our pseudocode is a reduced version of the code. In the end the pseudocode turns into real code (rather than description). So our code would look like:
get objectslist
foreach object
if object is somethin
do this
else
do that
end foreach
This is way faster to type out when your discussing something with a colleague. Once you have agreed on the design, one programmer can flesh out all the variables etc. without keeping the waiting colleague involved in all the boring stuff. So yes, I actually do you use pseudocode when the going gets complicated.
Jan on May 8, 2009 9:49 AMActually, I tend to code that way too (never read CC). My one difference is that the last step, once everything is working, is to delete the pseudocode comments and put in proper comments.
T.E.D. on May 8, 2009 9:50 AMIt really depends on the complexity of the problem and how comfortable you are with the tools needed to solve it. If you struggle to read programming languages to begin with (e.g. if you are a beginner) then using psuedocode in design offers an obvious advantage. You can separate the solving of the problem from the writing of the code.
Its easy to forget just how hard it is for others to write code when you have been doing it for so many years that it flows naturally, just like writing in your native language.
In the work environment I would hope this would be the exception rather than the case... but then again, there is a ton of bad software out there.
Jheriko on May 8, 2009 9:50 AMI read the first version of CC many years ago and tried the PPP. I still use it today, although in probably a more abbreviated form that Steve McConnell suggests. However, I do find that once I start jotting down the comments on what to do, I have an easy time filling in the blanks. Also, just giving an extra minute of thought on the function I'm writing will often lead to a bit of design or refactoring that I might not have done had I just plunged into the coding. PPP is something that you have to try for a few days and see if you think it results in better code. Only then should you dismiss it.
Wandercoder on May 8, 2009 9:50 AMI'm firmly in the pseudocode sucks ranks. Let me digress a bit...
Have you ever written pseudo-math? At the basic arithmetic level, it works. You use it to teach children, to make arithmetic (and, therefore, mathematics -- supposedly) real to them, by relating it to things we can touch and handle (like OO, I suppose :).
Unfortunately, that ceases to be either practical OR helpful very quickly when you leave arithmetic.
It's important to note that mathematics as written today did not come to be because of an external constraint. No, the mathematicians could have chosen anything to represent what they write, and, as a matter of fact, the notation has changed through-out history and is still changing today. Calculus, as written by Newton, bears no resemblance to what you get taught today.
So, if there were no external constraints to how the mathematicians write their stuff, why do they chose a notation so un-natural-language-like? It was NOT because they needed to exchange knowledge. It's because natural languages are awfully inadequate to this purpose.
So, digression finished. I'm sure all of you got the point, but I'll conclude with a statement I have made in this very blog many times, and which always generate a backlash. Code is Math.
Using UML to design and comments to comment.
Only script kiddies who don't do real programming forget comments.
YOu might think your code is clear. But 4 years later when someone has to look at the code again, maybe the language has undergone changes, or even the next programmer just doesn't understand your pseudoclear code.
Work at bigger firms, you even are forced to do some level of planning, not just doing write once, trash it code
DawnOfWar on May 8, 2009 9:51 AMI read the first version of CC many years ago and tried the PPP. I still use it today, although in probably a more abbreviated form that Steve McConnell suggests. However, I do find that once I start jotting down the comments on what to do, I have an easy time filling in the blanks. Also, just giving an extra minute of thought on the function I'm writing will often lead to a bit of design or refactoring that I might not have done had I just plunged into the coding. PPP is something that you have to try for a few days and see if you think it results in better code. Only then should you dismiss it.
Wandercoder on May 8, 2009 9:51 AMBrian you said So, if it took 6 lines of code to look up the error message, then that one line comment would allow someone to essentially skim over the next 6 lines of code (unless if they are looking for a bug that exists in that block).
In this case I would do without the comment and create a 6 line method called lookUpErrorMessage(params...). Then not only is the code self commenting I could also use this method anywhere else I needed to look up an error message.
Richard on May 8, 2009 9:54 AMI hate pseudocode.
I prefer to actually write code.
At my job, the analysts have that bad habit of writing pseudocode instead of an analysis. Then, when you program, everything has already been thought for you (even function names,...), and you either have to try to understand what it's supposed to do, or just follow it blindly.
Not mentionning that everytime the program change, you have to change the document.
We have programmers that dont really program, they just follow pseudocode.
And when they try to explain to the client what the program's supposed to do, people who never programmed have to try to understand pseudocode!
Danielle PH on May 8, 2009 9:54 AMWe used pseudocode almost exclusively in my Algorithms class this spring. It seemed like a nice idea, but the problem we ran into is a professor with a very specific, very detailed idea of *what* pseudocode was. It was a defined language in her mind, which really hurt things. Still, I like the idea of developing pseudocode into comments...still seems to be a real problem with some people, adding little comments in there...:D
Charasan on May 8, 2009 9:55 AMHonestly, I think the most important part about pseudo code is that it is language agnostic. I don't recommend writing pseudo code for everything, because it is overkill for solving simple problems.
In general though it is great, pseudo code allows your to focus on the problem, not the implementation.I think that is the most important advantage it gives you when trying to solve difficult problems.
Mike Grouchy on May 8, 2009 9:56 AMIt's a personal preference, but it's one you Agile nuts seem predisposed against.
Corey Furman on May 8, 2009 9:58 AMI often write pseudocode when creating a new method. It helps me get my thoughts straight before writing real code. This is especially useful when I know I will be using API objects I'm not that familiar with. I can get the flow and logic down smoothly without having to interrupt myself finding the exact methods I need to call on the unfamiliar objects.
I don't generally use that pseudocode as comments, though, as I agree the code should generally be readable enough not to need such detailed comments.
Jim on May 8, 2009 9:58 AMHe Jeff
thank x for another great article , but don't u think Pseudo code can help programmers for e.g junior programmers to understand the Requirement more as they write the requirement themselved in the form of Pseudo code then they will understand the requirement more as Pseudo code can reinforce the requirement in their mind
Adeel on May 8, 2009 10:00 AMNope. I rarely need pseudocode for the simplistic events of our web application. It basically breaks down to request data, access the database, format data for display, display the data. In the rare occasions where more complicated processing is required I might use a post-it note to jot down some thoughts on the process, but I would never write it out in plain English because that seems like a waste of time.
I agree that comments should describe why/how the code works, not describe what it is doing step by step.
Jeromie Walters on May 8, 2009 10:02 AMMost things, I just write the code, but sometimes I have found it helpful to write out the process as pseudocode comments and slowly convert it to code. This helps for keeping things named well and removes the useless comments in the process.
Joshua on May 8, 2009 10:05 AMDo you write pseudocode before writing code?
basically NEVER. for the same reasons as you cited.
i've shared your view on that chapter in code complete.
Mike P on May 8, 2009 10:11 AMJeff, I think you really hit on something when you wrote I find it easier to think about code in code.
Programming languages are just languages, the same as French or Japanese. Just as with human languages, no one is going to write a masterwork (novel, essay, whatever) in a different language by writing it first in their native language and then translating it (even successful translations of major literary works require the translator to essentially re-write everything). So for experienced programmers using a language in which they are fluent, pseduo-code makes no sense.
However ... I once had an Education professor in college who, when discussing bi-lingual learning, related a story of when he was just an ESL (English as a Second Language) student himself. He said that he had real difficulty speaking English whenever he was on the spot, until one day his teacher put him on the spot, but said take your time; first think about how you'd say the answer in Spanish, then say it in English. That moment was a breakthrough for him, because it taught him that he could to use the language faculties he already had to help gain new language faculties. By the time I heard him lecture, he didn't even have a trace of an accent.
The point of the above is, pseudo-code is an incredibly important aspect of LEARNING a programming language (or a part of a language you previously weren't familiar with). Trying to do something from scratch when you're new at it is incredibly difficult, but if you can bring in some of your existing, wrong language skills (like your proficiency in English) and build on that it can be incredibly helpful in mastering the right language.
So that book had great advice ... it's just too bad they didn't specifically orient it towards new learners, rather than suggesting it's something programmers who have mastered their language should use.
Jeremy on May 8, 2009 10:14 AMI only use pseudocode for the most critical or complex functions. In simple, small, uninteresting functions there's no point in using pseudocode, if its written well enough the function name is all the pseudocode you need (if its not you're probably doing it wrong).
Some functions will be more complex or critical to the product. In the more important/critical functions I always use the pseudocode approach so it can be maintained easier.
JL on May 8, 2009 10:15 AMPseudocode really comes into its own when you're writing something in a new or unfamiliar language. When I'm not quite au-fait with the syntax and want to get my ideas down quickly and stay in that zone when ideas are flowing without the stop-start google / textbook consultation that comes with writing actual production code in a language you're not as familiar with.
evilliam on May 8, 2009 10:15 AMI do sometimes. My thoughts come all at once when I grasp a solution, and if I start implementation immediately I might lose something. But what I find much more interesting are all of the new ruby testing libraries like shoulda, bdd, cucumber, rspec, etc.
They are really innovating over there in rubyland.
1. write the behavior of what the code should produce
2. Write some code that turns those comments into tests
3. Start turning tests green.
You end up with comments that are USEFUL and do something.
Matt Katz on May 8, 2009 10:16 AMto clarify, imagine if someone was reading your comments or spec of your project and could tap you on the shoulder, saying This code doesn't do what you say it does.
Matt Katz on May 8, 2009 10:17 AMYears ago I had a programming assignment, and while waiting for a new PC and software to arrive I chose to pseudo code while riding the local subway, and hour in the morning and an hour in the evening.
The process forced me to do several things:
- think without typing (and without all the influences of a UI, language, etc.)
- iterate
- resolve
Needless to day, when I did sit down to code, many of the pieces almost coded themselves.
It is almost impossible for most people to code with pencil and paper when they have a computer on the desk!
Steve on May 8, 2009 10:17 AMOn review... What Jeremy said.
evilliam on May 8, 2009 10:17 AMNobody has mentioned Steve Y's take on this yet:
a href=http://steve-yegge.blogspot.com/2008/02/portrait-of-n00b.htmlhttp://steve-yegge.blogspot.com/2008/02/portrait-of-n00b.html/a">http://steve-yegge.blogspot.com/2008/02/portrait-of-n00b.html/a">http://steve-yegge.blogspot.com/2008/02/portrait-of-n00b.htmlhttp://steve-yegge.blogspot.com/2008/02/portrait-of-n00b.html/a
If you look back at the comments in my hypothetical code from 20 years ago, you'll see that I was...making up a temporal narrative in an attempt to carve out a mental picture of the computation for myself. These stories I told myself were a critical part of my mental development as a programmer. I was a child trying to make sense of a big, scary new world.
Most programmers go through this phase. It's perfectly normal.
MarcT on May 8, 2009 10:18 AMSorry, let's try that link again:
http://steve-yegge.blogspot.com/2008/02/portrait-of-n00b.html
MarcT on May 8, 2009 10:19 AMI occasionally use pseudocode to help me get my head around a particularly complex sequence of code. Or as sort of TODO: placeholder for code that I still need to write.
If I'm in C# or some other high-level language then the pseudo-code comments generally get transmogrified into objects and method names.
If I'm writing bit-bashing C or assembler then I leave them as comments.
Graham Stewart on May 8, 2009 10:20 AM@Charasan: same thing with my professor. In my Introdution to Informatics class I have to write pseudocode using a structure, just like I would if I were writing code. In fact, instead of writing a program in a computer, we have to program in pseudocode exclusively, writing it in paper (mayor PITA). Also, they don't even teach us C most of the time, they just tell you you see this statement in pseudocode? well, this is how you write it in C, and give us a C introduction book.
Alex on May 8, 2009 10:22 AMI don't use pseudocode per se, but I definitely strive to drop in comments before hand. It helps to organize and structure your design and thought process before you jump in and start spewing code. Writers do this all the time, they create an OUTLINE before hand.
Although I'm a strong believer in the concept that comments should describe the WHY not the WHAT. People can read the code to understand most of the WHAT, but having the WHY is important to people reviewing and working in your code base.
I do not use pseudo code, I'm much more in favor of semantic code. I like many others in this thread was taught pseudo code in University, and quickly discarded it as impractical.
I find that the biggest problem with pseudo code and excessive comments in general is that they act like a crutch to allow you to write poorly written code. If I have a whole bunch of comments explaining what I'm doing than the importance of writing clean semantic code is lowered, because you can simply read the comment to see what my poorly written code is doing.
The problem is that programming is a mindset, once you are thinking about the variables, objects, and syntax of a program it is jarring to have to refer to some string of english to attempt to incorporate that knowledge into the knowledge your brain is building about that code. It's like reading some beautiful python or ruby and then all of a sudden some inline FORTRAN is in there, sure you might know how to read FORTRAN just fine, but switching gears in your head takes some time and is an uncomfortable thing to do.
The other problem is that then you have to keep 2 models in sync, the code model of your program and the comment model of your program, it is very for these to become decoupled, compound that with writing inferior code because you believe that your comments make up for it, and wham, your code ends up on thedailywtf.com
just my $.02
Matt Nowack on May 8, 2009 10:25 AMFor those of us who aren't killer-code wranglers, this is an invaluable approach. I'm just a lowly sys-admin but I sometimes need to write some code and this gets me thinking in that vein, plus it comments my code. I find it really useful. YMMV.
Tim H on May 8, 2009 10:26 AMI find it easier to think about code in code.
Then you've entirely missed the point of PPP. The goal of writing pseudocode first is to think about your detailed *design* before you think about the code needed to implement it. PPP helps to clarify what you want to do before you actually implement it. It's a tool that supports a particular process of thinking.
Now, different people use different thinking processes for different problems. I'm a big fan of PPP for much of my own work - it helps a lot when I'm writing business logic, to make sure I really understand the logic before it's implemented (the comments are a nice side-effect, not the goal) - but I don't always use it.
Certain problems are easier to think about if I follow the plan to throw one away model instead. I write code as a way of thinking about design; then I write fresh code that implements that design.
Darren on May 8, 2009 10:28 AMI think the comment above about C# is a pretty fair one. Pseudocode is probably a really good idea next time I'm using x86 assembler or C++/ATL but in a good langugage suited to the domain I'm working in, like C#, or Python, or Ruby, or even Java, the level of the natural-language sentence is similar to the level of the actual code.
If I needed to, for example, call IUnknown, then call into ATL to make a COM call, then put the result into some data structure, then decompose the structure into the variables I want the results in, then I'd definitely want to put some pseudocode in to make sure I remember what I'm doing. Given that's the equivalent of one ordinary call into the System or Windows namespace in .NET, I'd just write the function call in C#.
Richard on May 8, 2009 10:28 AMI guess I never really thought of it as Pseudocode. But I use it all the time when I’m thinking about other things at work, home, or other. It helps me work out what I want to do, when and if I ever get to do it when I’m at home.
But I do not actually use it in my code it’s more of just a large mental note in an email.
Tim Meers on May 8, 2009 10:33 AMI do this on occasion, though I didn't know it had a formal name. For me, the value is not in the end result (which is, admittedly, code that is littered with comments of questionable value).
The value in it is that it allows you to design and plan your algorithm / block of code at a higher level, without getting caught up in the nitty-gritty syntactic details.
For example, it would be perfectly acceptable to say something like this in your pseudocode:
append array A to B, eliminating null values on the way
In pseudocode, that's a one-liner, single step. Understandable. But if you try to do that in code, you suddenly get lost in the details: I have to extend the length of array B, possibly by creating a new array and copying all of B over, then reassigning B, then going through each element of A to see if it's null and... Wait, why am I doing this again?
I like to compare this technique to the XP pair programming technique: in pair programming, the driver is in the details, the navigator is looking at the slightly bigger picture. By pseudocoding first, I perform both roles serially.
Jeremy on May 8, 2009 10:33 AMI'm about like ANaimi... I don't always use it, but often it's a helpful abstraction when I'm tackling a particularly complicated task, because it helps me to identify discrete subtasks that can be modularized, the precise order of those subtasks, that sort of thing.
But even my pseudocode tends to look more like actual code (usually C-like) than it does English prose.
Ryan C on May 8, 2009 10:35 AMYour example shows the basic problem of pseudocode: if it goes to any detail, it is actually *longer* than the code it describes: your example is 814 characters pseudocode to 378 characters code (without the comments).
Te idea of pseudocode originates from a time when coding involved a lot more bookkeeping and copy+paste code (Code Complete is from 1993; in the early 1990s, I was still sometimes writing assembler, and usually C).
Markus on May 8, 2009 10:35 AMI find it easier for myself to do Block diagrams of code, at least larger functions, before hand on paper. I find it more efficient, and you have something in front of you that you can always refer to or revise on the go (If done in pencil, I mean is that how everyone does it?)
pferland on May 8, 2009 10:35 AMI've used pseudocode lots of times, it's very valuable when the sequence is complex or involves a lot of things. You start mentally drawing what you have to do without worrying whether each line will be a function call, a statement or just any other line of code.
Some complex algorithms require this mental image. If you later delete the comments that is ok, but it can help a LOT in many circumstances.
At least it did (and does) for me.
I think a flow chart works better than pseudo code and it's both more readable (to everyone) and less ambiguous. It's a bit more work but it's more valuable as documentation.
Pseudocode has its use for helping you wrap your mind around a problem, but i don't usually feel the need to write things down to make this work - unless it's a lenghty and complex problem, though if this is the case then it's a sign that you need to break the problem down into its components and think about each one separately - divide and conquer.
Job on May 8, 2009 10:37 AMThis is only a preview. Your comment has not yet been posted.
As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.
Having trouble reading this image? View an alternate.
| Content (c) 2009 Jeff Atwood. Logo image used with permission of the author. (c) 1993 Steven C. McConnell. All Rights Reserved. |
Posted by: |