Skip to content

Code Rules

Universal Guidelines

These guidelines will produce good looking, easy to read, and standardized code. This is not absolutely strict - these are minimum guidelines that should be observed as closely as your personal style will allow you. The odds are pretty good you're already mostly coding this way. If something is not mentioned here, it must be okay, and therefore up to your discretion. If your personal style is different, just make sure that you are consistent.

  • Indentation: Tabs, set to 4-5 spaces
  • Comments: Everywhere. At least one at the beginning of every function and control statement. Prefer single line comments (//) over block comments (/**/) unless it is many paragraphs long, or describing a function or object in greater depth.
  • Object names: Pascal case, like Object, Application, Utility, EntityController
  • Function and Variable names: Camel case with acronyms in caps, like fundNASA(), obeyOrders(), isNull, and citizenID. Functions should for the most part be verbs. Functions that return booleans and boolean variables should start with "is", "has", "will", "can", and other binary verbs. Names should be descriptive, but to the point. For example, isUserLoggedIn() is great, while checkIfUserIsLoggedIn() and LStat() are not.
  • Braces: On the same line as the block declaration.
  • Quotes: Single quotes except where nesting, variable substitutions, or interpolation requires double quotes.
  • Standard functions: Use 'get', 'set', 'goto', 'make', and other verbs as prefixes for functions that perform tasks so that their purpose is obvious.
  • Comparisons: Right-hand comparisons, like ($name === 'Addama') rather than ('Addama' === $name)
  • Equality: Always use === for comparisons unless you absolutely can't.
  • Sources: Provide any useful websites, sources, snippets, facts, and formulas as comments at the beginning of the function or object they helped you create.
  • Spaces: Treat it like punctuation and spacing in English. After every word and punctuation, but not opening parentheses. Use for (var i = 0; i <length; i++) {} not for( var i=0;i<length;i ++ ){}

HTML

<!DOCTYPE html>
<html>
    <head>
        <title>Lorem Ipsum</title>
        <link rel='stylesheet' href='style.css' />
    </head>

    <body>
        <div id="content">
            <section id="section1">
                <header>
                    <h1>Section1</h1>
                </header>
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum varius nunc ex. In a tincidunt odio. Suspendisse ultrices, felis quis semper pellentesque, est tellus blandit purus, ac aliquet quam nulla et est. <code>Sed vel tincidunt lectus.</code> Pellentesque hendrerit ligula nulla, a euismod sapien scelerisque non. Praesent fringilla varius posuere. Curabitur interdum semper nisi, quis scelerisque risus volutpat eget. Sed a rutrum ante. Aenean ultricies ex sit amet lectus rutrum egestas. Sed dictum tincidunt magna, id scelerisque nibh semper sit amet. Fusce varius imperdiet massa eget dignissim. Nulla ac rutrum odio, id luctus magna. Donec consectetur sollicitudin dignissim. Morbi nibh odio, elementum auctor magna in, tempus varius metus. Quisque rhoncus enim nec leo pulvinar, quis aliquet ex malesuada.</p>
                <ul>
                    <li>Item 1</li>
                    <li>Item 2</li>
                </ul>
            </section>
        </div>

        <script type='text/javascript' src='script.js'></script> 
    </body>
</html>
  • Always use <!DOCTYPE html> as your document header.
  • Elements and their attributes should be lower case.
  • Adhere to modern HTML coding standards, and the syntactic intent of the elements you're using.
  • CSS should be in the <head>, and Javascript should be included just above the </body>
  • Always give form elements (input, textarea, etc.) name and ID attributes at a minimum.
  • Indent your code. Try to indent such that the DOM tree structure can be easily followed.
  • Treat HTML like XML: always end every element with a matching closing tag UNLESS it can be self closed (<br />)
  • Avoid in-element style declarations (the style attribute) and javascript event handlers (onload, onclick, etc.).
  • Avoid tables, iframes, and other outdated presentation methods.
  • Surround elements with their angle brackets. None of this ><SPAN business.

Javascript

var Utility = {
    castValue: function(value, type) {
        // Casts a value in a format specified. While this is mostly just stock parse___() functions,
        // it also allows us to convert to specialized formats that would require their own function,
        // but that don't really deserve their own spot in the global.
        var result = '';
        switch (type) {
            case 'float':
                result = parseFloat(value);
                break;
            case 'int':
                result = parseInt(value);
                break;
            case 'string':
                result = String(value);
                break;
        }
        return result;
    },

    getWeather: function() {
        // http://openweathermap.org/weather-data#current
        // https://gist.github.com/alecperkins/6748189
        // Retrieves and stores general weather data (current, not forecasted) for the current location
        var app = this;
        var directions = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW', 'N'];

        var src = 'http://api.openweathermap.org/data/2.5/weather?lat=' + this.position.coords.latitude + '&lon=' + this.position.coords.longitude + '&units=imperial';
        return $.getJSON(src).done(function(result) {
            app.weather = {
                temp: result.main.temp,
                humidity: result.main.humidity + '%',
                pressure: result.main.pressure, // hPa
                coverage: result.clouds.all + '%',
                wind: {
                    speed: result.wind.speed,   // Wind speed in meters per second
                    direction: directions[Math.floor((result.wind.deg + 11.25) / 22.5)],    // Wind direction in ordinal direction
                    bearing: result.wind.deg,   // Wind direction in degrees
                },
                desc: result.weather[0].description,
                category: result.weather[0].main,
                precip: {
                    rain: 0,
                    snow: 0,
                },
            };

            if (result.rain instanceof Object) app.weather.precip.rain = result.rain['3h'];
            if (result.snow instanceof Object) app.weather.precip.snow = result.snow['3h'];
        })
    },
}
  • Assume that you have jQuery and the TS Reuse Library at your disposal on every project.
  • Write all or most of your Javascript in separate files, only putting it in a <script> tag in the HTML when necessary.
  • Always declare variables using var
  • Use var app = this; at the top of functions and objects to solve scope issues.
  • Always end every line (optional on those that end with a curly brace) with a semicolon.
  • Use conditionals ( (test === value) ? 'true' : 'false' ) only when an if statement is needed inside of a string or other non-block element.
  • Contain similar functions inside named objects instead of in the general namespace.
  • Avoid closures like (function() { })();- call your functions like a normal person.
  • When dealing with AJAX, use jQuery promises, and have your function return the promise itself rather than its result. You can still give the promise a .done() handler.
  • You CAN omit braces from if statements (and similar controls) if only one instruction follows it.

PHP

<?php

/**
* isWarmaster: Determines if given name is warmaster
* @param string $name   Name to verify
*/
function isWarmaster($name) {
    switch(strtolower($name)) {
        case 'addama':
            return true;
            break;  // Unnecessary because we used return, but good practice
        default:
            return false;
    }
}

$employeeInfo = array(
    'addama' => array(
        'name'  => 'Addama',
        'title' => 'Lead Developer',
    ),
    'kdoge' => array(
        'name'  => 'Matt',
        'title' => 'Pleb Lord',
    ), // Having a comma on the last item hurts nothing.
);

foreach($employeeInfo as $key => $values) {
    if(isWarmaster($values['name'])) {
        ?>
            Warmaster <a href="http://<?=$key;?>.lamp.ts"><?=$values['name'];?></a> is <?=$values['title'];?> at Tiger Sheep.<br />
        <?php
    } else {
        ?>
            <a href="http://<?=$key;?>.lamp.ts"><?=$values['name'];?></a> is <?=$values['title'];?> at Tiger Sheep.<br />
        <?php
    }
}
?>
  • Always use require_once() and require() as opposed to include()
  • If you just need to print in the middle of a page, use <?=$variable;?>
  • You can do a lot of ugly stuff with PHP. Try to be consistent with your ugliness if you have to make ugly PHP code.
  • If using OOP coding style, separate each class into its own file with the name of the class it contains in a single directory—do not stick everything into one file.
  • Always call functions using parentheses, perhaps with the exception of return.
  • Always use <?php when moving in and out of PHP processing instead of <?, with the only exception being <?=;?> from above.
  • Always properly scope your class, object, function, and variable definitions, otherwise everything lives in the public scope—which is poor practice.
  • Keep scripts that contain sensitive information (login credentials, employee information, etc.) outside of publicly accessible directories.

Resources