nestle - zaka (108)

Upload: zakavision

Post on 09-Apr-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 Nestle - Zaka (108)

    1/22

    Writing Maintainable Code

    Shaun Moss

    March 2008

    [email protected]

  • 8/8/2019 Nestle - Zaka (108)

    2/22

    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.

  • 8/8/2019 Nestle - Zaka (108)

    3/22

    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

  • 8/8/2019 Nestle - Zaka (108)

    4/22

    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;

    }

  • 8/8/2019 Nestle - Zaka (108)

    5/22

  • 8/8/2019 Nestle - Zaka (108)

    6/22

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

    This is for increased clarity, facilitates object-oriented database

    programming (where records from multiple tables are

    combined), plus you can use USING in JOINs.

  • 8/8/2019 Nestle - Zaka (108)

    7/22

    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_id

    names, e.g. customer_name, country_name

  • 8/8/2019 Nestle - Zaka (108)

    8/22

    Naming Patterns - Application-wide

    Rule 8: For all variables and values that matchdatabase 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: 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);

  • 8/8/2019 Nestle - Zaka (108)

    9/22

    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.

  • 8/8/2019 Nestle - Zaka (108)

    10/22

    Hungarian Notation for Page Elements

    Rule 9: Use Hungarian notation for pageelements/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 selector

    rb: radio button rbg: radio button group

    cb: checkbox frm/form: form

    btn: button div: div

  • 8/8/2019 Nestle - Zaka (108)

    11/22

    Naming Variables andFunctions

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

    For function names, use either, but BECONSISTENT so that

    other programmers can detect patterns in your code.

  • 8/8/2019 Nestle - Zaka (108)

    12/22

    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:

    updateR

    ec() 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.

  • 8/8/2019 Nestle - Zaka (108)

    13/22

    Function Naming Using Parts of Speech

    Rule 12: Name procedural functions likeverbNoun() 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);

  • 8/8/2019 Nestle - Zaka (108)

    14/22

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

  • 8/8/2019 Nestle - Zaka (108)

    15/22

    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.

  • 8/8/2019 Nestle - Zaka (108)

    16/22

    Constants

    Rule 19: Name constants with UPPER_CASE. A tradition from C.

    e.g. MAX_N_COLOURS, COUNTRY_ID_AU

    U

    se naming patterns with constants as well: ACCOUNT_TYPE_MEMBER ACCOUNT_TYPE_ADMIN ACCOUNT_TYPE_SUPERUSER

  • 8/8/2019 Nestle - Zaka (108)

    17/22

    Consistency Rule 20: Be consistent with abbreviations, and

    documentthem somewhere.

    qty = quantity amt = amount txn = transaction

    cust = cust calc = calculate rec = record

    db = database rs = recordset dt = datetime

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

  • 8/8/2019 Nestle - Zaka (108)

    18/22

    XHTML

    Rule 23: Use both name and id attributes for form

    fields, and make them the same.

    'id' is used by JS, 'name' is used by PHP.

    Rule 24: Exception radio buttons. Use arraynotation. 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. Male

    Female

  • 8/8/2019 Nestle - Zaka (108)

    19/22

    PHP tags

    Should you use

  • 8/8/2019 Nestle - Zaka (108)

    20/22

    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.

  • 8/8/2019 Nestle - Zaka (108)

    21/22

    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.

  • 8/8/2019 Nestle - Zaka (108)

    22/22

    Ideas for next presentation

    Always use double-quotes for HTML and SQL

    strings.

    Use variables for constants that are often

    embedded in strings (e.g. $baseUrl) How to protect against SQL injection attacks.

    Why to avoid stored procs.