The Elements of C# Style
The Elements of C# Style is for all C# practitioners, especially those working in teams where consistency is critical. Like previous Elements titles, the text furnishes a set of rules for writing clear, comprehensible and easy-to maintain code; this time for C#. The authors offer a collection of standards and guidelines for creating solid C# that can save time, effort and expense. The book provides conventions for:
- formatting
- naming
- documentation
- programming
- packaging for C# 2.0 and includes discussion of advanced topics such as generics.
1100177233
The Elements of C# Style
The Elements of C# Style is for all C# practitioners, especially those working in teams where consistency is critical. Like previous Elements titles, the text furnishes a set of rules for writing clear, comprehensible and easy-to maintain code; this time for C#. The authors offer a collection of standards and guidelines for creating solid C# that can save time, effort and expense. The book provides conventions for:
- formatting
- naming
- documentation
- programming
- packaging for C# 2.0 and includes discussion of advanced topics such as generics.
31.0 In Stock
The Elements of C# Style

The Elements of C# Style

The Elements of C# Style

The Elements of C# Style

Paperback(New Edition)

$31.00 
  • SHIP THIS ITEM
    In stock. Ships in 3-7 days. Typically arrives in 3 weeks.
  • PICK UP IN STORE

    Your local store may have stock of this item.

Related collections and offers


Overview

The Elements of C# Style is for all C# practitioners, especially those working in teams where consistency is critical. Like previous Elements titles, the text furnishes a set of rules for writing clear, comprehensible and easy-to maintain code; this time for C#. The authors offer a collection of standards and guidelines for creating solid C# that can save time, effort and expense. The book provides conventions for:
- formatting
- naming
- documentation
- programming
- packaging for C# 2.0 and includes discussion of advanced topics such as generics.

Product Details

ISBN-13: 9780521671590
Publisher: Cambridge University Press
Publication date: 07/31/2006
Edition description: New Edition
Pages: 156
Product dimensions: 4.53(w) x 6.97(h) x 0.55(d)

About the Author

Ken is currently President of CenterSpace Software, a developer of C# numerical libraries for the .NET platform. He has previously written documentation for C++ and Java class libraries for Rogue Wave Software, mathematical and statistical tools for MathSoft Inc., 3-D modeling and animation tools for Cubicomp, and semantic networks for Microsoft. He has also developed Web-based learning systems for Medlink and the Stanford University School of Education. Ken holds a PhD in Cognitive Science from the University of California, San Diego, and a BA in Linguistics from the University of California, Berkeley.

Andy was coauthor of The Elements of C++ Style. He is currently an Executive Partner with Evolution Software Design, focusing on .NET, Tablet PCs, and XML/Web Services. He co-hosts TabletDev (www.tabletdev.com), a resource site for the Tablet PC development community. He has many years of Windows development experience, working for IntelliChem, Rogue Wave Software, ACCEL Technologies, and Microsoft. He holds a MS degree in Computer Science from University of California, San Diego, and a BS degree in Computer Science from Harvey Mudd College.

Trevor is coauthor of The Elements of Java Style and The Elements of C++ Style. He has held programming positions for a variety of firms using C#, C++, Java, and other technologies. He is currently CEO of CenterSpace Software, a developer of C# numerical libraries for the .NET platform, and has worked previously for Rogue Wave Software, CleverSet Inc., and ProWorks. He holds a BSc in Computer Science from the University of British Columbia and a BA in Economics from the University of Western Ontario.

Read an Excerpt

The Elements of C# style
Cambridge University Press
0521671590 - The Elements of C# style - by Kenneth Baldwin, Andrew Gray and Trevor Misfeldt
Excerpt



Introduction

style: 1b. the shadow-producing pin of a sundial. 2c. the custom or plan followed in spelling, capitalization, punctuation, and typographic arrangement and display.

—Webster’s New Collegiate Dictionary

The syntax of a programming language tells you what code it is possible to writewhat machines will understand. Style tells you what you ought to writewhat humans reading the code will understand. Code written with a consistent, simple style is maintainable, robust, and contains fewer bugs. Code written with no regard to style contains more bugs, and may simply be thrown away and rewritten rather than maintained.

