writing maintainable code
DESCRIPTION
Shaun Moss March 2008 [email protected]. Writing Maintainable Code. Benefits. INCREASED PRODUCTIVITY. Save huge amounts of time and $$$ during implementation and maintenance phases. Coding shortcuts. Ease of maintenance and repairs. Code that's easy to learn and understand. - PowerPoint PPT PresentationTRANSCRIPT
Benefits INCREASED PRODUCTIVITY. Save huge amounts of time and $$$ during
implementation and maintenance phases. Coding shortcuts. Ease of maintenance and repairs. Code that's easy to learn and understand. Other developers will be happy to work with
the code (outsourcing, delegating). Improved communication between developers. Looks professional. The software will be around for longer.
Coding Standards What are they? Code formatting patterns. Syntax patterns. Naming patterns. Benefits: Improved code readability. Improved productivity and maintainability. Reduce errors. Existing standards: PEAR: http://pear.php.net/manual/en/standards.php Java: http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html
Coding Standards - Formatting
Indenting. Pos of braces:
K&R: Same line. Allows more useful lines of code on-screen. function doStuff($x, $y, $z) {
$x++;echo $x + $y*$z;
} Allman: Next line. Can improve readability.
function doStuff($x, $y, $z){
$x++;echo $x + $y*$z;
}
Coding Standards - Formatting
Pos of spaces, commas, semi-colons, etc. General patterns:
Function calls: mult($x, $y);
Function declarations: function mult($x, $y)
Control structures: if ($x == $y) while ($x == $y) for ($i = 0; $i < 100; $i++)
Operators: $z = $x + $y; $a = $x - $y*$z; $b = $a++; $s = $catName.” is a cat”; // “$catName is cat”
Naming Patterns – DB Tables Rule 1: lower_case MySQL database table names.
This avoids problems when deploying MySQL databases on different operating systems. e.g. person, basket_item
Rule 2: Use singular for table names. Saves typing, easier refactoring. e.g. category not categories
Rule 3: Use underscore for linking tables. Linking tables implement many-to-many relationships between
two other tables. e.g. person, club, person_club Rule 4: Name primary keys same as foreign keys.
e.g. customer.customer_id, not customer.idThis is for increased clarity, facilitates object-oriented database programming (where records from multiple tables are combined), plus you can use USING in JOINs.
Naming Patterns – DB Columns
Rule 5: Use lower_case for column names.Provides consistency with table names.
Rule 6: Prefixes'n' = “number of”, e.g. n_items'd' = “date of”, e.g. d_birth, d_create't' = “time of”, e.g. t_start'dt' = “datetime of”, e.g. dt_sent'is', 'has', 'to' for booleans, e.g. is_sent, has_joined, to_check
Rule 7: Suffixesunits, e.g. price_aud, mass_kg, length_m, duration_sids, e.g. customer_id, basket_idnames, e.g. customer_name, country_name
Naming Patterns - Application-wide Rule 8: For all variables and values that match
database column names, use exact same name in XHTML, CSS, JavaScript and PHP.e.g. if the database column name is first_name, then also use:XHTML: <input name='first_name' id='first_name' />PHP: $first_name = (int)$_POST['first_name'];CSS: #first_name {color:Red;}JS: var first_name =
document.getElementById('first_name').value;
This will reduce errors, improve understandability and maintainability of code, and allows some nice tricks like:
$rec = $rs->fetch_assoc();extract($rec);
OR:$cust = new Cust($_POST);
Hungarian Notation
Hungarian notation means using prefixes to indicate type. 'b' = bool, e.g. $bDone 'i' = int, e.g. $iCount 'f' = float, e.g. $fRadius 's' = str, e.g. $sName
Generally cumbersome and unnecessary. Does not always improve code readability or
understandability. e.g. $count is obviously a number. $name is obviously a string.
Good naming is better.
Hungarian Notation for Page Elements
Rule 9: Use Hungarian notation for page elements/document objects/controls/widgets: This distinguishes them from the value they contain. JavaScript:
var tbFirstName =document.getElementById('first_name');
var first_name = tbFirstName.value; PHP:
$tbFirstName = new Textbox('first_name',$first_name);
Some standard prefixes:tb/txt: textbox ta/txt: textareasel: select box dsel: date selectorrb: radio button rbg: radio button groupcb: checkbox frm/form: formbtn: button div: div
Naming Variables and Functions
lower_case or camelCase? lower_case is a PHP/MySQL pattern. camelCase is a Java/JavaScript pattern. ProperCase is a MS/.NET pattern.
Rule 10: Use lower_case and/or camelCase for variables and functions For PHP/JS vars that match DB cols, always use lower_case. For vars that refer to objects or page elements, use camelCase
with Hungarian notation, e.g. $selCountry; In other cases use lower_case or camelCase as desired, but BE
CONSISTENT. For function names, use either, but BE CONSISTENT so that
other programmers can detect patterns in your code.
Function Naming Patterns
What not to do: update_record() DeleteRecord() getRec() display_rec() etc.
Or: $rec->Update(); $rec->delete(); $rec->getRec(); $rec->display_rec();
What to do: updateRec() deleteRec() getRec() displayRec() etc.
Or: $rec->update(); $rec->delete(); $rec->select(); $rec->display();
Rule 11: Use consistent patterns Esp. within your classes and libraries, so that other
programmers (and you) can learn and remember them easily.
Function Naming Using Parts of Speech
Rule 12: Name procedural functions like “verbNoun()” calcRisk(), updateRec(), openDB(), washDog()
Rule 13: Functions that return booleans start with verbs-to-be, e.g. 'is', 'to', etc.: isComplete(), toCheck()
Rule 14: For functions that return numeric/string values use simple names, usually nouns (like mathematical functions): sqrt(), strlen() age(), integrate(), tanh(), colour(), shirtSize() i.e. we say $y = tan($x), not $y = calcTangent($x);
Function names prefixes
Rule 15: To avoid name collisions, use prefixes for functions within libraries: mysql_query(), mysql_fetch_assoc() dtlNow(), dtlYear()
OR use classes instead msqyli::query(), mysqli::fetch_assoc() DTL::now(), DTL::year()
Rule 16: Use 'get' and 'set' to access private or protected attributes. get_product_id(), set_product_id() getName(), setName()
Classes
Rule 17: Use ProperCase for class names This clearly distinguishes them from other code elements. e.g.
class Database() class Customer() class Ellipse()
Rule 18: Map table names to class names. Many classes match one-to-one with database tables. e.g. if the table is named customer, the class is named
Customer. If the table is named basket_item, the class is named BasketItem.
Constants
Rule 19: Name constants with UPPER_CASE. A tradition from C.
e.g. MAX_N_COLOURS, COUNTRY_ID_AU Use naming patterns with constants as well:
ACCOUNT_TYPE_MEMBER ACCOUNT_TYPE_ADMIN ACCOUNT_TYPE_SUPERUSER
Consistency Rule 20: Be consistent with abbreviations, and
document them somewhere.qty = quantity amt = amount txn = transactioncust = cust calc = calculate rec = recorddb = database rs = recordset dt = datetimeHungarian notation prefixes: tb, sel, rb, cb, etc.
Rule 21: Be consistent with suffixes. e.g. if you use “_id” as your id suffix in your database, use this
throughout the app for every id. Not a mixture of “_id”, “_ID”, “Id”, “”.
Rule 22: Be consistent with meaning. Don't re-use variables for different things. e.g. $cust_id = getNickname($cust_id); // don't do this If a variable with an “_id” suffix is an int, make it always an int.
XHTML
Rule 23: Use both name and id attributes for form fields, and make them the same.
<input id='first_name' name='first_name' /> 'id' is used by JS, 'name' is used by PHP.
Rule 24: Exception – radio buttons. Use array notation. Radio buttons are grouped by the name attribute, but ids need
to be unique on a page. Array notation for ids gives advantages with JS.
<input id='gender[1]' name='gender' value='1'/> <label for='gender[1]'>Male</label>
<input id='gender[2]' name='gender' value='2'/> <label for='gender[2]'>Female</label>
PHP tags Should you use “<?php” or “<?” ?
PHP standard is to use “<?php” (short tags have been deprecated)
However – short tags save typing, increase productivity.c.f. '<?=' with '<?php echo'
Conclusion
Coding standards, formatting and naming patterns are important - don't neglect or leave until the end.
Can save you a lot of time during implementation, debugging and maintenance.
Makes your code easier to read and understand. Makes your code look professional and well-
designed to other programmers. Makes your life easier. Saves you and your client lots of money.
Plan carefully and you will have plenty.
Get good advice and you will succeed.
If you have to choose between a good reputation and great wealth, choose a good reputation.