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 established guidelines that will facilitate good habits that will create professional, clean code worthy of sharing and publishing.
PHP File Naming Style: PSR-4
All file names related to PHP, Html, and CSS shall comply to the following naming rules:
- All files names shall start with a lowercase letter a…z.
- File names shall only contain lower case letters a…z, digits 0…9, the hyphen/tack character -, and the underscore character _ only when creating public_html directories. †
Exception: Capital Letters Allowed for PSR-4
The sole exception to the prohibition on capital letters is to comply with PSR-4. PSR-4 set forth by the PHP Framework Interoperability Group (PHP-FIG). PHP-FIG is a project and vendor neutral board that sets PHP coding styles by which major frameworks and composer packages adhere to. File names will generally be lower case, except to create PSR-4 compatible class file names. PSR-4 states that class names must be case sensitive and directly reflect the class name.
For instance, if you have a class named
OrderProduct, PSR-4 states it should be in a file
OrderProduct.php. This is acceptable despite the use of capital letters, as the upper
case letters are used for the purpose of complying with PSR-4.
PSR-4 Compatible Namespaces
All classes will have a common, PSR-4 compliant namespace. A namespace is a logical root for all classes. All namespaces will adhere to the following naming rules:
Username\ProjectNamefor individual projects (e.g, data design).
GroupName\ProjectNamefor capstone projects.
GroupName\Project\Testfor capstone project unit tests.
This naming convention is an adaptation of Java Package Naming that is PSR-4 compatible.
Bracing Style: 1TBS
The official bracing style for Deep Dive Coding is 1TBS, a variant of the K&R style. 1TBS puts a brace after all blocks, even where it's optional on the same line.
Note the example above illustrates the following rules:
- Every block (function, if, loop, etc.) should be opened with a brace on the same line.
- Braces will open a block even when they are considered optional.
- Indentation will increase by one level every block.
- No spaces after keywords defining blocks (e.g., for, while, try, do, etc.).
- A literal tab character '\t' will be used to indent, not spaces.
- No use of the augmented assignment operators (e.g., +=, *=, etc.).
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.
|var xobjs;||var numberOfObjects;|
|$papaSmurf = $results;||$firstResult = $results;|
MySQL/PHP Attribute Naming
It should be clear what MySQL table or PHP class 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:
Better: tweet ID:
Case 2: You have a weak entity containing information linking users to their favorite tweets.
Avoid: A favorite tweet's tweet ID:
Better: A favorite tweet's tweet ID:
Avoid: A favorite tweet's user ID:
Better: A favorite tweet's user ID:
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
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 are special comments that automatically generate documentation for a function, class, or method. In fact, all the documentation at php.net is generated from Doc Blocks. In Deep Dive Coding, we will be using the Javadoc format and use Doxygen to generate documentation. Put doc blocks before every function, class, method, and state variable so it will be documented.
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?
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.
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:
- mySQL Prepared Statements
- PHP's filter_var() family of functions
- Regular Expressions
- HTML5 Form Inputs
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
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).
<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.
<img src="google.png" alt="Google">
<!-- Better -->
<img src="google.png" alt="Google" />
Use UTF-8. Specify the encoding in HTML templates and documents via <meta charset="utf-8" />.
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?
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.
Use HTML5. HTML5 (HTML syntax) is preferred for all HTML documents: <!DOCTYPE html>.
Use valid HTML where possible. Use tools such as the W3C HTML validator to test.
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.
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.
<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.
<p><em>Space</em>, the final frontier.</p>
HTML Quotation Marks
When quoting attributes values, use double quotation marks. Use double ("") rather than single quotation marks ('') around attribute values.
CSS Style Guidelines
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.
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.
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.
Use a semicolon after every declaration.
Separate rules by new lines. Always put a blank line (two line breaks) between rules.
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.
† The use of the underbar is deprecated, and will only be used in cases where backward compatibility is affected.