Attending to style is particularly important when developing as a team. Consistent style facilitates communication, because it enables team members to read and understand each other’s work more easily. In our experience, the value of consistent programming style grows exponentially with the number of people working with the code.

Our favorite style guides are classics: Strunk and White’s The Elements of Style3 and Kernighan and Plauger’s The Elements of Programming Style.4 These small books work because they are simple: alist of rules, each containing a brief explanation and examples of correct, and sometimes incorrect, use. We followed the same pattern in this book. This simple treatmenta series of rulesenabled us to keep this book short and easy to understand.

Some of the advice that you read here may seem obvious to you, particularly if you’ve been writing code for a long time. Others may disagree with some of our specific suggestions about formatting or indentation. The most important thing is consistency. What we’ve tried to do here is distill many decades of development experience into an easily accessible set of heuristics that encourage consistent coding practice (and hopefully help you avoid some coding traps along the way). The idea is to provide a clear standard to follow so programmers can spend their time on solving the problems of their customers instead of worrying about things like naming conventions and formatting.

The guidelines in this book complement the official .NET design guidelines in the ECMA C# specification5 and Krzysztof Cwalina and Brad Abrams’ excellent Framework Design Guidelines.6 This book extends those guidelines to internal implementation and coding style.

Disclaimer

We have dramatically simplified the code samples used in this book to highlight the concepts related to a particular rule. In many cases, these code fragments do not conform to conventions described elsewhere in this bookthey lack real documentation and fail to meet certain minimum declarative requirements. Do not treat these fragments as definitive examples of real code!

Acknowledgments

Books like these are necessarily a team effort. Major contributions came from the original authors of The Elements of Java Style: Al Vermeulen, Scott Ambler, Greg Bumgardner, Eldon Metz, Trevor Misfeldt, Jim Shur, and Patrick Thompson, and the original authors of The Elements of C++ Style: Trevor Misfeldt, Greg Bumgardner, and Andrew Gray. Both of those books have some roots in “C++ Design, Implementation, and Style Guide,” written by Tom Keffer, the “Rogue Wave Java Style Guide,” and the “Ambysoft Inc. Coding Standards for Java,” documents to which Jeremy Smith, Tom Keffer, Wayne Gramlich, Pete Handsman, and Cris Perdue all contributed.

Thanks also to the reviewers who provided valuable feedback on drafts of this book, particularly Brad Abrams, Krzysztof Cwalina, and Mark Vulfson of Microsoft Corporation; Mike Gunderloy of Larkware; and Michael Gerfen of Evolution Software Design.

This book would certainly never have happened without the help and encouragement of the folks at Cambridge University Press, particularly Jessica Farris and Lauren Cowles, who kept us on track throughout the writing and publication process.





1.

General Principles

While it is important to write software that performs well, many other issues should concern the professional developer. Good software gets the job done. But great software, written with a consistent style, is predictable, robust, maintainable, supportable, and extensible.

1. Adhere to the Style of the Original

When modifying existing software, your changes should follow the style of the original code.7 Do not introduce a new coding style in a modification, and do not attempt to rewrite the old software just to make it match the new style. The use of different styles within a single source file produces code that is more difficult to read and comprehend. Rewriting old code simply to change its style may result in the introduction of costly yet avoidable defects.

2. Adhere to the Principle of Least Astonishment

The Principle of Least Astonishment suggests you should avoid doing things that would surprise other software developers. This implies that the means of interaction and the behavior exhibited by your software must be predictable and consistent,8 and, if not, the documentation must clearly identify and justify any unusual patterns of use or behavior.

To minimize the chances that anyone would encounter something surprising in your software, you should emphasize the following characteristics in the design, implementation, packaging, and documentation of your software:

SimplicityMeet the expectations of your users with simple classes and simple methods.
ClarityEnsure that each class, interface, method, variable, and object has a clear purpose. Explain where, when, why, and how to use each.
Completeness Provide the minimum functionality that any reasonable user would expect to find and use. Create complete documentation; document all features and functionality.
ConsistencySimilar entities should look and behave the same; dissimilar entities should look and behave differently. Create and apply consistent standards whenever possible.
RobustnessProvide predictable, documented behavior in response to errors and exceptions. Do not hide errors and do not force clients to detect errors.

