Style Guide
All code written now and in the future should be assumed to be shared with the world. Coworkers, employers, and other interested parties will want to see your code so they can read it, improve it, modify it, comment on it, etc. The key to making code sharable is to write clean, consistent code that is easy for the reader to follow. This guide establishes guidelines that will facilitate good habits that will create professional, clean code worthy of sharing and publishing.
This guide is written as a reference. There are many rules here, and many of them are pedantic. When in doubt, look for some analogous code in the example snippets and follow it.
JavaScript
Unless specifically stated otherwise, all JavaScript will follow the StandardJs Style Guide
Variable Naming
Variable names should be reflective of the data they will be handling. They should be one to four words describing the purpose, written in camelCase. With the sole exception of looping variants within for loops, one letter variables are NOT permitted.
Avoid | Better |
---|---|
const xobjs | const numberOfObjects |
const number_of_objects | const numberOfObjects |
Note that variable naming conventions apply equally to CSS and JavaScript.
Postgres Attribute Naming
It should be clear what MySQL table an attribute belongs to based on its name. An attribute's name must be prefaced with its table or class name, written in camelCase. When naming weak entities, combine the two table names in alphabetical order.
Case 1: You have a strong entity containing an attribute for the tweet ID.
Avoid: tweet ID: id
Better: tweet ID: tweetId
Case 2: You have a weak entity containing information linking users to their favorite tweets.
Avoid: A favorite tweet's tweet ID: tweetId
Better: A favorite tweet's tweet ID: favoriteTweetTweetId
Avoid: A favorite tweet's user ID: userId
Better: A favorite tweet's user ID: favoriteTweetUserId
Writing Error Messages
Writing effective error messages is important in software development. Error messages should be succinct, descriptive, and to the point. If possible, suggest a course of action for the user. Keep all emotion out of error messages and don't confuse the user.
Avoid: Catastrophic failure: mySQL connection is dead!
Better: Unable to connect to mySQL. Verify the connection parameters and try again.
Additionally, there are two major audiences for error messages:
- IT Professionals
- End Users
Consider your audience for the error messages. IT Professionals prefer highly detailed error messages kept in a log file or possibly Emailed to a special Email address. End users easily get confused and annoyed with error messages. Keep error messages short and to the point. Also, consider whether it's necessary to annoy the end user at all with error messages they can do nothing about.
Suggested Reading: MSDN Guide to Error Messages
Commenting
Prime Directive: If you break any rules in this styling guide, add a comment explaining why!
Each block of code should have a comment explaining what and why it does. Clearly written code is often “self documenting” in the sense that it should be relatively easy to see what the code does at a glance. What is not always as apparent is why the code is written as it is. Whenever possible, have your comments explain to the reader why the code is doing what it is doing.
Doc Blocks
Doc blocks are special comments that automatically generate documentation for a function, class, or method. In Deep Dive Coding, we will be using the Javadoc format. Put doc blocks before every function, class, method, and state variable so it will be documented.
/** * One line description of what this function or method does. This text usually appears inside an <h1> tag. * * Detailed description of what this function or method does. This text usually appears inside an <p> tag. * * @param <type> $firstParameter an explanation of what this parameter does * @param <type> $secondParameter an explanation of the second parameter * @return <type> what this function or method returns * @throws <type> what this function or method can throw, and why it will throw **/ function someFunction($firstParameter, $secondParameter) { // function goes here... }
Full doc blocks are required for sign off on any code written in Deep Dive Coding.
Keep Code Simple
Everyone knows that debugging is twice as hard as writing a program in the first place. So if you are as clever as you can be when you write it, how will you ever debug it?
Brian Kernighan in The Elements of Programming Style
Code shouldn't solve a huge problem. Instead, it should provide a simple solution to a simple problem. Simple code is easier to read, write, share, and maintain. Harder problems in computer science are solved by decomposing the difficult problem into many simple problems and solving the simpler problems. Don't be clever for the sake of being clever. Integrating simple, tried and true methods is a reward on its own.
Security
Fundamental Theorem of User Input: All user input is trash until sanitized.
No user input will enter a web application unverified. All data must be sanitized by several layers of tools (multiple times in case on tool fails, the other can act as the next line of defense). These tools include but are not limited to:
All possible tools must be used to ensure data is never polluted, compromised, or otherwise at risk.
HTML Style Guidelines
Adapted from the Google HTML/CSS Style Guide
Capitalization
Use only lowercase: This applies to HTML element names, attributes, attribute values (unless text/CDATA), CSS selectors, properties, and property values (with the exception of strings).<!-- Avoid -->
<IMG SRC="google.png" ALT="Google" />
<!-- Better -->
<img src="google.png" alt="Google" />
Self Closing Tags
All self closing tags will end with a XHTML style slash. This clearly indicates whether a closing tag is required or not and is cross-compatible with XHTML.<!-- Avoid -->
<img src="google.png" alt="Google">
<!-- Better -->
<img src="google.png" alt="Google" />
Encoding
Use UTF-8. Specify the encoding in HTML templates and documents via <meta charset="utf-8" />.
Comments
Explain code as needed, where possible. Use comments to explain code: What does it cover, what purpose does it serve, why is respective solution used or preferred?
Action Items
Mark todos and action items with TODO. Append a contact (username or mailing list) in parentheses as with the format TODO(contact). Append action items after a colon as in TODO: action item.<!-- TODO: remove optional tags -->
<ul>
<li>Apples</li>
<li>Oranges</li>
</ul>
Document Type
Use HTML5. HTML5 (HTML syntax) is preferred for all HTML documents: <!DOCTYPE html>.
HTML Validity
Use valid HTML where possible. Use tools such as the W3C HTML validator to test.
Semantics
Use HTML according to its purpose. Use HTML elements (tags) for what they have been created for. For example, use <h1> elements for headings, <p> elements for paragraphs, <a> elements for anchors, etc. Using HTML according to its purpose is important for accessibility, reuse, and code efficiency reasons.
Multimedia Fallback
For multimedia, such as images, videos, animated objects via canvas, make sure to offer alternative access. For images that means use of meaningful alternative text (alt), and for video and audio transcripts and captions, if available.<!-- Recommended -->
<img src="spreadsheet.png" alt="Spreadsheet screenshot" />
Separation of Structure, Style, and Behavior
Separate structure from presentation from behavior. Strictly keep structure (HTML markup), presentation (styling), and behavior (scripting) apart, and try to keep the interaction between the three to a minimum. That is, make sure documents and templates contain only HTML and HTML that is solely serving structural purposes. Move everything presentational into CSS style sheets, and everything behavioral into scripts.
General HTML Formatting
Use a new line for every block, list, or table element, and indent every such child element. Independent of the styling of an element (as CSS allows elements to assume a different role per display property), put every block, list, or table element on a new line. Also, indent them if they are child elements of a block, list, or table element.
<blockquote> <p><em>Space</em>, the final frontier.</p> </blockquote> <ul> <li>Moe</li> <li>Larry</li> <li>Curly</li> </ul>
HTML Quotation Marks
When quoting attributes values, use double quotation marks. Use double (" ") rather than single quotation marks (' ') around attribute values.
CSS Style Guidelines
CSS Validity
Use valid CSS where possible. Unless dealing with CSS validator bugs or requiring proprietary syntax, use valid CSS code. Use tools such as the W3C CSS Validator to test.
ID and Class Naming
Use meaningful or generic ID and class names. Instead of presentational or cryptic names, always use ID and class names that reflect the purpose of the element in question, or that are otherwise generic. Names that are specific and reflect the purpose of the element should be preferred as these are most understandable and the least likely to change.
Generic names are simply a fallback for elements that have no particular or no meaning different from their siblings. They are typically needed as “helpers.” Using functional or generic names reduces the probability of unnecessary document or template changes./* Not recommended: meaningless */
#yee-1901 {}
Shorthand Properties
Use shorthand properties where possible. CSS offers a variety of shorthand properties (like font) that should be used whenever possible, even in cases where only one value is explicitly set. Using shorthand properties is useful for code efficiency and understandability.
CSS Hacks
Avoid user agent detection as well as CSS "hacks". Try a different approach first. It's tempting to address styling differences over user agent detection or special CSS filters, workarounds, and hacks. CSS hacks should be considered last resort in order to achieve and maintain an efficient and manageable code base. Put another way, giving detection and hacks a free pass will hurt projects in the long run as projects tend to take the way of least resistance.
Rule Separation
Separate rules by new lines. Always put a blank line (two line breaks) between rules.
Parting Words
Be consistent. If you're editing code, take a few minutes to look at the code around you and determine its style. If they use spaces around all their arithmetic operators, you should too. If their comments have little boxes of asterisks around them, make your comments have little boxes of asterisks around them too.
The point of having style guidelines is to have a common vocabulary of coding so people can concentrate on what you're saying rather than on how you're saying it. We present global style rules here so people know the vocabulary, but local style is also important. If code you add to a file looks drastically different from the existing code around it, it throws readers out of their rhythm when they go to read it. Avoid this.