Chapter 8 -- Formatting Code

[Previous] [Next]

Chapter 8

No professional writer would forgo the use of punctuation or capitalization, and no professional developer should write unformatted or poorly formatted code. Consider the formatting of words, which is more than an exercise to keep English teachers busy. Language standards serve the reader and the writer to an equal degree. When you encounter a question mark at the end of an English sentence, you instantly know that the sentence is a question, not a statement or a declaration. That single little punctuation mark makes all the difference in the world, as illustrated in this short dialog:

Jayson: The dog ate it.
Mike: The dog ate it?
Jayson: The dog ate it!

The same sentence is presented three times, but thanks to the use of standardized punctuation elements, it takes on very different meanings each time. Without these simple symbols, you would have to change the sentences to convey the same conversation:

Jayson: The dog ate it
Mike: You're kidding me; are you saying the dog ate it
Jayson: You must be dense; I said the dog ate it

Even if the words aren't very well written, the simple act of applying the correct formatting (punctuation and spelling) makes a huge difference in the readability of the words. Words written in all capital letters or in phonetic form are understandable and can be used to communicate, but they make the communication process unnecessarily difficult. TRY TO READ A DOCUMENT WRITTEN IN ALL UPPERCASE LETTERS , or perhapz reed a letr riten solee uzing fonikz, and you'll see what I mean.

The consistent application of accepted formatting standards combined with uniform sentence construction (use of verbs, nouns, and so on) empowers writers to focus on the subtleties of what they're trying to say rather than the mechanics of what they're writing. It also allows the reader to focus on the message conveyed by the writer rather than having to work to decipher the words and sentences.

Words that are formatted according to the rules and constructs of a language often have more impact and are almost always easier to understand. The same is true of formatted code. Code that is consistently formatted according to a set of rules is easier to read, easier to understand, and often more reliable. By applying formatting techniques to your code, you'll create much more professional code that people might even enjoy reading, as opposed to code that causes others to reach for a bottle of aspirin when asked to perform a code review.

Consider the following two procedures. They are identical in content and perform exactly the same task because they are written with the same code. Note the two <?> notations in the first example. These indicate code statements that are so long that the lines can't be read on a typical display without scrolling across the code window.

Unformatted code:

  PublicSub  RequeryAccountPhone()  OnErrorGoTo  PROC_ERR  Dim  rstPhones  As  Recordset  Dim  strSQL  As   String   '*Clearthephonelist.  lvwPhones.ListItems.Clear  '*Retrievethephonenumberinformationforthisaccount.  strSQL="SELECT*FROMtblPhoneNumbersWHERE[AccountNumber]="M<?>  Set  rstPhones=dbContacts.OpenRecordset(strSQL,dbOpenForwardOnly)  DoWhileNot  rstPhones.EOF  Call  AddPhoneToList(rstPhones![FormattedPhoneNumber],rstPhones![Ph<?> rstPhones.MoveNext  Loop  rstPhones.Close PROC_EXIT:  Set  rstPhones=  Nothing  :  ExitSub  PROC_ERR: MsgBox"Error:"&Err.Number&vbCrLf&Err.Description  GoTo  PROC_EXIT  EndSub  

Correctly formatted code:

  PublicSub  RequeryAccountPhone()  '* Purpose:FillaListViewcontrolwithallofthephone   '*numbersbelongingtothecurrentaccount.   OnErrorGoTo  PROC_ERR  Dim  rstPhones  As  Recordset  Dim  strSQL  As   String   '*Clearthephonelist.  lvwPhones.ListItems.Clear  '*Retrievethephonenumberinformationforthisaccount.  strSQL="SELECT*FROMtblPhoneNumbers"&_ "WHERE[AccountNumber]="&Me.AccountNumber&""&_ "AND[ContactNumber]IsNull"&_ "ORDERBY[Primary];"  Set  rstPhones=dbContacts.OpenRecordset(strSQL,dbOpenForwardOnly)  '*AddeachrecordintheRecordsettotheListView.   DoWhileNot  rstPhones.EOF  Call  AddPhoneToList(rstPhones![FormattedPhoneNumber],_  rstPhones![PhoneLocation],_  rstPhones![Primary]) rstPhones.MoveNext  Loop  rstPhones.Close PROC_EXIT:  Set  rstPhones=  Nothing   ExitSub  PROC_ERR: MsgBox"Error:"&Err.Number&vbCrLf&Err.Description  GoTo  PROC_EXIT  EndSub  

While these procedures are identical in function and content, there's clearly a difference between them. If these procedures were written by another person and you had to maintain them, which one would you prefer to work with? If you were the author of these procedures and had to have the code pass a peer review, which procedure would you prefer to have written?

Steve McConnell in Code Complete (Microsoft Press, 1993) states the following: "The Fundamental Theorem of Formatting is that good visual layout shows the logical structure of a program." This is a powerful statement. Even if a procedure's algorithms border on genius, sloppy code is sloppy code. Formatting isn't just about making code look nice, it's about making it more readable and understandable. When you format your code, you should

  • Make code easy to read and to understand. Readers should be able to follow the flow of code much as they would follow sentences and paragraphs within a document.
  • Reduce the work necessary to understand structural constructs. Complicated constructs consisting of nested (one inside of another) loops or If Then blocks can be terribly difficult to follow when indentation and white space aren't applied.
  • Organize code into functional pieces and understandable fragments , much like paragraphs in a document. The first step is to create many specialized procedures rather than one large procedure that performs dozens of tasks ”much like splitting a large document into chapters. Organizing the code within procedures is akin to breaking a logical argument into paragraphs.
  • Avoid forcing the reader to make assumptions. When you reference an object's default property without explicitly naming the property (for example, Text1 = "Shiny Object" as opposed to Text1.Text = "Shiny Object" ), you force the reader to make an assumption.
  • Make the structure of code as self-documenting as possible. You can often make code self-documenting simply by applying correct indentation.

Every company, team, and developer has an opinion about code formatting (and if they don't, they should). Unfortunately, many developers appear to not give code formatting even a passing thought. Their goal is to write code that works, and that's that. You might decide to alter some of the suggestions you find in this chapter based on your own opinions , but if you choose not to follow these directives, think carefully before doing so. If you decide to adopt your own variations of code formatting, make sure that the standards you choose are well documented within your organization and that all programmers adhere to them strictly and consistently.

When code is correctly formatted, it appears "finished," even elegant. You can often tell which programmers take the most pride in their work by how well their code is formatted. Code formatting is not polish that you can apply after the fact. Like code commenting, formatting is rarely done after the code is written. You must adopt a set of formatting standards and apply the techniques as you write code. It might seem like extra effort to remember the various formatting elements and how and when to apply them, but after a while it will become second nature. After all, do you really have to think about putting a period, a question mark, or an exclamation point at the end of a sentence?

NOTE
This chapter does not discuss the writing or formatting of comments. See Chapter 9, "Commenting Code," for information on that topic.
Goals of Formatting Code
When you format your code, your goals should include
  • Making your code easier to read and understand by organizing it into functional pieces and understandable fragments
  • Reducing the work necessary to understand structural constructs
  • Freeing the reader of your code from having to make assumptions
  • Making the structure of your code as self-documenting as possible


Practical Standards for Microsoft Visual Basic
Practical Standards for Microsoft Visual Basic .NET (Pro-Developer)
ISBN: 0735613567
EAN: 2147483647
Year: 2000
Pages: 57

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net