Deep Dive Coding 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 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:

  1. All files names shall start with a lowercase letter a…z.
  2. 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 named 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\ProjectName for individual projects (e.g, data design).
  • GroupName\ProjectName for capstone projects.
  • GroupName\Project\Test for 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.

function someFunction($firstParameter, $secondParameter) {
	$answer = 0;
	$limit = $firstParameter + $secondParameter;
	for($i = 0; $i < $limit; $i++) {
		if($i % 2 === 0) {
			$answer = $answer + ($i + 2);
		} else {
			$answer = $answer + ($i + 1);

Note the example above illustrates the following rules:

  1. Every block (function, if, loop, etc.) should be opened with a brace on the same line.
  2. Braces will open a block even when they are considered optional.
  3. Indentation will increase by one level every block.
  4. No spaces after keywords defining blocks (e.g., for, while, try, do, etc.).
  5. A literal tab character '\t' will be used to indent, not spaces.
  6. No use of the augmented assignment operators (e.g., +=, *=, etc.).

The PhpStorm settings file ( Mac OS X) ( Linux) ( Windows) imported during the prework reflects all these rules.

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
var xobjs; var numberOfObjects;
$number_of_objects; $numberOfObjects;
$papaSmurf = $results[0]; $firstResult = $results[0];

Note that variable naming conventions apply equally to CSS, JavaScript, and PHP.

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: 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


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 fact, all the documentation at 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.

 * 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.


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


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" />


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?

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 -->

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.


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.

<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

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.

Declaration Stops

Use a semicolon after every declaration.

Rule Separation

Separate rules by new lines. Always put a blank line (two line breaks) between rules.

Angular File Naming Style

All file names related to angular shall comply to the following naming rules

  1. Use dashes to separate words in the descriptive name. my-file.ts
  2. Do use dots to separate the descriptive name from the type. my-file.component.ts
  3. * Use only conventional type names including .service, .component, .pipe, .module, and .directive.
  4. * Use consistent type names for all components following a pattern that describes the component's route, feature, then its type. route.feature.type.ts.
  5. A file's name should also must match where the file lives in the project relative to the app directory. For example the file landing-page.sign-in.component.html path is /src/app/landing-page/sign-in/landing-page.sign-in.component.html

By default we will be following the official style guide set forth by Angular. Most of the rules above were taken directly from the Angular Style Guide. It is highly recommend that you come back and read the official Angular Style Guide once we start Angular portion of the class.

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.

The use of the underbar is deprecated, and will only be used in cases where backward compatibility is affected.
* denotes where the Deep Dive Style Guide diverges from the official Angular Style Guide