Programming Style Guide: Guidelines

GVSU Libraries Programming Style Guide

While most development in the library is done in HTML, CSS, PHP, and Javascript, we have tried to keep the conventions generic so that they can apply to any language.

Variable creation and naming

In most of our development languages, variables are loosely typed, which means the type of data they can hold is determined at runtime.  This means variables can be declared anywhere in the program, and the type of data a variable can hold can change as the program executes.

However, using variables this way is not necessarily conducive to readability.  It’s therefore important to observe some conventions when creating and naming variables:

The type of data a variable holds should not change unless absolutely necessary.  A variable holding a string should continue to hold strings for the life of the program.  If you need to hold a different value, try to create a new variable for it.

Variable names should be descriptive of their contents.  Using longer, more descriptive variable names is preferred to using short, vague names.  “isLoggedIn” is a preferable name for a boolean that indicates whether the user is logged in than “login.”  The exception here are variables with limited scope, for example, a control variable used to increment a loop.  Such variables can be given single character names to indicate their temporary usage.  

// perfectly acceptable
for (int x = 0; x > n; x++) {
}
x = login.getType();

//this is not okay
If (!x) {
    Doo foo;
}

Variable names should be mixed case starting with lower case.  For example, isLoggedIn, not Isloggedin.  Research has shown that we recognize words primarily by shape, so using mixed capitalization makes it easier to recognize names.

Names should be written in English.  Do not use foreign words in variable names. Do not use emoji as variables. (Yes, it is possible. Don't do it.)

Variables holding Booleans or values serving a similar purpose in control structures should use a prefix such as is, can, has, or should.  Examples: isLoggedIn, shouldPrint, canResize, isFound, hasBeenInput..

Avoid abbreviations or acronyms, unless it is a standard, widely used acronym such as HTML, XML, etc.  If it isn’t, write out a longer, more descriptive variable name.  If using an existing and well-understood acronym, such as HTML or XML, do not capitalize the entire acronym, but follow the mixed-case capitalization rules (htmlTemplate, xmlParser, getHtml, findCss).  This keeps you from confusing acronyms with constants (see below).

//You are not going to know what this is in a months time
isAbbrFunct = this.function();

//much more readable
abbreviatedString = this.abbreviate();

Names of constants should be in all caps.  You can also use this technique for languages that don’t support constants to signal to others that they should not change the value of the variable in the body of the program.

All nontrivial, non-control variables should be preceded with a one-line comment either when instantiated or when first used that indicates what the variable is for any what type of value it holds.  The only exceptions are control variables used in loops. Example:  

//Varible to check to see if the screen can be resized
public Boolean canResize;

Naming methods and functions

Method, object, and function names follow the same mixed-case capitalization rules as variables.

Method and function names should be indicative of what they return, if they return a value, and what they do if not.  Examples: logInUser, getInteger, returnRatio, redirectUser.

Abstract and interface classes should have the words “_Abstract” or “_Interface” appended to their classnames:

chessboard_Abstract
loginObject_Interface

Writing code

In general, strive to keep line length under eighty characters.  Longer lines can scroll off the screen and make code hard to read.  There are situations in which long lines are necessary, but those should be the exception.

Proper code indentation is absolutely necessary.  Contents of functions, object classes, and the contents of loops and control structures should be appropriately indented to show which structures statements “belong to.”  

With the exception of Class declarations, closing braces are always placed on a line by themselves, and indented at the same level as the control statement that "owns" them.

If (foo == bar) {
    //we are now doing foo
    do foo;
}

Control structures: Where possible, avoid nesting conditional statements.  These are hard to read through.  Instead, make use of branching structures such as if/elseif, or create multiple Boolean values that can be checked in one conditional:

If (isEdited && !isListed && canBeCopied) { do foo}


If (isEdited) {
    If (!islisted) {  // try not to do this!
        Do foo;
    }
}

 

Every file containing code should begin with a multiline comment that describes the purpose of the code, who wrote it, and a version number or date of creation.

/*
*Script to log library instruction statistics
*
*
*Author: Kyle Felker
*Version 1.0
*/

Objects should have a similar header block that describes the purpose of the structure, the author, and a version number or date.

Functions and methods should have multiline comments that describe what the method or function does, what parameters it accepts, and what values it returns (if any).  If the language does not require that you declare what errors it throws (as PHP does not), then any errors that may be thrown must also be detailed in your header.

/*
*Function that checks returned login name against a *database of librarian names
* @ param string login: the login name returned from the *login script
*
*@ return Boolean indicating if the user is a librarian
*
*/


If you need to include code from an outside source, all such statements should be placed near the beginning of the document.

Separate classes should be put in separate files unless doing so would impact execution speed.

Developers working in Windows need to ensure their line breaks are converted to UNIX line breaks before code is uploaded to production.

Any code that produces an HTML document should produce a full, valid HTML document according to the most current HTML specification (right now, HTML 5).  This typically includes a doctype declaration, HTML tags, a header with a title, and a properly implemented body tag at the bare minimum.  Do not output badly-formed or invalid HTML.  You can create functions or template objects that wrap messages in valid HTML to output messages quickly and in valid format.

<P>This is a user message</P> <!--This is bad-- >

<!DOCTYPE html>
<HTML>
<head>
<title>This is a valid HTML 5 Document</title>
</head>
<body>
<P>This is a user message.</P>
</body>
</html>

Never combine multiple statements on the same line.

Foo = bar;  if (foo > bar) {do foo}; //don’t do this

All code used for debugging should be removed or commented out before code goes live.

SQL keywords are always capitalized: INSERT, SELECT, UPDATE TABLE, etc.  Beak up long queries into multiple lines so that they are more readable.

Handling Errors

Code should function correctly without displaying warnings to users.  Use current coding practices for your language and avoid outdated constructs and methods.

If it’s possible for code to throw an error, the code should use some variant of a try/catch construct to deal with it.  If the language does not support such a construct, at least use a conditional statement to check for the error.  Good examples of times when this is necessary are attempts to load or save data from an external file or to make a connection to, retrieve data from, or save data to a remote database.

Do not call system variables like $_COOKIE without first checking to see if they have been properly instantiated using a construct like ISSET or the PHP negation operator.

If an error happens, the code should display a concise message describing what happened to the users screen.  This will be helpful in debugging the problem.  You could also have the program itself email a copy of the message to you.

PHP Specific

Always use the <?php ?> syntax instead of the <? ?> syntax.

Try to avoid mashing PHP and HTML together.  Have your PHP scripts generate the HTML they need within the script block.  This makes documents easier to read.  Use the heredoc syntax for long blocks of code: (NOTE: Matthew *completely disagrees with this practice.*)

<?php
echo <<<HTML
<html>
<head> <title>$title</title>
</head>
</html>
HTML;

If your file contains only php code, the closing ?> bracket is not required, and omitting it prevents the accidental injection of trailing whitespace, which can produce errors.

Header Code Samples

/**
 *Super Class
 *
 *Here is a brief description of what this class does
 *
 * @package    Package Name
 * @subpackage    Subpackage
 * @category    Category
 * @author    Author Name
 * @link    http://example.com
 * @param Parameter accepted (for methods and functions)
 * @Error Any error the class, function or object can throw
 * and conditions under which it will be thrown
 */
class Super_class {

 

Your friendly Web Services Librarian

Matthew Reidsma's picture
Matthew Reidsma
Contact:
340C LIB
(616) 331-3577
Website

Digital Initiatives Librarian

  • Last Updated: Nov 10, 2016 1:31 PM
  • URL: https://libguides.gvsu.edu/coding