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?
first
Raphael on May 8, 2009 8:17 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 8:24 AM> Do you write pseudocode before writing code?
Both. At once.. Python \o/
dbr on May 8, 2009 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8: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 8:51 AMThere is a middle ground! I use this approach when the problem is complex:
Write the main bits of code -- as Steve suggests -- but using real code and subroutines which don't yet exist. When you like the flow, write the subroutine headers and doc. Then write the subroutines.
This is nice because:
1. The reader of the code has a compact, high-level method explaining what's going on.
2. It's easier to change the high-level stuff.
3. It's easier to unit-test the parts.
4. You don't need comments because the method names can usually be self-explanatory.
5. It's all "real code."
Brian 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 8: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 8: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 8: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 8:56 AMIt's a personal preference, but it's one you Agile nuts seem predisposed against.
Corey Furman on May 8, 2009 8: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 8:58 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 9: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 9:05 AM> Do 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 9: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 9: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 9: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 9: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 9:16 AMI will write test snippets in a console app or test web app, or I'll briefly outline proposed logic in a notebook, but I never write pseudocode as described above.
Jon Sagara on May 8, 2009 9: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 9: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 9:17 AMOn review... What Jeremy said.
evilliam on May 8, 2009 9:17 AMNobody has mentioned Steve Y's take on this yet:
<a href="http://steve-yegge.blogspot.com/2008/02/portrait-of-n00b.html">http://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 9:18 AMSorry, let's try that link again:
http://steve-yegge.blogspot.com/2008/02/portrait-of-n00b.html
MarcT on May 8, 2009 9: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 9:20 AMI find that if I try writing pseudo-code - I refine it and refine it and end up with - guess what? Code!
Neil Barnwell on May 8, 2009 9: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 9: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 9: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 9:26 AM"I 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 9: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 9: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 9: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 9: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 9: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 9: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 9:37 AMI use pseudocode often for "medium" sized problems with procedural complexity. I.e. problems that certainly need some subroutines, but not complex enough to justify UML designing.
Pseudo code is just another way to make you feel more secure at what you're doing by boiling a few hundred lines of code down to something you can grasp. On a good day you don't need it, on a bad day you're grateful for all the help you can get. Just like pair programming.
As for leaving the pseudo code in comments - depends on whether it adds information to the code. Meaning if it's a good comment it stays, but not for the sake of keeping pseudo code.
That is actually about the only thing I regularly use from the book. I work in a partnership with a non-technical person, and we can both work in sentences. Then it's my job to turn those sentences into code.
I love it. The comments actually help me a lot when I take the time to really do it.
Anyway, works for us.
Morgan on May 8, 2009 9:46 AMI suspect McConnell suggests this because writing comments forces you to verbalise your solution. If you agree that you don't really understand a problem (and/or its solution) until you can put it into words, then you must agree this approach is worth something.
It's something I do myself: write down in your editor (as comments) what the code _should_ do then gradually turn the comments into real code. You'll probably delete most of the original comments along the way.
Obviously if the code is simple enough to be written straight off then you don't really need to do this.
Trevor Johnston on May 8, 2009 9:48 AM(didn't read all other comments...) Code should be as difficult to read as natural language. That's because: 1> code is language and 2> there is nothing "natural" about natural language. Systems of references, both. Current programming languages are awkward...
marcio brk on May 8, 2009 9:55 AM> Do you write pseudocode before writing code?
yes, when some n00b compsci student brings me his class assignment and i find it challenging yet i don't wish to spoon feed him. of course after writing the pseudocode i lose all interest in the program because after pseudocode, there is nothing else to do but type.
also flowcharts help in this alot.
i find pseudocode a means to think aloud when i can't concentrate
jake on May 8, 2009 9:55 AM> Do you write pseudocode before writing code?
yes, when some n00b compsci student brings me his class assignment and i find it challenging yet i don't wish to spoon feed him. of course after writing the pseudocode i lose all interest in the program because after pseudocode, there is nothing else to do but type.
also flowcharts help in this alot.
i find pseudocode a means to think aloud when i can't concentrate
jake on May 8, 2009 9:56 AM> Do you write pseudocode before writing code?
No. I practice TDD, so my tests help me with my design, not pseudocode.
> Pseudocode makes reviews easier.
So does tests. You look at the tests and you know exactly what code should do.
> Pseudocode supports the idea of iterative refinement.
> Pseudocode makes changes easier.
> Pseudocode is easier to maintain than other forms of design documentation. With other approaches, design is separated from the code, and when one changes, the two fall out of agreement.
It's really interesting, that all these things can be said about writing tests (whether practising TDD/BDD or else). And with the named downsides and upsides, that other techniques possess, there's no reason to choose PPP.
I can see how pseudocode was a more useful technique, when programs were written in C and other lower level languages though.
> Do you write pseudocode before writing code?
No. I practice TDD, so my tests help me with my design, not pseudocode.
> Pseudocode makes reviews easier.
So does tests. You look at the tests and you know exactly what code should do.
> Pseudocode supports the idea of iterative refinement.
> Pseudocode makes changes easier.
> Pseudocode is easier to maintain than other forms of design documentation. With other approaches, design is separated from the code, and when one changes, the two fall out of agreement.
It's really interesting, that all these things can be said about writing tests (whether practising TDD/BDD or else). And with the named downsides and upsides, that other techniques possess, there's no reason to choose PPP.
I can see how pseudocode was a more useful technique, when programs were written in C and other lower level languages though.
> Do you write pseudocode before writing code?
No. I practice TDD, so my tests help me with my design, not pseudocode.
> Pseudocode makes reviews easier.
So does tests. You look at the tests and you know exactly what code should do.
> Pseudocode supports the idea of iterative refinement.
> Pseudocode makes changes easier.
> Pseudocode is easier to maintain than other forms of design documentation. With other approaches, design is separated from the code, and when one changes, the two fall out of agreement.
It's really interesting, that all these things can be said about writing tests (whether practising TDD/BDD or else). And with the named downsides and upsides, that other techniques possess, there's no reason to choose PPP.
I can see how pseudocode was a more useful technique, when programs were written in C and other lower level languages though.
Mindaugas on May 8, 2009 9:58 AM> Do you write pseudocode before writing code?
No. I practice TDD, so my tests help me with my design, not pseudocode.
> Pseudocode makes reviews easier.
So does tests. You look at the tests and you know exactly what code should do.
> Pseudocode supports the idea of iterative refinement.
> Pseudocode makes changes easier.
> Pseudocode is easier to maintain than other forms of design documentation. With other approaches, design is separated from the code, and when one changes, the two fall out of agreement.
It's really interesting, that all these things can be said about writing tests (whether practising TDD/BDD or else). And with the named downsides and upsides, that other techniques possess, there's no reason to choose PPP.
I can see how pseudocode was a more useful technique, when programs were written in C and other lower level languages though.
Mindaugas on May 8, 2009 9:59 AMI pretty much never program anything without using pseudo code. If you are using it at the level of one line of pseudo code to one line of real code you are not getting any benefit from it. Look at it as outlining. In fact, I use an outliner to organize my thoughts and to help me break down complex problems. That outline ends up being my pseudo code. Some of it will end up as comments and some of it will not. The majority of my pseudo code is at the level of a method or higher. The more complex areas of functionality might have several lines of pseudo code.
I'm sure that you have written notes down about something you want to create. Even if you write it down in C# you most likely will take shortcuts and not jot down complete syntax. That is pseudo code and I believe most programmers do it, even if they don't call it that.
Bruce
Bruce Atkinson on May 8, 2009 10:02 AMI use pseudocode rarely, almost always in complex routines, when I need to work out exactly what needs to happen, it helps me sort out the logic ahead of time.
Matt on May 8, 2009 10:05 AMWhen I was learning, this is how I used to deal with programming big blocks of code that I didn't understand. I wrote my first linked list walker/sorter in commented pseudo code, then added the code. It just works for me, but I can see why it would drive some people nuts.
Gary on May 8, 2009 10:11 AMI do this all the time for particularly complicated pieces of code. Except I don't write it as "pseudocode", I just write what I intend to do as comments, one thing per line and then fill in the code below each line.
That way I ensure that I say what the code DOES instead of how it does it.
DMB on May 8, 2009 10:15 AM"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?"
val c = (a ++ b).remove(x => x == None)
That was pretty straight-forward and clear to me. Now, if I were to implement the append and the remove functions right there, it would be a serious problem with the level of abstraction.
So, perhaps, there's one more reason to avoid pseudo-code. Maybe it obfuscate such problems.
Daniel Sobral on May 8, 2009 10:21 AMI use pseudocode for tracking flow - before I get bogged down in the implementation details, I trace out what's going to happen, and make sure that everything goes in the right place. I find code is great for "what", comments cover the "why" (which is usually where the problems are).
A Gould on May 8, 2009 10:23 AMThe problems with pseudocode and other less code and more english programming techniques is that human languages do not do well in describing algorithms or other programming concerns. If they were, we would have real natural language programming.
In my experience, I often write 'almost code' which in most cases is very close to final code, and with additional comments to where human level and environmental concerns are not reflected well enough in the language. After I am satisfied with my design, meaning that I believe I have a good structure, have validated my interfaces, and have adequately reflected the algorithms, I then make a pass or two through the code and bring it up to real code and make additional changes headers, comments, etc to conform to whatever standards the project uses for its walk-throughs.
This way I have tailored my efforts to reflect the way I work most efficiently, but recognize that fairly early in the process, I need to communicate the results to others. Usually nobody is completely pleased with project coding standards, but when the size of the programming staff is greater than one, a common compromise must be used.
When I return to old code, either mine or someone elses, it is surprising how often that when I have problems locating an error, running a copy of the code through a tool that removes comments results in my reading exactly what the machine is doing rather than what the original programmer thought was happening and enables me to locate a previously hidden logic problem.
In both cases (producing new code and maintaining legacy code) I accomodate project standards as well as job realities while allowing me to work the way I have found to be most effective.
As far as maintaining pseuodcode or other detail design works, after 30 years of programming, I have yet to be on a maintenance project that provided me with pseudocode level documentation. I rarely even have been given high level design documentation. When detailed design documentation is available, it has never been kept up to date.
Literate coding with short explanitory comments when necessary are the best tools for effective maintenance targeted documentation. Boiler-plate comments and pseodocode are useless.
"I prefer coding without comments, in that I want the code to be as self-explanatory as humanly possible. Don't get me wrong; comments do occur regularly in my code, but only because the code could not be made any clearer without them."
Although I agree PPP is overkill, I find comments like this hard to justify.
Every day I see very complex blocks of code with no comments what so ever. When I ask a fellow programmer why they aren't commenting they give me this same line. "Comments take to long, easy to read code is better than commenting"
Then 6 months later we find a bug that I am assigned to fix. I ask the original programmer what the complex block does. They have no idea. They will have to study it for 10-30 minutes to wrap their head back around what they where doing/thinking at the time.
Code is always easy to understand 1 minute after you write it.
Code that took you spent several hours/days planning and writing will seem very logical at first.
It may not be quite as obvious to the next guy who comes in after 6 months without the knowledge of everything you learned in the planning stage.
DaveNCheez on May 8, 2009 10:25 AMI use this fairly regularly although many times the pseudocode doesn't stay around as comments in the final version. I use it as a design tool to help lay out the process I'm trying to achieve in the domain space before translating it into nuts and bolts of code. It helps to lay out the general flow of the solution and discover any area you may not have a clear picture of yet.
Since most of my coding projects these days are for myself and pushing into areas where I'm still learning, I find it easier to write out the general plan first and then dive into the details of how to actually accomplish it.
In addition, most of my coding is done in a high interrupt environment, either at home (kids) or in between meetings and other distractions at work (I'm a manager now and me producing code is fairly low down on the priority list, that's what my superstars are for). By laying the work out in pseudocode first, I can get the design done up front and then spend my short bursts of time available for coding on fleshing out the details without loosing the big picture.
Tom Stephens on May 8, 2009 10:26 AM>> So does tests. You look at the tests and you know exactly what code should do.
No you don't. The issue of how the API behaves is somewhat orthogonal to how the code behind that API works. It can be full of bugs and spaghetti code and still return the right thing to your particular test case.
Besides, tests I've seen from TDD proponents usually don't even cover half the branches in their own code, don't test for exception safety or concurrency, don't test failure recovery. They just test each piece of their code under the most optimal circumstances, just to verify that the code is there and when right parameters are passed in it does something. They never venture into those catch blocks, never abort the thread while test is in progress, etc.
If you've started your career as a tester (as I did) - that's weak sauce. We were expected to WRECK the system, and wreck it we did. I've found probably thousands of super-critical bugs that would never have been found through TDD. In one particularly nasty case, the system would just hang after running happily under load for two days due to the developer non-atomically decrementing a counter in his thread management routines and causing an integer underflow. To investigate, I had to dump the RAM and look at the disassembly in the debugger. How do you find this through TDD? If you can't find this through TDD why even pretend that your code is bug-free?
DMB on May 8, 2009 10:27 AMwhat is with the double posting? @jeff!!!
jake on May 8, 2009 10:28 AMThough, of course, it does not correspond to the pseudo code, which says append A to B, not B to A. That's a bug, though. :-)
Daniel Sobral on May 8, 2009 10:29 AMI often do this, though the pseudocode/comments are only for me to remember what it is that I'm trying to accomplish along the way. It takes no time at all to put down some sentences about what I'm trying to accomplish in English and then flesh out the code afterward.
Sometimes the pseudocode ends up as a comment but often it is deleted as it is clear what the code does.
I use it mostly as a checklist of what I'm hoping to accomplish in the function. The details of how I'm going to do it aren't essential initially when I'm thinking through the design.
itsmatt on May 8, 2009 10:31 AMI do this if I'm writing a function complicated enough that I can't hold every step in my head simultaneously. First just write out each step in a way simple enough to fit into a one-line comment, then fill in the space below each comment with the code for that step.
If you end up with only one line of self-explanatory code for a comment then I can always just delete the comment when I'm done. If the code is somewhat more complicated I leave it in as a useful summary of what that block does.
If a block gets really long/complicated or shows up more than once you extract it out into its own function.
fdghdfgh on May 8, 2009 10:31 AMIf you debug by reading comments, you are doing it right. I'm tired of finding bugs where what the code DOES and what the comment says it's SUPPOSED to do don't match. And, of course, no one can find it, because they have read the comment, so they misread the code into doing what it was supposed to.
That's why I never read the comments when trying to understand what a code does.
Sure, document what the code should accomplish, and why. But never get into the how, because the only how that matters is
Tilton's law, learn the damn language.
http://smuglispweeny.blogspot.com/2008/07/now-batting-dave-roberts-why-is-mariano.html
I remember I was once reverse-engineering a file format, and wrote some code to test things (read specific information off the file), apart from a textual spec.
The other guy who was working on the project saw what I had committed to SVN and said
"I really hope you understand what all that pseudocode means"
"oh wait, it's python"
Indeed it was.
Nicolas on May 8, 2009 10:35 AMI use it sparingly, usually in relation to implementing an image processing or numerical operation.
I'll also admit that I usually delete my original pseudocode comments and write the algorithm out in the method comment
Peter Tate on May 8, 2009 10:36 AMI often code this way, except I don't call it pseudo code, I call it English (insert spoken language of choice here). When I go to write a routine and if I have much of the reasoning already worked out, I'll quickly commit those thoughts as a series of comments. Sure, I've been writing code for a long time but I still can't write code as fast as English.
Sometimes I start writing code first if the the code is quite straight forward but there's always times where I change my mind about the approach or I realize an additional bit of required logic. In this case, I'll quickly jot down some more comments so that the new and current lines of thought aren't lost.
It is true that the resulting comments mirror what is often unambiguous code. The purists generally don't like this but I firmly believe that code alone only tells you what it does, not what it is supposed to do. So I write what it is supposed to do first.
capar on May 8, 2009 10:40 AMCucumber lets me write pseudo code which is used for testing. So I suppose writing pseudo code is part of what I do :)
GaViT on May 8, 2009 10:41 AMWhen working with any code that isn't obvious I try to comment the hell out of it, explaining the "why" and sometimes the "how" as much as I can. I have found that if I have to explain something to someone else I force myself to think about the topic in greater depth and learn/analyze it better. Good commenting is just explaining aka I analyze what I am doing in a greater depth. Its like pseudo-peer review in real time.
Jason Jackson on May 8, 2009 10:43 AMI'm like most others here. I'll write pseudocode if I have trouble wrapping my brain around it... but then I put the pseudocode in the ide, write the function below it, translating each piece of pseudocode into real code, and then I delete the pseudocode.
Steve-O on May 8, 2009 10:46 AMAgreed. Pseudo-code is very impractical. All those layers of documentation may make sense for an ISO, but for your average small to mid-sized engineering house, it generates too much overhead.
Personally, I like comments, but only to a point. I generally comment modules (i.e. file headers), functions, and branch statements. Other than that, I agree with Jeff; code should be as human-readable as possible.
Jim on May 8, 2009 10:48 AMAs an afterthought, I do write pseudo-code when I'm doing low-level debugging of someone else's code, so I guess it has a place, albeit limited.
Jim on May 8, 2009 10:51 AMI don't like pseudocode either. It was extremely useful when I was a beginner, but afterwards it did me no good. It simply wastes time for me nowadays.
And I really don't like having comments that word the code below them.
Stefan Kanev on May 8, 2009 11:01 AMComments that can be made wrong with minor code cleanup suck. Design documents that have to be changed frequently suck. Trying to reason about formal subjects using only informal notation sucks. Writing the same thing in two very similar ways sucks.
(Yeah, I know, you want to know what I really feel.)
Yes, I'm prejudiced. I went for several years with systems analysts thinking that a buggy program written in some sort of pseudocode (actually, they used bastardized decision tables) was an adequate spec for a real program that was actually supposed to work. (Look, guys, I'm the expert in converting specs into programs. Tell me what the program's really supposed to do and I'll make it happen.) I was, of course, responsible for any bugs put into the low-level stuff by the analysts, and not given enough context to know they were bugs.
I've seen vast arrays of entirely useless comments, which were no more clear, and gave no different information, than the code. Heck, I used to do that sometimes, before I knew better.
I've seen comments that described what the code was doing, and been specifically warned away from them, as they were misleading.
Pseudo-code has its uses. It's good for algorithms books, for example, since it ages well. (I've got a book with routines written in Fortran - excuse me, FORTRAN - and APL. Pseudo-code would be nice.) It's useful as scaffolding in working out a routine, WHEN DONE BY THE GUY WHO'S DOING THE PROGRAMMING.
But don't use it for design reviews. It's low-level and untestable, and can be ambiguous. Don't use it for comments. That's something I'm just going to have to ignore when maintaining the code, and besides it gives the code the look of commented code, so nobody will put in the actually useful comments. Don't use it for specifications. It's on the exact wrong level of abstraction.
David on May 8, 2009 11:02 AMI think the theme here is to think about what you are doing before making your cuts. Or like my dad the carpenter says: "Measure twice, so you only have to Home Depot once".
I consider the contemporary version of "write psuedocode" to be story->task decomposition->tests and discussing with my pair what we are trying to accomplish.
Jason on May 8, 2009 11:06 AMI have been known to use the pseudocode approach. It often works great for algorithms, but not much else :(.
Joshua on May 8, 2009 11:07 AMPseudocode has always just been a language-agnostic way of conveying algorithms and data structures to me. I can't imagine actually writing it out unless I was trying to explain something to somebody who didn't code or coded in another language.
Taylor on May 8, 2009 11:09 AMSure, this is stupid:
// lookup the user id
id = lookupUserId();
But that's a straw man.
What's meant by PPP is this:
// update the widget on all the ones that matter
for (iterator i=things.begin();i != things.end();++i) {
if (i->isCurrent() && i->isImportant() && ! skipList.has_key(*i)) {
i->updateWidget();
}
}
When doing the pseudocode, you can skip over the details about EXACTLY what "ones that matter" means. As long as you are confident that it CAN be determined which ones matter, then you can go on to worry about whether widgets should be updated before or after the foobars are pruned.
Once in a while you discover that you can't update widgets before OR after foobars are pruned. At that point, you are only 60 seconds into writing the function and you need to look to see if there is a better solution. PPP has improved your efficiency.
Of course, if you never write code that has subtle issues like this, you are either working in a very simple domain, or you are much smarter than me.
Mike on May 8, 2009 11:16 AM> > Do you write pseudocode before writing code?
>
> Both. At once.. Python \o/
+1 :-)
Anthony Roy on May 8, 2009 11:37 AMI completely agree with Mike V. The most useful thing for me with new functionality is the whiteboard. It gets you and your co-workers on the same page and saves a lot of time.
The whiteboard is also invaluable for teaching programmers new to the code base how everything works in real time.
Jonathan R on May 8, 2009 11:38 AMre: Steve on May 8, 2009 09:17 AM It is almost impossible for most people to "code" with pencil and paper when they have a computer on the desk!
I used fullscreen editors for 17 years (starting in 1972) before giving up paper and pencil for onscreen programming. It is much more than the difference for an author moving from longhand to a typewriter.
I often used a 4 sheet of paper working style: Initiation, Termination, Data, and Processing logic. Even if I could have 4 files open at once, my screen size didn't make it useful to see much of all 4 at once. As I added code to the processing logic that required another variable, I added to the data sheet. If I added a file, I added to the data, initiation, and termination sheets.
re: Pseudocode
In communicating programs, it is useful to document what is not visible in your code, namely what message or action of the peer or network this piece of code is in reaction to. That is the why or when.
It is worthwhile to document a custom protocol in the comments.
In some code I once put a warning: "If you do not know what the peer can do and what the communications return codes mean, do not tinker with the next page of code." Years later, in a code review, I saw the same warning and the unchanged code in a totally different program. Of course, I was flattered.
As a warning to future newbie improvers, the following comment makes sense for languages without early termination of logical expressions:
If (k = Int(k)) And (0 < k) Then ' do not combine these IF's to avoid using a noninteger subscript
If (pfacts(k) = 0.0) Then
:
:
End If
End If
I'll usually write pseudocode if I'm sitting down with a piece of paper and/or talking about it with someone. It's alot easier to jot down a word or two than to start coding while carrying on a conversation. It doesn't make it into the comments but sure helps go over the design when talking it over with another developer.
Ryan Clare on May 8, 2009 11:42 AMThis is a very strange argument, pseudocode and self-documenting code go hand in hand and are in no way replacing each other. One tells you clearly what the code SHOULD do, the other tells you clearly what it DOES.
The example given is perhaps a bit extreme, but consider the benefit when you come across this subtle error in the code:
// if doing interactive processing, display the error message
// interactively and declare success
if ( errorProcessingMethod != ProcessingMethod_Interactive ) {
DisplayInteractiveMessage( errorMessage.Text() );
errorMessageStatus = Status_Success;
}
With only the code to look at it might take you ages to spot the error. The difference in the pseduocode and actual code makes it much easier. If this wasn't technical but instead pseudocode describing an obscure business rule, you might never realise that the code was doing the opposite of what it was supposed to.
So - Pseudocode is awesome, McConnell FTW! ;)
Pseudo code feels like it's more for academics (and something you learn at class in university, but actual programmers don't use it pretty much) and people who can't code (and often that means the same thing).
I can think when you revert to pseudocode is when you can't program in the language (or at all).
Fuck all things that aren't actual programming - everything else sucks, except actual working lines in your application!
Your wikipedia Tang lang is broken - it's missing the starting " at the href=.
configurator on May 8, 2009 12:10 PMThe thing about code is that you cannot always make it completely clear without comments, which is why programming languages have comments in the first place! I write code with comments like you show from Code Complete, but I write them afterwards. This has helped even myself understand what's going on months later.
kinghajj on May 8, 2009 12:23 PMThis reminds me of my recent job interview, where I came to the realization I have no idea how to write good pseudocode. They asked me to write something to go through a linked list and check if it is looped or something of that nature, and I started scribbling out some nonsense that looked like I combined 5 programming languages with a new brace syntax and stuck in some English words for good measure.
It seems I can either go to a very abstract level and write almost a paragraph describing the code, go into a very specific level and write the code itself, but trying to find the right level of abstraction in the middle for pseudocode is difficult.
Plus, there is no "standard" for pseudocode. Everyone writes it a little bit different, which makes using it to show another developer your ideas often more difficult than just showing them the code.
PherricOxide on May 8, 2009 12:27 PMI am often complimented on the readability of my code, and I use very few to no comments. In modern languages they are not necessary. In the way olden days (and I am dating myself here) with single letter vars, you had no choice but to comment. Long procedural blocks also need commenting since you could forget what all the moving parts were doing by line 5000.
Nowadays, if a routine is so convoluted that it needs comments your time is probably better spent fixing the code than writing a comment to explain the mess.
I suppose I occasionally write pseudo-code when I'm sketching out a non-trivial routine. But they are just placeholders. They don't end up in the final code at all - not even as comments. Just like sketching, those light lines are eased as the picture starts to take form. They are usually replaced by methods with expressive names.
The example from Code Complete is a violation of DRY. The code already says what it does.
Matt Lentzner on May 8, 2009 12:28 PMI think it's a valuable tool to have in your toolbox, but it's not applicable to everything. I use it when I'm writing a routine that's finicky, with a lot of details that I need to keep in mind. For example, when I was writing the stack-based implementation of a recursive serialization algorithm, I used PPP to outline the details before starting so I wouldn't forget any of them.
However, I switched to C# from C++ (mostly C with a C++ compiler) a few years back, and I can't remember doing it since. It may be that the domain of problems I'm working on require less of that kind of precision, but it also might be due to using a higher level language where I don't need to concentrate as heavily on managing memory and error codes, leaving me able to maintain the overall algorithm in my mind without the assistance of psuedocode.
Nicole DesRosiers on May 8, 2009 12:51 PMI typically design functions with pseudocode with paper and pencil, but never include them in the actual on-screen code.
Aston on May 8, 2009 12:54 PMI 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 1:11 PMI 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 1:13 PMWhen 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 1:16 PMThe 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 1:25 PMWith 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 1:27 PMI try to minimize comments by refactoring code into useful pieces. Python is writing pseudo while programming indeed !
Mohammed on May 8, 2009 1:30 PMWe 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 1:38 PM
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 1:40 PMI 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 1:40 PMJob interviews? Are you kidding?
Psuedocode isn't a "best practice" for output but for planning and for overview documentation. I use pseudocode now and then with great success, but a job interview is the last place I'd ever think to benefit from pseudocode.
As you made it clear that you understand, pseudocode does make for some good commenting. Jeff, if you think your code is highly readable without comments, congratulations; however, you are not the appropriate judge for your own code. You should always assume that, no matter how proud you are of your own work, someone is going to look at your legacy and hate your work, simply because the process of understanding code by reading code, when there are no comments to explain, makes it more difficult for some people (even if not you) to digest.
I use pseudocode (but only on occasion) only because sometimes I just need a brain break and I want to look at the problem from a problem domain perspective rather than from a syntactical perspective. I ask myself questions like, "What's the ultimate end goal here?" "How can I break this down into generalized steps and conditions?" "How can I break it down further into logical detail?" I answer these questions in pseudo code, typically in comments right up front, and then yes, I start writing code for each line of pseudocode.
Why do I do this? Because the questions about the world's problems don't boil down to code. Only the answers do.
Jon
Jon Davis on May 8, 2009 1:49 PMI 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 1:55 PMI 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 2:00 PM
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 2:34 PMGood 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 2:51 PMWhat I have found most pseudocode most useful for is actually not designing new code, but for figuring out existing code that has not been commented, or very minimally.
More specifically, at my work we have HUGE amounts of COBOL code that is up to 20 years old and is still used and maintained. It is VERY ugly, and can be an absolute nightmare when trying to figure out what exactly is going on in files that can be thousands of lines long. Using pseudocode as I trace my way through these old programs has always helped tremendously in trying to figure out what these programs are doing since the original authors are not around and documentation is very limited.
Obviously, this is a different method than what the book proposes, as I am not using it to design initially, but it has been proven to be very useful none the less.
Jaywon on May 8, 2009 2:52 PMI 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 3:00 PMI'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 3:10 PMSometimes 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 3:23 PMAs 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 3:31 PMI 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 3:37 PMCode 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 3:54 PMWow, 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 4:39 PMFor 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 4:43 PMI 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 4:54 PMYour pseudocode looks like python
Coder on May 8, 2009 5:20 PMAlthough 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 7:03 PMI 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 7:05 PMI 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 7:09 PMOn 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 7:12 PMExplaining "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 7:42 PMI 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 8:16 PM"There'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 8:23 PMHe 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 9:00 PMI 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 9:35 PMPersonally, I am not really a fan of pseudocode -- it is like a programming language with ill-defined syntax and semantics. If in doubt, you have to guess what the author really meant.
Instead, I prefer code written clearly, with "real" variable and function names (not grmblPsft()-style). The example you've given illustrates this quite well: the pseudocode comments do not contain significantly more information than the C version. Of course, you could have written it like this:
st err_stat = fail_st;
Msg err_msg = err_lk( err );
if ( err_msg.vld() ) {
pm err_pm = curr_pm();
if ( err_pm == pm_i ) {
i_msg( err_msg.str() );
err_st = succ_st;
}
In that case, extensive comments and pseudocode would have been useful lest we have to guess what each variable, type, and function means. That's why I like the rationale behind Ada's somewhat more complicated (as opposed to C) syntax: code is written once, but read many times; so it should be easy to read, not necessarily easy to write.
That said, I am a sysadmin, not a full-time developer. I write the occasional small utility, and I dig through other people's code hunting for bugs; but requirements may be different when working on large projects.
kirjoittaessani on May 8, 2009 11:14 PM"I find it easier to think about code in code."
But you shouldn't be thinking about code. You should think about logic at that point.
Vinzent Hoefler on May 8, 2009 11:33 PMTo me, it kinda seems like when you are learning a new human language: When you are starting out and are not that proficient you actually translate the things you say, write, hear and read back and forth from the foreign language and your own. But when you get proficient in the other language you actually think in that language as you are speaking it or writing it, just like I am doing right now. Not only is this faster, but it allows you to use the language in a "better" way, taking advantage of the grammatical possibilities it offers.
This is the same with a computer language: When starting out it may be nessecary to think in terms of human language, but as your skill increases you start "thinking in code" and this is when you really can call yourself a programmer.
Jens J on May 8, 2009 11:50 PMI do use pseudocode for complicated algorithms.
BUT
I remove comments after it's done. Such comments aren't just useless, they're dangerous when code gets modified.
I think this reason for pseudocode:
"Pseudocode makes changes easier"
is not as strong an argument if your coding environment has strong refactoring tools.
Jeff Odell on May 9, 2009 1:24 AMI've been doing this for a while, and it works well.
I usually don't keep the Pseudocode after I've written the actual code because it rarely actually describes the code I end up writing.
Pseudocode allows me to write out an algorithm that makes huge assumptions, leaves parts out and only makes sense to me, but it allows me to quickly put a process down without having to think about how I'm actually going to do it(i.e. which libraries, classes, API, variable names, function calls, types etc. I'm going to use).
An example would be something like:
get image
get hist
get image
get hist
compare hists
if threshold
which is a function that compares the histograms of two images and does something if the difference is above a certain threshold.But to
anyone that isn't me it makes no sense.
- Jessta
Jesse McNelis on May 9, 2009 1:33 AMI do not have a great debate about using pseudocode. The design problem I am confronted with dictates whether I employ this technique or not. I am not conscious of making a decision to use it or not. When I have used it I have found it that is has helped me to understand the problem more fully, to winkle out issues and assumptions that may have not have been visible if I had started to write code without reference to any previous thought. My pseudocode is not always a strict formal English. I usually delete the pseudo comments as they are mostly, for me, replaced by self-commenting variable and function names etc with the usual conventional provisions.
One thing I have noticed is that it does not encourage thinking about any constraints. These constraints may be domain related or code related. However, I always think about constraints as a matter of habit.
Pseudocode is mainly used for method or function design. I can see no applicability for it in class design where I employ UML. Good class design is difficult; creating a good class library more so. Pseudocode has no jurisdiction here as it is not OO.
Simon Parmenter on May 9, 2009 2:15 AM"I find it easier to think about code in code."
I think most programmers get to this point. But for somebody learning how to code, it seems to work reasonably well, and I use it in my intro programming classes. Students don't think better in code, and learning to express an algorithm on paper, before writing it, is useful. It also allows them to paper-test the algorithm before committing it to code.
"It'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."
This is exactly correct as well. In the example in the post, pseudocode is used as almost a line of pseudocode to one line of code mechanism. That i9s fine in very early stages of learning how to program, but eventually, that is overkill. However, it can remain useful as a higher-level design technique beyond this. 1 line of pseudocde per function call (or inline block of code) can make sense. When done this way, the pseudocode becomes a task list - a high-level skeleton to ensure that you don't forget something. And if the pseudocode really does end up simply marking a function call, than I am all for removing the comment and making sure that the function call is properly self-commenting.
coderprof on May 9, 2009 3:15 AM"Do you write pseudocode before writing code? "
No. But I think today's refactoring tools makes Steve's arguments less relevant. (I love Steve’s book, myself, but the way: See http://geekswithblogs.net/btudor/archive/2009/04/05/130772.aspx).
You can “stub-out” real code easily in a modern editor, leaving “Not Implemented Yet” blocks for the details. You can add implementation later, restructuring the code as needed.
The skeleton/stub code is good enough to review, and easy enough to extend.
I don’t tend to write much pseudocode myself, and would agree that PPP is overkill for most functions, but I do tend to think in pseudocode – think about what I want a function to do, then fill in the details with code. If you don’t do this, you are no thinking about “code in code”, you’re thinking about function in code – starting with the how do I do something rather than the why.
But, preferring to code without comments? Talk about technical debt. I’ve spent too much time trying to maintain code written by developers who thought their code was self-explanatory (including my own code). If code could always “tell the story” bugs would not exist.
My view of mixing pseudo code comments with code is that this in best
case is a learning tool for students, although I am not so sure that
it is a good one because /writing good comments is just as difficult as
writing good code/[1], and unless the person is fairly skilled you end up
with crap like
// Increment i by one
i++;
In my opinion there are three ways to write code:
a) Write unreadable code
if (read(...) == -1)
b) Write unreadable code, and (try to) comment it readable
if (read(...) == -1) // -1 == EOF
c) Write readable code
#define EOF -1
...
if (read(...) == EOF)
Very often single line comments fall into the b) category and could easily
be transformed into c) by better naming or refactoring. Example:
// check if xxx already exist
found = false;
for (i=0; ...; i++) {
/* 5-20 */
/* lines */
/* of */
/* code */
}
instead of
static boolean find_xxx(...)
{
/* 5-20 */
/* lines */
/* of */
/* code */
}
...
found = find_xxx(...);
Comments should be used as a last resort, when it is impossible to directly
express the content in the source code.
[1]
I am BTW 100% sure that Jeff first wrote the code in his example and then
afterwords inserted suitable pseudo code comments.
I often have serious concentration issues so I use pseudocode a lot. It is much easier for me to keep on coding without forgetting what I am doing when there's high level pseudocode to look at. But I never leave pseudocode itself there as comments.
AnonymousGerbil on May 9, 2009 4:52 AMWe were forced to write PC in high school. I really hated it and found it non practical.
samirbenabid on May 9, 2009 5:26 AMI usually don't write pseudocode before coding, but sometimes when I'm working on complex code, I do just that.
Patrik on May 9, 2009 6:13 AMYes, when the problem is larger than what I can code straight off.
Many of the pseudocode lines are statements of *what* the code should do, and they become "title" comments which state what the following section is supposed to accomplish... not the "how", that's what the code is for. For a maintenance programmer, having a clue about what the original programmer was trying to accomplish is a first step to understanding how the code works.
Other pseudocode lines are shorthand "how", and they don't survive as comments; they morph into actual code.
Sometimes, pseudocode lines become procedure/function/module names that are called... another example of morphing into actual code.
Self-documenting code is always the goal, but... we work with 3rd generation languages mostly, where the code is an expression of "how", not "what", so comments about intent/purpose/desired results are often valuable.
And yes, it has worked for me for decades.
Breck Carter on May 9, 2009 9:07 AM> Do you write pseudo-code before writing code?
On a never-ending re-brand and redevelopment project, I have found myself taking business rules from paper to pseudo-code and from pseudo-code to flow charts before actually rewriting the process.
I have found the logic in the actual coded process to be horribly inefficient, and not worth the time to code to that then fix it.
It has helped me immensely in understanding how the website currently functions and how to improve upon what it has under the hood.
Jeremy on May 9, 2009 9:55 AMI tend to code first, comment later. When it comes to anything conceptually hard to code, I puzzle it out in iterative pseudocode first, coding what I am certain to be correct at each stage.
Groxx on May 9, 2009 10:06 AMI use this method for the hard things, the things where I have to think about how the problem is to be solved. I start a method, and then jot down notes in it, as comments. Then I just leave them in place and code to them. And yes - a lot of the time, it will suggest what I'm working on needs to be further broken up into more routines.
I agree on having your code be as self-explanatory as possible, and 'commenting to the exceptions'. Definitely a good practice.
Rick! on May 9, 2009 11:25 AMMore helpful than pseudocode to me is a simple English description of exactly WHAT a procedure does. I like to keep that separate from HOW it does it, for which I use code + comments. If you think about it, we designed programming languages specifically to express the HOW better than English does.
A. L. Flanagan on May 9, 2009 11:55 AMNever used pseudocode - it just seems like a wasted step, when it is so close to real code anyway! I've never seen a colleague use it either. People feel (right or wrongly) that it's "babyish"!
Magnus Smith on May 9, 2009 12:02 PMMost of the time, no, I don't. I'm another who codes to keep the code as readable without comments as possible - if that means slightly longer or less efficient, then so be it. Neither are usually anywhere near as critical as maintainability.
Occasionally though, I will do exactly this. As a rule it's too much but there are some odd problems where I find it far simpler to sketch out an idea to help visualise that, and a comment block is a great way to do that.
The other thing that can be worth playing with is doing this at the block level. Particularly with VS.Net I'll often code merrily away to all sorts of unwritten functions, then write their XML comment blocks before I start coding as notes for where I was heading. Saves me having to worry about all the bottom up funcationality and just code big pictures, in the knowledge that the bottom up blocks are there to be filled in as needed.
Greg Webb on May 9, 2009 1:18 PMI don't use pseudo code per se, but sometimes I write code as if the libraries I am working with worked the way I want. Easy example, go have a look at how you create render context in GL. http://www.nullterminator.net/opengl32.html . What you might really want is something with a bit less nonsense:
glCreateContext(width, height, bitdepth, hasDepthBuffer);
Such a logical function doesn't exist, but I might code as if it did anyway. If I get over-focussed on bit flags and tokens, I might spend half an hour creating the context, and completely lose focus on my algorithm. Once I've got the algorithm coded up or at least roughed in, I can go back and fill in the details, possibly actually writing the utility functions that I wished existed in the first place.
Nick Porcino on May 9, 2009 1:35 PMAs a computer science instructor and practicing software developer, I find that psuedo-code at the early stages of programming education is almost essential. It just becomes less so, as one gains experience.
The biggest issue is see is that new students are trying to learn both syntax and semantics at the same time (if they are just thrown into a language). Though it's something that becomes intuitively obvious to the experienced programmer, many beginners really tend to confuse the two concepts. Forcing them to write pseudo-code first is just really forcing them to think about the organizational details before tackling the syntax and implementation issues. I always tell my students that learning to write code without learning to properly plan is like tying to learn a song you've never heard on an instrument you've never played.
At least at the early stages, pseudo-code seems to be about the best way to plan, and then the code can evolve from that plan. As you gain experience, you learn how to "plan in code" with greater precision.... Just like as you gain experience with musical instrument, you eventually stop thinking about where you fingers are going and just play the notes.
Long ago and far away, when I was a young, young guy, I sometimes wrote pseudocode. I found it helpful for stepwise refinement, especially in Pascal. I still find it useful for languages like Lua, which is very powerful semantically but is like a syntactic straitjacket, especially when it comes to looping constructs. But I really just treat it as a more powerful form of code than what I actually have available at the moment. No need to put that stuff in a comment. Comments are for what problem the code is intended to solve and why I did it *that* way.
Norman Ramsey on May 9, 2009 4:16 PMI don't know what TDD/BDD tools exist for C/Java-family languages, but we use RSpec and Cucumber for writing tests on our Ruby projects.
Cucumber is great because it is similar to writing business logic statements that can then be translated into code. I used to write pseudo code, because thats what I was taught in College, but now I write Cucumber feature tests instead.
jtimberman on May 9, 2009 7:04 PMYou should re-read the portion about programming "in" a language vs. programming "into" a language.. Of course pseudocode is of no value with trivial methods.. and this is could be a good chunk of your code.
The interesting thing about my job is I am often trying to solve problems I have not already solved 100 times before..
When switching between languages, using a new API, or implementing a complex algorithm, you should be thinking about *what* you are going to do before you think about *how* you are going to do it. If you are thinking in code, you are still programming "in" a language..
1. Silly comments replicating the code nearby (or its names) are silly.
2. Pseudocode & comments aren't synonymous, although the former may be transformed or incorporated into the latter.
3. Totally agree with Andy Roublev on
"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)."
Any complex matter I need to work on (product code, test code and even debugging of product/test failures) begins from figuring out:
- what is actually wanted/needed
- the knowns
- the unknowns (things to investigate further)
The above gets expressed in whatever way is appropriate for the problem:
- lists of items to take care in various places at various times in the design and implementation
- pseudo code
- flow charts/block diagrams (state machines naturally need these)
- math or whatever other domain specific language (DSL) is necessary or useful
I admit it to myself and I'm not embarrassed to tell it to others: I don't have superpowers and I accept my natural limitations as a human:
- how many things I can keep in my mind at once
- how deep/far I can go into something, how many steps ahead
- where I am likely to make a mistake
- that it's easy to fall for wrongful and unquestioned assumptions
- that I don't know something
And I find ways around these limitations, which makes me a better programmer.
I try to:
- familiarize myself with the problem at the high level
- get as much of the necessary info/details upfront as possible
- ask questions or seek for other forms of clarification, where things are ambiguous
- plan figuring the remaining unknowns
- organize the acquired knowledge in a structured and logical way permitting me to:
- quickly navigate in it
- understand the prob from top to bottom or bottom-up
- have the details handy and reduce distraction
- keep track of the progress
- implement the damn thing
Trivial and simple things don't need much of the above. But when you go nontrivial or the problem becomes intractable due to its size (I think 30KLOC would be it already), you clearly need to be more serious and organized. Else you miserably fail.
Anonymous on May 9, 2009 9:27 PMI don't know, but i feel Pseudocoding when TTD'ing.
darnell on May 10, 2009 12:25 AMI have to disagree with your decidedly negative statement concerning writing pseudo code.
As a sophomore Computer Engineer, I have found that pseudo code has helped me on many occasions to obtain an overall framework for the project that I was about to commence.
The flow is simple, and allows for a basic form of debugging in the very beginning. Remember, if your logic is flawed from the beginning, no code that you write will be able to "fix" your problems.
My 2 cents.
Austin on May 10, 2009 12:42 AMI think you misunderstood Steve McConnell. He never said to intersperse your code with code. What's would be point of that? He advocates writing the function first in _plain English_. Plain English is not pseudocode. Also, I'm pretty sure he advises to remove comments later if they turn out to be to close to the final code. There's no use in repeating yourself.
And yes, I use this technique for difficult code, and find it invaluable. I'm not a fan of the "it was difficult to write, it should be difficult to read"-motto, I think someone who has to read my code later should at least know what I was thinking when I wrote it.
Niki on May 10, 2009 1:09 AMLanguages are means to express your intent.
When I am writing this comment, for example, I think in English and I write in English.
Thinking in my native language and then trying to translate it to English would make both my thought process and the English boring.
Similarly, when you code, you “think” in the language you code.
Thinking in English and then trying to convert it to C# is lame. It makes both your thought process and the c# code that comes our boring.
It also makes the process of writting code much more time consuming.
I never see myself using pseudo code except when I interview candidates and there is a language mismatch. For example, when I am interviewing someone who knows only Java.
Other than that, I use it once in a while on white board to explain something to team members.
In that case however the code I scribble on the white board is more of C# in short hand rather than being true pseudo code or plain english.
Pseudo code is overrated. I think we should stop teaching it and start encouraging our programmers to think in the language of their choice.
Languages are means to express your intent.
When I am writing this comment, for example, I think in English and I write in English.
Thinking in my native language and then trying to translate it to English would make both my thought process and the English boring.
Similarly, when you code, you “think” in the language you code.
Thinking in English and then trying to convert it to C# is lame. It makes both your thought process and the c# code that comes our boring.
It also makes the process of writting code much more time consuming.
I never see myself using pseudo code except when I interview candidates and there is a language mismatch. For example, when I am interviewing someone who knows only Java.
Other than that, I use it once in a while on white board to explain something to team members.
In that case however the code I scribble on the white board is more of C# in short hand rather than being true pseudo code or plain english.
Pseudo code is overrated. I think we should stop teaching it and start encouraging our programmers to think in the programming language of their choice.
Languages are means to express your intent.
When I am writing this comment, for example, I think in English and I write in English.
Thinking in my native language and then trying to translate it to English would make both my thought process and the English boring.
Similarly, when you code, you “think” in the language you code.
Thinking in English and then trying to convert it to C# is lame. It makes both your thought process and the c# code that comes our boring.
It also makes the process of writting code much more time consuming.
I never see myself using pseudo code except when I interview candidates and there is a language mismatch. For example, when I am interviewing someone who knows only Java.
Other than that, I use it once in a while on white board to explain something to team members.
In that case however the code I scribble on the white board is more of C# in short hand rather than being true pseudo code or plain english.
Pseudo code is overrated. I think we should stop teaching it and start encouraging our programmers to think in the programming language of their choice.
rajiv on May 10, 2009 1:45 AMI don't write pseudocode in my own programming, but I use it extensively when teaching.
I encourage beginner programmers to use pseudocode to break code into manageable chunks, then write the code. The idea is that as you gain more experience, the chinks get bigger and the pseudocode reduces accordingly. I can plan and structure an entire method, or sometimes even an entire class, in my head. Beginners need to write it down and pseudocode is a good tool for this.
I also use pseudocode when guiding junior programmers. When assisting a junior programmer I could just write the code - it would be just as quick as writing the pseudocode. But if I write pseudocode and leave the junior to convert it to real code after our discussion then they are more likely to remember and learn from what I said.
Richard Lord on May 10, 2009 1:55 AM+1 for Both at once. :)
I both read and write c# faster than any kind of pseudo code.
hohoho on May 10, 2009 2:58 AMI pseudocode in comments and kind of "wireframe" the thing up before coding. It helps decouple the design process from the coding process which to me is A Good Thing. If I pseudo-code up a routine, other design options become apparent such as a need for different encapsulation, and logic errors or faulty assumptions show themselves before I have invested the time in writing the code.
Once the comments are there and the workflows are clear, the coding becomes that much easier because you are not iteratively second-guessing your design decisions as the bigger picture slowly reveals itself to you. I can also feel free to stop working at any time and come back to it later without worrying that I'll forget what I was doing. I like anything that encourages me to stop working. :-)
JimmyRu on May 10, 2009 4:11 AMIt's worth noting that this really only fits a particular right-in-the-middle size & scope of developing task.. If something is big and complicated, you do a more formal spec for it and start there. If something is small and trivial, you just do it.
JimmyRu on May 10, 2009 4:17 AMYeah, someone already said that pseudocode is something you'll only use at school. I think it has some use in algorithm design as well, but that's only because an algorithm happens to be a very clearly defined problem - it's somehow natural to go over it with a quick pseudocode before you actually do it since recursive functions and whatnots are sometimes pretty tedious to tackle straight on.
The idea that you should leave all the pseudocode as comments on your code is about the worst idea i've heard in a while - if you've ever read over commented code you'll know what i'm talking about. It's no longer fun when you have a comment on every other line of code (or worse for that matter). I mean who would like to read something like this:
// if a is greater than b
if (a > b)
This kind of thing only manages to serve two audiences - programmers and designers - but that's about the only upside i can see for it.
JPH on May 10, 2009 7:55 AMI have found pseudo code to be mostly useful to explain code logic to management who do not know how to read actual program code. For management who have had programming experience, they'd rather go through the actual code to know the exact truth.
Aaron Seet on May 10, 2009 9:00 AMWhen I first read this, I thought it was a great idea (I was a very junior programmer looking for structure). But yeah, it wasn't long before I came to realize it was completely impractical at least the way I interpreted using it.
But ocasionally, I will use it now. Usually if I have some huge process (stored procedures especially) where I want to nail down the process before I get caught up in all the details.
John MacIntyre on May 10, 2009 10:34 AMWhen I first read this, I thought it was a great idea (I was a very junior programmer looking for structure). But yeah, it wasn't long before I came to realize it was completely impractical at least the way I interpreted using it.
But ocasionally, I will use it now. Usually if I have some huge process (stored procedures especially) where I want to nail down the process before I get caught up in all the details.
John MacIntyre on May 10, 2009 10:36 AMThe major, major problem of pseudo-code is semantics. If you describe something (say, an algorithm) with a certain notation (say, pseudo-code, or flow-charts, or whatever), then you need semantics. What does "if error code is valid then dostuff" mean? Of course, by semantics of the english language, this means: "There is a condition hidden here, and whenever the condition is true, execute dostuff". In a recent lecture, this resulted in horrible misunderstandings, because the semantics of "return" appeared to be "output the value after the return and continue execution" after this. The result was a horrible misunderstanding with regard to the algorithm.
The usual way to obtain a semantic for this pseudo-code is by mimicing an existing language and using the english language semantics. However, given this, I second Jeff: It makes no sense to use pseudo-code, because pseudo-code will always look like an existing programming language, and well-factored code in a high level language (say, prolog, haskell, python/ruby) will look like pseudo-code. In fact, whenever someone asks me for pseudo-code, I write down a program in one of these languages (maybe with a bit of syntactic convienience, but usually, those could be eliminated with a simple preprocessor).
However, the deeper question is: Is there a need to have a better representation of complex code to reason about? I say yes, and yes, sometimes it is necessary. For certain compiler operations, for example, it is hilariously helpful to just draw two tree diagrams (before transformation, after transformation) instead of writing several pages of text about it. In other areas, a simple block diagram with a little statemachine next to it can help a lot. In other areas, a simple dataflow diagram will help a lot. The important thing to notice about all these representations however is: They are not trivially isomorphic to code. Take most pseudo-code, and it is fairly easy to write down the code for this line of pseudo-code. This is bad. This is very, very bad, because it means: pseudo-code is a very, very thin layer of abstraction, and thin layers of abstractions are just an obstacle. Given a dataflow diagram, or two trees and an arrow from one to the other, it is certainly not trivial to actually program this. This is a good thing, because apparently, the abstraction is big.
So, dont use pseudo-code, because it is a weak abstraction, use a good (ad-hoc) diagram to explain this. If you need the diagram more often, write down a little formal explanation of it and be happy :)
Yes i do.
Not a pseudocode mayb, but something like it. My coding "plan" is simple. First is simple model, comonnly on papers, shemas and pictures.
Then i create structure of desired code by comments. And finally - code.
And that's work great for me.
Pavel on May 10, 2009 12:18 PMWith agile, TDD and refactoring as more of a refined method of coding - instead of writing pseudocode, I write tests and descriptive code.
McConnell wasn't wrong, it's just that for the most part nobody writes monolithic C programs with mostly 1-letter variable names, so the notion of writing pseudocode has been superseded. The industry as a whole appears to have progressed, so pseudocode is of limited use now in this process.
Pseudocode however is still very useful when describing how code is supposed to work to a non-technical audience, or when describing algorithms in a language agnostic manner.
Bazark on May 10, 2009 2:25 PMIt reminds me of the academics walking though a new and very successful factory that was the brain-child of a student from the school of hard knocks who had no formal education.
They look at the unique factory layout, the novel machinery and employment arrangements. In the end they concluded “Oh yes, sure it works in practice, but it would never work in theory.”
Okay, that was fictional, but the point is that when someone becomes too academic they can start to focus on theory over practicality. So for the reasons Jeff lists, I agree with Jeff.
But from what I’ve read of the comments the conclusions are that the theory is sound, when placed into a practical framework. And that’s where I sit – I’m on board with the TDD camp.
I find that pseudocode is useful when you pick the right level of detail. When you think of all the things that you need to do and you write them down it helps ensure that you don't miss anything.
Sometimes psusedocode can be as simple as a TODO list that you fill in with code.
Doug on May 10, 2009 4:07 PM@dbr
Even more so: Erlang
Pseudocode only gets written in my Brain, which I translate to real code whenever I code - that makes is almost self-commenting such that few comments need to be added in the end.
Toukarin on May 10, 2009 8:51 PM
I found writing pseudo code useful when I have to write the complex routines. I do not use any formal method for it, I just use eclipse to do it.
I think we write the pseudo code when the complete code of the routine if not clear in our mind.
Pseudo code is only useful to me when I have "Coder's Block". I, like you want to think in the code then go back an add comments as needed to make my code clear.
Stephen on May 10, 2009 10:42 PM"Do you write pseudocode before writing code?"
Normally, no. If problem is not too complex, I only write my purpose as a comment, not the algorithm itself.
If problem is complex, I write pseudo code for a reference for only myelf and try to clear after implementing the real code.
In complex problems I mostly change my algorithm several times during coding; leaving pseudo code comments may misguide the posterior programmers, so I try to clear all pseudo codes and write comments for:
- What the following algorithm is purposed for
- Inputs and outputs
"Languages are means to express your intent."
Eh?
They are also the means by which to confuse and deceive.
How does one discern the difference when hearing the spoken language or reading it?
For the intent of any code use a specification.
Simon Parmenter on May 11, 2009 12:23 AMI love pseudo-code, it makes perfect sense to me. First you figure out at a high level what you want to do, in a feasibility study or a project summary. Then you break it down into logical chunks. Then you pseudo code parts of the program that aren't completely straight-forward. Then (or rather, throughout) you check whether what you are doing would work. This way you find 95% of design bugs during the design process, which is one of the most important ways to reduce project overruns.
Andrew on May 11, 2009 12:42 AMHi, Jeff
I think you are right if you say, that thinking about code is in code (not in plain english). At least for me. I dont write pseudocode to start coding, I rather write some of my comments in pseudocode while coding. Although I almost constantly draw class-relations, important methods and Membervars, while coding on complex problems.
MTZ on May 11, 2009 2:37 AMI've worked on a project with high assurance TCSEC (Rainbow Series) requirements. In part, this called for a low-level design; and basically this was a pseudocode representation of the entire product. This tended to be a duplicative effort for writing code. A consequence of this that I haven't seen mentioned is that it was also duplicative maintenance. If you actually make pseudocode part of your development process, you are "coding" twice as much through the entire lifecycle. In retrospect, I don't think that this duplicative effort delivered much value to the product.
I've read a variety of distinctions between code, pseudocode, and the resulting product. I would not consider pseudocode to be analogous to a blueprint. Software *is* built differently. I'd argue that the source code is the definitive low-level design for the product, and then it is sent off to the "compiler" to be built. Pseudocode isn't a common language (a blueprint is; so is a programming language), nor is it to any standard of detail (a blueprint does). More: the source code is the only definitive representation (next to the assembly code or RTL!) that exactly describes what the compiler will build. See also http://c2.com/xp/TheSourceCodeIsTheDesign.html
I won't completely disavow any value to pseudocode; it's a language-agnostic way to communicate code ideas; suitable for research papers and textbooks. Its value beyond this is, in my opinion, rather limited.
ALoyalReader on May 11, 2009 4:40 AMAnother vote for both at the same time using Python.
My process is usually to write pseudocode in Python syntax, then implement any missing functions/methods so the pseudocode becomes executable. Then write the tests to see if it does what I think it does (depending on the circumstances I also write some tests beforehand). Sometimes a bit of refactoring is also needed, but usually the resulting code looks pretty much exactly the same as the pseudocode.
I do use comments, but usually to specify the *why*, not the *what*. Only when I can't make the executable code as clear as the pseudocode I add comments that say what the code does, but that is a rare occurence.
Ants Aasma on May 11, 2009 5:04 AMtest of fuck
---
I use pseudocode like a lot of people here. I write out how the thing should work, I comment that, I find/build the functions to do what should happen.
fuck on May 11, 2009 5:39 AMI would go with the refining of the code one step fw and remove comments since now they are redundant, and get something like:
Status errorMessageStatus = Status_Failure;
Message errorMessage = LookupErrorMessage( errorToReport );
if ( errorMessage.ValidCode() ) {
ProcessingMethod errorProcessingMethod = CurrentProcessingMethod();
if ( errorProcessingMethod == ProcessingMethod_Interactive ) {
DisplayInteractiveMessage( errorMessage.Text() );
errorMessageStatus = Status_Success;
}
If this is the code you get from just starting writing code without any first pseudecode then this is great, you are a good programmer, you don't need pseudocode anymore.
But for beginners there is a great chance not to get to this one, and using first pseudocode then may lead them to the right code.
By "right" i wanted to say "readable".
Costin on May 11, 2009 5:44 AMi start off with code, then i refineit and expand it and refine it and eventually, voilà! a blog post!
secretGeek on May 11, 2009 5:53 AM
Pseudocode, no. English, yes.
I think everyone has pointed out the flaws with pseudocode. But the problem is not with the concept of writing out what your code will be doing. It is, as you said, that coders think in code. They cannot write pseudocode. They start structuring it and making it look like code, and then it has all the problems that people have already explained.
The problem isn't the concept of pseudocode. It is that we are all doing it wrong.
So I just write English. And it doesn't become comments for the code itself... it becomes the descriptive comments that outline what each function does.
Dave A. on May 11, 2009 6:43 AMI'm sure this comment will never be read, but for what it's worth, I do use pseudocode when I'm planning my work, but usually with PAPER AND PENCIL. Then I step back and run it in my brain, and optimize it for a few hours, before finally typing it as actual code. Pseudocode is the language I use for "mental simulation", and it's only needed for particularly tricky pieces of logic, or something that I haven't done before.
stebe on May 11, 2009 6:57 AMFor rapid prototyping, I prefer to use post-it notes (to symplozize modules, objects, core building blocks, whatever the other parties understand) and stick them to a flopchart.
Seems like a a stone age aproach but it is very efficient.
PPP: Tried it, arrived to the same conclusion as you. :)
Csaba Kétszeri on May 11, 2009 7:27 AMIf I have a big task that I understand in outline but
=>I know it will take days/weeks to code
and/or
=> I'll be handing it off to someone else to work on
then I start it in pseudocode:
if (important and complex condition) then {
mumble
mumble
don't forget to foo
watch out that the complex condition doesn't create a nested loop here
}
else {
need to bar
mumble
mumble
have I covered this use case?
}
Having mapped out the forest, I can start chopping down the trees one at a time. Better to map out the problem than to hope the solution fits.
dgrc on May 11, 2009 7:29 AMI must admit that I use this technique almost religiously. This was one of the single greatest concepts that I took from the book Code Complete.
I understand that lots of people don't like to code this way, but I think it results in better code. Just like most programmers don't like TDD at first once they get used to it it results in better code.
Anything that is high discipline takes away to get used to. "Hacking away" at code is indeed fun, but doesn't always result in the best code.
Billkamm on May 11, 2009 7:34 AMI find pseudo code particularly useful when I'm attempting to write a tricky algorithm into the design docs for for the benefit of some _other_ developer who's going to implement it.
(As our resident mathematician, it's sometimes my job to explain the maths to other devs, or to clients who will be coding in-house themselves. I can show the algorithm steps easily, in a readily-coded way, and be sure the other developer has understood what's required. But without actually having to prescribe someone else's implementation.)
Having said that, I agree - usually far too much work to use when I'm coding myself. Makes more sense if each pseudo-code line represents several lines of real code.
It makes no sense to do this:
// pseudo-code: for each dish
for each d in mydishes
// pseudo-code: wash dish
d.wash
// pseudo-code: next dish
next d
But it can be very useful to do this:
// pseudo-code: for each dish
for each d in mydirtydishes
// pseudo-code: put dish in sink
lefthand.pickup(d)
lefthand.moveto(over_sink)
lefthand.moveto(in_water)
// pseudo-code: wash dish
if not righthand.isholding(dishcloth)
then righthand.pickup(dishcloth)
repeat
righthand.scrub(d, dishcloth)
until d.isclean
// pseudo-code: stack dish
lefthand.moveto(over_draining_board)
lefthand.putdown(d)
// ToDo: Trap exception PileOfDishes.TooBig_FellOver
next d
Sigh. Now I've confused the issue by having a silly example with two levels of pseudo-code; one representing example pseudo-code and one standing for real code. But I couldn't think of a better example offhand. Maybe all problems really do go away with one more abstraction layer...
For anything complicated, I write pseudocode first. It helps me plan, and it helps me resume after being interrupted. It is one of my best tools.
Nathan on May 11, 2009 7:50 AMIt looks to me like it might actually be a matter of preference.
Do what works for you. We understand that people have different styles of learning. It makes sense that they have different styles of problem solving.
Practicality on May 11, 2009 8:16 AMMcConnell: "You can review detailed designs without examining source code."
This is scary, actually. Comments are not code and they often don't match the code (part of the problem of commenting too much). So if you're reviewing comments to see what the code is doing you could very likely be misled.
Tim on May 11, 2009 8:31 AMI use it, and like it when others do it.
"good" code is a relative and subjective measure. As you can tell by the other comments many people have strong opinions about what they prefer. The real question shouldn't be is it a good practice in itself, but rather does it improve collaboration, understanding, learning, and ultimately the bottom line. Pseudo commenting can be extremely beneficial for some members of a team (especially junior team members, these forms of comments are definitely instructive).
You may understand code better without comments, that's fine, but imposing this on others is a different matter. If it helps your colleagues as they claim it does, then it is selfish to not comment. The code serves to communicate to both the machine and your coworkers.
I'll concede it can go too far. Fully realized graphical documentation per class can be overkill and unrealistic. So the question, how much commenting is reasonable for others to understand your work?
Ryan on May 11, 2009 8:36 AMJeff,
Sometimes even a simple algorithm can have a lengthy, eye-numbing implementation. A clear pseudocode explanation of a function's purpose and method can be helpful. As a simple example, a function to return the arithmetic mean of a buffer of elements might look like:
But you know what goes here...
Depending on the input and output requirements, you may well end up with dozens of lines of if.then.else statements all doing basically the same thing. But as a prudent programmer you're also avoiding overflow, underflow, and warning on NaN's. A simple mean computation might run into a hundred or more lines of code.
Ever read your own code from ten or twenty years ago? A very instructive exercise.
- Lepto
Lepto Spirosis on May 11, 2009 11:23 AMI have to disagree. I believe i'ts a good idea to write pseudocode first, but maybe it's because I'm not the best coder out there.
Writing pseudocode is much quicker than writing code and you can take advantage of that to better design your app.
Writing pseudocode first always saves me so much time later when I start writing the actual code.
phuong on May 11, 2009 11:48 AMThere are folks who use really abbreviated variables to fit 24x80.
A bunch of BSD/Linux code is like that.
Comments become really helpful in such situations.
I think it totally depends on a) the type of programming being done and b) the language(s) being used.
For most web-dev stuff that isn't heavily on algorithms or trickery (using well written libraries with sane method names) PPP is probably overkill as the code itself (should) be readable enough even for non language geeks.
If you are writing something tricky or highly complicated though in say ANSI C, then the PPP starts to look like an easy way to eliminate bugs before they are even created.
CliffordJ on May 11, 2009 1:22 PMI was taught this technique in college, and I used to do this quite often in my first several years after college to help me think through a problem. I think it's very useful for someone who is fairly new to programming - your brain isn't wired yet to think in code. As I got more experience under my belt, I gradually stopped thinking in terms of pseudocode and started thinking in pure code, at which point it became a redundant exercise in most cases. I agree with some other commenters, though, that it can be a useful trick for even the most experienced programmer when designing a very complex routine.
Ed Leighton-Dick on May 11, 2009 2:46 PMAs I was reading through Steve's rationales, I found myself objecting in my head along the same lines that you offer with further reading. As I read, I wondered how PPP could possibly be redemptive since it had (seemingly) two well-respected advocates.
My only thought was that if the pseudo code was abstracted/declarative/high-level enough, it might be useful. Whereas in your example, the pseudo code is almost a line for line redundancy of the actual code. A more useful example might be something like this.
When the code is valid, log a message from table using a context-appropriate method.
Otherwise, notify the user that an internal error has occurred.
...Paraphrasing or recording the spec this way might be a useful tool to help you work out the project goals with the client. Once done, this "pseudo code" may also be instructive when it comes to naming methods, variables, etc.
steamer25 on May 11, 2009 3:01 PMhee hee.
You're all idiots. I most enjoy reading the one's where you nimrods on your 'im-so-impressive soapbox' on comments and how you don't need any of it because you can think in code like a machine in the first place and you are perfect. perfect. (queue evil laughter here)
i wish i could be like you.
PS Jeff, if you say you can't digest something, you're saying 'i read it but I can't understand it'. You apparently do understand it, you just don't buy into it or see its continued relevance. Not understanding how it helps, or if it helps, and the discourse you go through indicates you comprehend it. Then again maybe it's just your smackdown use of hyperbole.
I love Code Complete and have read through it more than once, but just like you I have had trouble sticking to this practice. I have tried and for the most part I agree that code is much easier to write that pseudocode.
The only time I use it with success is when I am stuck on a harder problem. In those cases the pseudocode allows me to see the problem at a higher level and get things in the correct order in my head. Usually, this is on a whiteboard and not buried in comments. I too prefer the code to speak for itself if at all possible.
Brooke on May 11, 2009 4:19 PMPersonally I tend to code directly but that is because how I like to do it and how I personally understand it better.
If I try to explain it to other people, if they are like-minded programmers, I'd show my code as is and hope they get the hang of the code (which means I didn't screw up so much) :)
If things doesn't make sense to them, that is where I would fall back to Pseudocode trying to explain the code in plain English. Sometimes not on a line-by-line basis, but at least the general idea of what the function suppose to do. And from there go further down into more detailed functionality (whether a mix of Pseudocode + Code, or just code)
I believe Pseudocode has its uses but I have yet to be able to utilize it fully to my own advantage :)
Darius on May 11, 2009 4:21 PMI Learned flow charting when I was a pre-teen. When I need to design something I draw pictures. It might be a flowchart, usage chart, uml, or just a bunch of boxes on a sheet of paper with lines linking them.
Whatever the case may be, never pseudocode unless I am explaining to someone else how the code that I already wrote works.
That being said, anyone who does not write comments in their code, I never want to have to work with you nor to even meet you. I have had to translate way too much code from a foreign language, say php, to something like java. If there had been comments in the code I would have been able to write the new code without having to go learn a new language, therefore saving weeks in the production cycle.
Thou Shalt USe Comments!
Mark on May 11, 2009 4:27 PMI'm in favour of pseudocode, but mainly for high-level descriptions of what chunks of code going to do. There does become a point at which it's easier just to write code. That's the point at which I stop writing pseudocode and actually write code. :-)
James Sinclair on May 11, 2009 4:48 PMI'm in favour of pseudocode, but mainly for high-level descriptions of what chunks of code going to do. There does become a point at which it's easier just to write code. That's the point at which I stop writing pseudocode and actually write code. :-)
James Sinclair on May 11, 2009 4:48 PMThere's good use for pseudocode sometimes, for example in involved conditional statements. You can play through several scenarios on paper, find the patterns in them in general logic (I want this to happen here, but only if...), then write the actual statements as they pertain to the concrete situation (if ($a && !$b || $c...)).
It really depends on the situation, and for trivial situations pseudocode is indeed often a waste of time. It's just another technique and, as with anything, you have to use it wisely.
Dav on May 11, 2009 8:32 PMI use this method, but I don't presume all the comments have to be left in at the end (delete the obvious ones when done). I don't use it for trivial details either.
Although, leaving them in can be good for newbies, auditors and managers who evaluate source code. Also, proof-readers can then spot differences in intention to implementation.
It makes it far easier to come back to code the next day - you know where you are going because you sketched it out. For difficult problems, it saves having to research specific algorithms or APIs ahead of time.
I prefer to complete whole skeletons of applications this way and then fill them out - iterate the architecture before committing to code (but I am a small systems specialist, so my rules are different to large teams).
Otherwise, I could write a function or a class and then discover it needs to be something different when I go to call it from somewhere else - what seems slower at the onset is faster by the end (a sharp axe is no benefit if you're cutting the wrong tree!).
Also, I notice a lot of people who believe generic reusable code is unattainable type code directly. Pseudo-code allows you space to plan and think - critical if you are both the architect and coder (as is the case in most small-medium projects).
The idea is to think not about the code, but about what you are trying to achieve.
I simplify it though - more a mix of pseudo and comments in one hit, plus putting in the framework of interfaces, routine names and parameters first.
I just listed about 12 fatal bugs to a famous backup program company that would not have happened if they had followed these kind of rules (part of the problem is that they never thought what must be done to successfully perform a backup in general terms before coding and the rest is that they never tested their code, either at developer or test team stage before release - key features are not even close to working. Most of these errors could have been picked up at pseudo-code stage rather than several versions down the track.
BTW Anyone else finding that typing into this blog does not go in real time with IE8? Haven't hit this problem anywhere else yet.
Paul Coddington on May 11, 2009 11:10 PMI use pseudocode if the problem is vast and I can't figure out the appropriate code straight away. But usually I just write code and comment where necessary. On the other hand things should be specified and designed first. If you have specification and design, then you might not need pseudocode. Also I might prototype something and write the design according to the prototype. Reusable components could use prototyping and designing. But when you use the components, things get trivial and you design the logic, not how you use the component again and again.
Silvercode on May 12, 2009 12:32 AMI like using pseudocode and it really helps me detail the business process before I figure out what data structures I wish to use for example .. Unlike you, it is easier for me to "think" in pseudocode.
I am honestly quite incapable of "thinking" in code !
Preeti Edul on May 12, 2009 1:09 AM80+ % bad. Why?
Because code comments rot a LOT faster than code does. So, in a random code base comments are MISLEADING and thus useless or actually subtracting value from the source code the vast majority of time.
Mathias on May 12, 2009 4:46 AMI've never heard of PPP before, but that's a perfect description of how I write all my really complex code. For simple tasks, it's easy enough to just bang out some code. However, in a really complex algorithm, or really sensitive section of code, this so-called PPP is definitely the way to go!
Brian Knoblauch on May 12, 2009 5:04 AMI don't get to write much code nowadays, but when I started 40 years ago, and had to write in assembler, a structured pseudocode was a great way to work through the logical design of a module.
When translating line by line into assembler, I would even sacrifice a little efficiency to keep each block completely equivalent to its pseudocode, in case any changes were needed later.
Now, with higher level languages, and all the design documentation we have to follow or produce, the advantages of pseudocode are needed less frequently when working with big or critical systems, but I can see that there may still be some use for it in less formal applications.
I'm still a relative beginner whne it comes to coding and I think pseudocode (though I've never called it that before) is indispensible when coding as a beginner because although I may be able to construct the algorithm, all the loops and ifs in everyday language, I simply don't have the encyclopaedic knowledge of the language I'm using yet to be able to write it out properly as I think of the tasks the code needs to complete. Writing out the pseudocode allows me to 'write' the code in a fluid manner without having to keep interrupting my thinking through th logic in order to look up eg. what order I should put the parameters in a particular function.
Rhys on May 12, 2009 10:27 AMI like to plan out sections of new development coding using pseudocode in a text editor - usually when I program in LotusScript.
I like the pseudocode because I can plan how the major functionality will work - without having to worry about the exact syntax.
After I've completed the pseudocode, I copy it into Domino Designer as comments - but I usually remove most of the pseudocode comments as I convert them into code.
To me, good code can be self-documenting so it can be redundant to keep the pseudocode in place....
But I do keep the pseudocode in place when it describes something that may be less obvious at a first glance at the code.
Derek Etnyre on May 12, 2009 10:42 AMI guess the point is to know when using PPP might give you an advantage.
I use PPP sometimes when I want to accomplish something comlicated but don't know yet how to do it in code. For example when there are functions or objects I'm unfamiliar with. Figuring how to call the functions etc. can be distracting and one can quickly forget to check for special conditions.
joerg on May 12, 2009 10:47 AMI agree with you completely regarding writing out pseudo-code in a literal way like that. I occasionally use pseudo-code in accompanying design documentation, but I find code to be the most succinct and interesting. I don't like too many comments in code because I find that it obstructs my view (of the code.) A header on the method that describes the purpose is usually enough for me.
Assembler language was a different story, but at that time maintaining linked lists was something you had to think about rather than just instantiating a pre-built class.
Michael Cookson on May 12, 2009 6:00 PM"Because code comments rot a LOT faster than code does."
Bad programmer. Hope I never have to work after you.
broseph on May 12, 2009 10:47 PMI found starting with a pseudo code commenting lead to long method implementation, which can easily turn into spaghetti code.
I am totally with you Jeff. The focus needs to be making the code itself easier to read rather than putting metadata around it.
These days I found BDD makes alot more sense for the same purpose. Stating all the expectation in the form of method names, Implementing them as I go along. same concept, but focusing on the code. I tend to get focused, concise classes and methods.
Ronald Widha on May 12, 2009 11:28 PMhttp://www.cheap-air-jordan.cn
jp2506 on May 13, 2009 2:50 AMI've always written my code by writing the comments first, ie PPP. To me this has a couple of advantages:
1) It makes you think about the *design* rather than the mechanics of the language. Generally, when you do this, you are also working in the problem domain rather than the code domain (ie "get invoice details" not "get all the rows from tblInvoiceRow where foreignkey is tblHeader.InvoiceNumber"). If you're writing them at the coding level, I agree that you might as well just write the code.
2) You end up with commented code, that defines *what the code does* not *how the code does it*. If I come along to maintain some code written by some guy who left the company 3 years ago, if the comments describe what/why he was trying to do, even if his code is unreadable, I at least have some hints towards what the code is doing.
Now, there is a risk in this, in that the comments have to be maintained when the code changes, and some people are better than others at this (I *always* do this, some of my colleagues would rather have root-canal treatment) - so the danger is that the comments and code don't relate to each other.
However, for me, the majority of the benefit is in getting the design right in the first place, which, IMHO, is a lot easier if you're thinking "what is the logic?", than "how can I write this code?"
SteveX on May 13, 2009 5:32 AMI don't follow this practice rigorously, but I do use both pseudocode and comments.
I agree with SteveX and some others, both pseudocode and comments allow you to determine what you want to do and why you want to do it this way. Comments explain decisions that you made such as: using one data structure over another or why you decoupled code into different classes/methods.
Pseudocode allows you to sketch out a good algorithm or approach without being concerned with the syntax. This depends greatly on how focused you are on a single language. If you use mostly one language, year after year; your psuedocode tends to be quite close to real code and your thinking aligns with the structure of that language. Similar to this quote in the book:
"We were writing a new system in C++, but most of our programmers didn't have much experience in C++ They came from Fortran backgrounds. The wrote code that compiled in C++, but they were really writing disguised Fortran"
We're currently reading Code Complete 2nd Ed on my blog if anyone wants to join us in our virtual book club to read, review, or re-read.
Technical Book Code: Code Complete
http://blogs.msdn.com/springboard/archive/2009/05/07/technical-book-club-how-to-participate.aspx
There are coding n00bs out there like me that have to sit there for an hour trying to think of the best way to code something before actually writing out the code and debugging it.
Pseudocode helps me achieve that goal a little faster and takes care of the commenting while I'm at it. As I become more practiced in coding, I'm sure I'll shy away from it just to get the coding side done faster, but I don't think I'll completely phase it out.
I agree, pseudocode can be a bit redundant, verbose, and mind-numbingly cumbersome, but for n00bs like me, it's a real help.
"The idea is not to think about the code, but to think about what you're trying to achieve"
-StephenK
Network Admin
Hi,
nice article. It reminds me one thing. Before I do some programming work it's good to look on the problem from more abstract view. It's like when you're lost then it's good idea to find a high place and look round. Sometimes I find myself staring into code. Hard trying to penetrate the thing and better is looking from window and think of the whole problem.
Uroboros on May 14, 2009 3:47 AMI am in favor of using pseudocode. I have never actually heard the formal description of how to use until this article but it describes exactly to the T the method I have used. I may not have outline every exact detail in english but a rough explanation of the design. Thus when I finished coding the code was already commented and it was easy to share the design in pesudocode with the rest of the team rather than reams of code. It should be noted the language being used for this approach is C.
Wilson on May 14, 2009 3:41 PMI agree with you here. I don't see much benefit from pseudocode over code at all. Since the specific programming language is your first language, pseudocode doesn't produce higher level of clarification than code itself. The result of turning pseudosode to line level comment is disaster against good commenting style completely.
xuzf on May 14, 2009 9:37 PMIf you need to first write the code in pseudo code in order to understand it, then most likly your routine is too large and needs to be split up into smaller easier to underrstand pieces.
Morten on May 15, 2009 12:40 AMI think I was using a "sort of" PPP even before I read CC for the first time - I think it helps me write better code faster. However, my pseudocode is just that - mine. It is a personal shorthand type thing, which is perfectly geared for my comfort level in the language which I am using at that point in time. Most times, it makes for great comments. But that is not the primary objective. Most coding assignments have some grunt plumbing to do - you do not want to get lost in the details of those, when you are focusing on your primary solution algo. PC helps you get the major design flows right, and you can go back and "fill up" the easy stuff in a second iteration.
Sunder Raj on May 15, 2009 1:00 AMVisual representation of pseudo-code (graphs, diagrams) is much more useful
lanG on May 15, 2009 10:47 AMOooo, all you really smart people who think in ones and zeros and don't need to comment your brilliant code! Of course your way is best and only way and everybody else is wrong. The nerve of all the noobs that disagree with you, pah!
Get over yourself chef hacker boy-r-dee.
bhwaahaha
ztopitnow on May 15, 2009 12:17 PMThe problem is this is the wrong kind of pseudocode. Your pseudocode should resemble what your comments would be when you're done - why and what you're doing, not how:
pseudocode:
* test error code for validity
* if doing interactive processing, display the error message interactively and negate the error
code:
// test error code for validity
Status errorMessageStatus = Status_Failure;
Message errorMessage = LookupErrorMessage( errorToReport );
if ( errorMessage.ValidCode() )
{
// if doing interactive processing, display the error message interactively and negate the error
ProcessingMethod errorProcessingMethod = CurrentProcessingMethod();
if ( errorProcessingMethod == ProcessingMethod_Interactive )
{
DisplayInteractiveMessage( errorMessage.Text() );
errorMessageStatus = Status_Success;
}
}
I find it easier to design a routine in pseudocode comments. But once I'm done writing the routine, I find that the pseudocode is usually redundant and I end up deleting it.
Jeff B on May 17, 2009 12:23 PMI never use pseudocode as mentioned in the article, but I do use UML quite regularly. It's a great took to leverage when a good idea strikes and it might be easily forgotten. Friday afternoon this happpened, right before work ended. I quickly drew out some UML on my white board and left. This morning it was useful as I had completely forgotten what I came up with in that fleeting moment before leaving work on Friday.
Taylor on May 18, 2009 11:43 AMTypically I'd write the pseudocode and then make as many lines as possible to separate routines (or refer to existing code). This is with the aim of making the the code look as much like the original Pseudocode as possible. Once this is done, the pseudocode is deleted.
If the code is human readable then it is self documenting and easier to maintain.
Using pseudocode in this way helpd to ensure that my methods only do one thing and that the structure is sound. If I was to just dive in to the code then the chances are that the train of though will be lost once the a complicated bit of coding is encountered.
Al Rose on May 19, 2009 5:02 AMIt's funny, I am not a classically trained programmer and this is exactly what I have always done. The whole two programming classes I took in college both recommended (one of them required) a written plan of action for how you were going to accomplish whatever ridiculous academic exercise that they were going to have you complete. Now, my handwriting as atrocious, and I lose loose paper all the time, so I decided instead of wasting my time on pencil and paper I just wrote out my plan of action and then used it as a guide to what I was doing. I didn't do any programming for a few years and then when I got a job as a programmer 4 years ago, I started doing that again.
However, when I get the whole section of code written, I take out some of the comments that are obvious in the code. Sometimes this results in there being no comments, but if there is some business rationale behind what I did, I leave that as a note for the next poor SAP that runs across it.
In this way the pseudocode is not for the express use as comments, but instead a guide which might possibly be comments with a little more polish.
Anthony on May 19, 2009 8:38 AMHi!
To me, pseudocode comes in handy when you are with your bosses/consultants/key account managers and they want to be explained how a piece of code should be implemented (of course, they have no idea about programming languages).
Other than that, I can hardly say I've pseudocoded at all...
Nice blog, keep the good job.
Cheers
Jaime on May 20, 2009 12:26 AMI rarely use pseudocode. As you say, I find it easier to just write the code. But sometimes, for example when I have to implement some particularly gnarly algorithm which needs a lot of thought, I will use pseudocode first.
Pseudocode is a tool that has its uses. Perhaps in the days of less expressive languages it was helpful and I think it would be helpful to beginners who haven't yet got a good grip on a language, but to use it all the time seems like overkill to me
Grahame on May 21, 2009 7:33 AMI'm a beginner programmer but I think of it as a good way of practicing your mind and your ability to define problem and its solution loudly to ur self and others before getting ur mind involved in code details even if u r experienced programmer and details are easy for u, but i feel thinking process should still be separate .this process is just saying you r a good problem solver not a problem solver with c# or java just problem solver.
Anonymous on May 24, 2009 5:26 PMI'm a beginner programmer but I think of it as a good way of practicing your mind and your ability to define problem and its solution loudly to ur self and others before getting ur mind involved in code details even if u r experienced programmer and details are easy for u, but i feel thinking process should still be separate .this process is just saying you r a good problem solver not a problem solver with c# or java just problem solver.
MaD_GirL on May 24, 2009 5:30 PMWe use it to document (and debate) the design prior to implementation. I find that it is most useful when dealing with higher-ups and new folks; they really *don't* think in code, and presenting ideas in psuedo-code/English saves me from having to translate on-the-fly. We also use Visio diagrams for the exact same reason.
@MaD_GirL: Hi there. I'm very glad that you're beginning to program and I think that Jeff's site here is fantastic resource to learn from. (I know I have.) Kudos on starting right.
If I may, let me suggest that you go back and read . It'll do you a world of good.
JButcher on May 25, 2009 3:20 PM(Jeff's no HTML rule bites me yet again).
@MaD_GirL: That link was http://www.codinghorror.com/blog/archives/001184.html
Article Date - November 8, 2008
Article Title - Coding: It's Just Writing
Pseudocode vs "coding":
I think composing at the keyboard is great - and tends be my preferred method - but really this is short-circuiting design.
The idea behind Pseudocode is not to describe your code (or what will become your code) in English - the idea is to focus on the "problem" and the "solution" rather than the code.
In your example you state things like "Set default status to fail". This is NOT something you want in pseudocode. That's a valid programming construct, but (probably) doesn't really have any meaning outside the language you are programming in.
Describing the algorithm is significantly different than describing the code syntax. Pseudocode should be all about the algorithm and should be language-independent.
-CF
ChronoFish on May 26, 2009 11:00 AMHa - get to sit at a computer and write code in a job interview, I was once given scrap paper and a pencil in one such situation (at least I could rub it out)!!!
As for PPP, i can see both sides. Mostly, I think in code, write in code and then comment it up to remind me *why* i coded like that, rather that *what* has been coded.
I find PPP great when detailing a routine where it isn't obvious to me at the start how I will code it. I know what parameters I've got and what the goal of the routine is...but the middle bit is a bit fluffy. In such situaations I find Pseudocoding really helpful as it shows up immediately where the tricky bits will be
Chris on May 28, 2009 2:12 AMWell, first off I'll say any programmer that doesn't believe in commenting, or has to endure the chore of commenting code after it has been written is an amateur and un-professional.
Heads up: writing code and commenting your code are an integral activity. It takes about half day to a day to learn the disipline to comment as you code and then you never have to think twice about it.
Code tells you what, comments tell you why. Comments also allow you to summarise sections of code and break it up into sections. Try to think about the poor mug that has to fix your code - that may be you in six months time!
Having said that, I'm finding OO code requires less commenting that procedural code.
*******
As to p-code, in my early days as a programmer I always used p-code prior to writing the code. By myself, I had settled on one week development cycle, which in later years would be echoed in the Agile methodology as an 'iteration'. In my week, Monday, Tuesday and Wednesday were design, Thursday was coding and Friday was testing.
During the design phase I would be relying heavily on my training from college, using input/output diagrams, process charts and p-code. Those three days were spent thinking about the code, writing p-code and stepping through it. It was certainly helping me reduce errors during implementation and the testing was a lot smoother (hence only 1 day in a 5 day cycle).
So for an inexperienced programmer it is a valuable tool and I would still insist on a junior programmer going through ALL the design steps prior to writing any code. Even as an experienced professional I still rigorously write design documents and specifications - how else are you and your customer going to agree to the work that is required? Correct documentation is also a very good tool to making sure your time estimates are accurate?
See, most programmers think the correct documentation is nothing to do with the code, or them. But they have got it wrong - documentation is just as integral to a program as the comments that aren't written for it. As with comments, do it as you go along. A design document or specification is not set in stone, they can be changed as the software evolves.
Its OK for amateur to skip all that stuff, but a professional should never let the documentation and the code fall out of sync. Really, at the end of the project it all makes it easier to hand-over your work onto the support programmers. Plus, they'll have a lot more respect for you. Not to mention the fact that your customers will have an idea of what they are getting, but the documentation helps you to remember exactly what it is you are meant to be writing. Your testers might have a clue too, when they come to write their test plans!
****
Finally, p-code is never a substitute for the code and as a tool it is often misunderstood. P-code is as free-form as you want it to be and allows you to skip over the really boring stuff, but still allow you to define and concentrate on the really critical parts of your programs.
The real key to using p-code correctly is knowing where the p-code ends and the coding begins.
Mat on June 9, 2009 6:26 AMI thought it was a very good site and explained the key concepts to bookkeeping well.
Accounting Homework on June 28, 2009 12:05 AMI think that makes it even better. I have good feel read your article .Thanks
accountinghomework help on July 3, 2009 1:18 AMWhen you receive business requirements as bullet points, and there are cross relationships between them, I find using PPP is great to extract the logical flow for my code. I can write out the PPP at a high level then jump top design.
Uniface on July 29, 2009 6:24 AMi love you all...good reading indeed, thnx you
syamhid on August 18, 2009 8:51 AMPseudo-code makes a lot of sense for people to whom the programming language is not a second language -- a language in which he or she is fully fluent in, being capable of reading it, writing it, and thinking in it, without having to resort to back-and-forth translation into another language he is fluent with.
This should make sense to anyone fully fluent in a foreign language (or more than one national language), or in a programming language itself. Programmers who are fluent in neither might think it downright impossible.
It happens with all math too, by the way. People who can actually _work_ math, instead of repeating a particular pattern described in a book, on the web or by a teacher, do not think about it in English (or whatever). They think it in the specific language of the field he works on.
It happens too with physics. Physicists do not think of the universe in English. They think of it in math, and the specific theories, theorems, assumptions and facts of his field.
And so on. So I, personally, don't care much for someone who needs comments because he can't read and think in the language he's a professional programmer for -- unless, of course, the person is aware of it and in the process of correcting the problem.
It happens too with physics. Physicists do not think of the universe in English. They think of it in math, and the specific theories, theorems, assumptions and facts of his field.
links of london on August 26, 2009 1:28 AMPseudo-code makes a lot of sense for people to whom the programming language is not a second language -- a language in which he or she is fully fluent in
links of london on August 26, 2009 1:40 AMAbercrombie & Fitch on Sale, Hoodies, Jeans, T-Shirts, Pants, Polos abercrombie and fitch abercrombie fitch abercrombie cheap abercrombie fitch Abercrombie Men Tee abercrombie womens polos Abercrombie & Fitch Men, women, and children's clothing
abercrombie and fitch on August 28, 2009 12:59 AMi love you all...good reading indeed
evlilik yıldönümü hediyesi on October 13, 2009 12:36 AMi love you all Good reading indeed
evlilik yıldönümü hediyesi on October 13, 2009 12:37 AMI find Pseudocode serves one basic purpose. It is useful to pass programs to others that use different languages, and it is easily recognizible what needs to be programmed. And I never add comments on my pseudocode because that would be redundant.
SailorGary on October 19, 2009 12:17 PMThanks for your information, i have read it, very goodï¼
ed hardy shirts on October 23, 2009 7:05 PMTHINK YOU
Anonymous on November 6, 2009 2:23 AMIt's my experiences that Pseudo always ends up as a way to explain code to those incapable of reading code
so as an example if your manager wants to know how something works you show them the pseudo
| Content (c) 2009 Jeff Atwood. Logo image used with permission of the author. (c) 1993 Steven C. McConnell. All Rights Reserved. |