3. Do It Right the First Time

Apply these rules to any code you write, not just code destined for production. More often than not, some piece of prototype or experimental code will make its way into a finished product, so you should anticipate this eventuality. Even if your code never makes it into production, someone else may still have to read it. Anyone who must look at your code will appreciate your professionalism and foresight at having consistently applied these rules from the start.

4. Document Any Deviations

No standard is perfect and no standard is universally applicable. Sometimes you will find yourself in a situation where you need to deviate from an established standard. Regardless, strive for clarity and consistency.

Before you decide to ignore a rule, you should first make sure you understand why the rule exists and what the consequences are if it is not applied. If you decide you must violate a rule, then document why you have done so.

This is the prime directive.

5. Consider Using a Code-Checking Tool to Enforce Coding Standards

A source code analysis tool enables you to check your code for compliance with coding standards and best practices. For example, FxCop9 is a popular .NET code analysis tool that uses reflection, MSIL parsing, and callgraph analysis to check for conformance to the .NET Framework design guidelines. FxCop is extensible, and can thus incorporate the particular coding standards used by your own organization.





2.

Formatting

2.1 White Space

6. Include White Space

White space is the area on a page devoid of visible characters. Code with too little white space is difficult to read and understand, so use plenty of white space to delineate methods, comments, code blocks, and expressions clearly.

Use a single space to separate the keywords, parentheses, and curly braces in control flow statements:

for·(...)
{
   //...
}

while·(...)
{
   //...
}

do
{
   //...
}·while·(...);

switch·(...)
{
   //...
}

if·(...)
{
   //...
}
else·if·(...)
{
   //...
}
else
{
   //...
}

try
{
   //...
}
catch·(Exception)
{
   //...
}
finally
{
   //...
}

Use a single space on either side of binary operators, except for the “.” operator:

double length = Math.Sqrt(x * x + y * y);
double xNorm = (length > 0.0) ? (x / length) : x;
double currentTemperature =
engineBlock.Temperature;

Use a single space after commas and semicolons:

Vector normalizedVector =
      NormalizeVector(x, y, z);

for (int i = 0; i < 100; i++)
{
   //...
}

Use a single space between the parentheses for the parameter list in a method declaration:

Vector NormalizeVector(double x, double y,
                                       double z)
{
   //...
}

Use blank lines to separate each logical section of a method body:

public void HandleMessage(Message message)
{
   string content = message.ReadContent();
   switch (message.ErrorLevel)
   {
      case ErrorLevel.Warning:
         //... do some stuff here ...
         break;
      case ErrorLevel.Severe:
         //... do some stuff here ...
         break;
      default:
         //... do some stuff here ...
         break;
   }
}

Use blank lines to separate each method definition in a class:

public void SendEmail()
{
   //...
}

public void SendFax()
{
   //...
}

7. Use Indented Block Statements

One way to improve code readability is to group individual statements into block statements and uniformly indent the content of each block to set off its contents from the surrounding code.

If you generate code using an integrated development environment (such as Visual Studio), make sure that everyone on your team uses consistent indentation options. If you are generating the code by hand, use two spaces to ensure readability without taking up too much space (see Rule #9):

void PesterCustomer(Customer customer)
{
   customer.SendLetter();
   if (customer.HasEmailAddress())
   {
      customer.SendEmail();
      if (customer.IsForgetful())
      {
         customer.ScheduleReminderEmail();
      }
   }
   if (customer.HasFaxNumber())
   {
      customer.SendFax();
   }
}

If you are managing a development team, do not leave it up to individual developers to choose their own indentation amount and style. Establish a standard indentation policy for the organization and ensure that everyone complies with this standard.





© Cambridge University Press

Table of Contents

Preface; Introduction; 1. General principles; 2. Formatting; 3. Naming; 4. Documentation; 5. Design; 6. Programming; 7. Packaging; Summary; Glossary; Bibliography.
From the B&N Reads Blog

Customer Reviews