Style - PowerPoint PPT Presentation

1 / 33
About This Presentation
Title:

Style

Description:

Comparable, Printable. Interfaces are supposed to represent features ... be seen by the entire world! ... and use a set of keywords to flag unresolved issues. ... – PowerPoint PPT presentation

Number of Views:44
Avg rating:3.0/5.0
Slides: 34
Provided by: DavidMa5
Category:
Tags: flags | of | printable | style | the | world

less

Transcript and Presenter's Notes

Title: Style


1
Style
  • Consolidated Lectures

2
About the book
  • This book is a team effort by many good
    programmers, not just one persons opinions
  • The rules have been widely distributed and
    commented upon
  • The rules reflect widespread and accepted
    practices
  • And no, I dont agree with everything in the
    book!

3
Rule 1 Adhere to the style of the original
  • Consistent style is very important
  • Most times, you will enter an ongoing project,
    with established style rules
  • Follow them even if you dont like them
  • Dont try to establish better style rules
  • It wont work anyway
  • There may be reasons you dont know about
  • If a project has mixed styles with no
    consistency, you might try to get people to agree
    on one

4
Rule 3 Do it right the first time
  • Youre working on a large project, so you use
    good style...
  • ...but you need a tool to help you do one little
    job, so you slap it together quickly
  • Guess which program will be around longer and
    used by more people?

5
Rule 5 Indent nested code
  • Always indent statements that are nested inside
    (under the control of) another statement
  • if (itemCost lt bankBalance)
    writeCheck(itemCost) bankBalance
    bankBalance - itemCost
  • while (seconds gt 0) System.out.print(seconds
    "...") seconds seconds - 1
  • Indentation should be consistent throughout the
    program
  • 2 to 4 spaces is usually about right

6
Rule 6 Break up long lines
  • Scrolling a window horizontally is a pain!
  • When you print on standard paper, long lines are
    either cut off or wrap in bad places
  • I have long used a 72 character limit
  • Some editors will show you a limit line
  • The book provides good advice on how to break up
    long lines (read it!)

7
Rule 8 Dont use hard tabs
  • Once upon a time, you could depend on tab stops
    every eight character positions
  • Today, every editor has its own idea of where and
    how to set tab stops
  • If you change editors, your nice indentation gets
    ruined
  • Its worse if you use both tabs and spaces
  • I have learned this one the hard way!
  • A hard tab is an actual tab character in your
    text
  • Good editors can be set to use soft tabs (your
    tab characters are replaced with spaces)
  • BlueJ uses only soft tabs

8
Rule 9Use meaningful names
  • Names should be chosen very carefully, to
    indicate the purpose of a variable or method
  • If the purpose changes, the variable or method
    should be renamed
  • It is worthwhile spending a little time choosing
    the best name
  • Long, multiword names are common in Java

9
Rule 10 Use familiar names
  • Where common terminology exists, use it dont
    make up your own
  • Example from the book If your users refer to
    customers, your program should use the name
    Customer, not Client

10
Rule 11 Question excessivelylong names
  • Variables should be used for a single purpose
  • Methods should do one simple, clearly defined
    thing
  • If a descriptive name is overly long, maybe the
    variable or method is trying to serve too many
    purposes

11
Meaningful names exceptions I
  • It is common practice to use i as the index of a
    for-loop, j as the index of an inner loop, and k
    as the index of a third-level loop
  • This is almost always better than trying to come
    up with a meaningful name
  • Example
  • for (int i 1 i lt 10 i) for (int j
    1, j lt 10 j) System.out.println("
    " (i j))

12
Meaningful names exceptions II
  • Method variables may be given short, simple
    names, if
  • The purpose of the variable is obvious from
    context, and
  • The variable is used only briefly, in a small
    part of the program
  • But never use meaningless names for class or
    instance variables

13
Rule 28 Use standard names for throwaway
variables
  • If variables have no special meaning, you can use
    names that reflect their types
  • For example, if you are writing a general method
    to work with any strings, you might name them
    string1, string2, etc.
  • Alternatively, you can use very short names
  • s, t, u, or s1, s2, etc. are often used for
    Strings
  • p, q, r, s are often used for booleans
  • w, x, y, z are often used for real numbers

14
Rule 12 Join the vowel generation
  • Despite the cutesy name, this rule is important
  • In more primitive languages, names were often
    limited to 8 or so characters
  • This led to names like maxVolum and lngPlyng
  • The usual rule was to leave out vowels, starting
    from the right
  • Such names are harder to read and to remember
  • Do not leave out vowels, or otherwise use unusual
    abbreviations, in Java!

15
Naming classes and interfaces
  • Rule 18 Capitalize the first letter of each
    word, including the first PrintStream,
    Person, ExemptEmployee
  • Rule 19 Use nouns to name classes
    ExemptEmployee, CustomerAccount
  • Classes are supposed to represent things
  • Rule 20 Use adjectives to name interfaces
    Comparable, Printable
  • Interfaces are supposed to represent features

16
Naming variables
  • Rule 25 Capitalize the first letter of each word
    except the first total, maxValue
  • Rule 26 Use nouns to name variables
    balance, outputLine
  • Variables are supposed to represent values

17
Naming methods
  • Rule 22 Capitalize the first letter of each word
    except the first display, displayImage
  • Methods are capitalized the same as variables
  • Rule 23 Use verbs when naming methods
    displayImage, computeBalance
  • Methods are supposed to do something

18
Rule 13 Capitalize only the first letter in
acronyms
  • In names, write acronyms such as GUI and API as
    Gui and Api
  • Examples setDstOffset, displayAsHtml,
    loadXmlDocument
  • Since capital letters are used to separate names,
    this rule helps avoid confusion
  • Suns APIs dont always follow this convention

19
Naming constants
  • A constant is an identifier whose value, once
    given, cannot be changed
  • Constants are written with the keyword final, for
    example
  • final int FIVE 5
  • final float AVOGADROS_NUMBER 6.022E23
  • Rule 31 Constants are written in ALL_CAPITALS,
    with underscores between words
  • Exception color names, such as Color.pink
  • Colors were defined before conventions were
    established
  • However, Java 1.4 adds properly capitalized names
    for colors, such as Color.PINK

20
Kinds of comments
  • Standard (C-style) comments / ... /
  • One-line and end-line comments// a one-line
    comment is on a line by itselfx 0 // an
    end-line comment follows code
  • All of the above are internal comments, seen
    only by someone looking at your code
  • Internal comments are only for maintainers
  • But avoid things that would embarrass you to a
    user!
  • Documentation (javadoc) comments / ... /
  • These are meant to be seen by the entire world!
  • Documentation comments are not covered in this
    series of slides

21
Which kind of internal comment?
  • Rule 36 Use standard (/.../) comments to
    comment out code without removing it.
  • This is a quick way to comment out and uncomment
    code
  • This rule isnt actually appropriate for us
  • BlueJs comment and uncomment commands make it
    easier to use one-line (//...) comments
  • Standard comments cannot be nested, so its
    tricky commenting out code with comments
  • One-line comments dont have this problem

22
Explaining the code I
  • Rule 59 Add internal comments only if they will
    aid in understanding your code.
  • Dont repeat the javadoc comments
  • Dont put in comments to explain things that are
    obvious from the code
  • Dont put in irrelevant or useless comments
  • // Go Cubs!!!!
  • Always put / ... / comments before the code
    they describe, never after the code

23
Explaining the code II
  • Rule 37 Use one-line comments to explain
    implementation details.
  • One-line comments are also good for writing
    reminders for yourself about things you still
    need to work on
  • // These assertions should be replaced by
    Exceptions
  • I like to use one-line comments to tell what the
    next several lines of code are going to do
  • // Put this Vehicle in a random location

24
End-line comments I
  • Rule 61 Avoid the use of end-line comments.
  • This rule is largely to prevent overly long lines
  • But Rule 62 says Explain local variable
    declarations with an end-line comment.
  • int edgeDistance // distance to the nearest edge
  • And Rule 64 says Label closing braces in highly
    nested control structures.
  • // end switch // end if //
    end for j // end for i
  • Better yet, avoid highly nested control structures

25
End-line comments II
  • I also find end-line comments useful for an else
    that is a long way from its if
  • if (distance gt 5) ... a lot of code in
    between ...else // distance lt 5 ...
  • But now that we have assert statements, this is
    even better
  • ...else assert distance lt 5

26
Flagging unresolved issues
  • Rule 63 Establish and use a set of keywords to
    flag unresolved issues.
  • I personally like to use
  • // the canvas isn't being redrawn properly
  • More specific flags are likely to be used in
    large projects
  • // DLM Problem 1403 Level Urgent

27
Intentionally missing break
  • Rule 65 Add a fall-through comment between two
    case labels of a switch statement, if no break
    statement separates those labels.
  • The switch statement is so badly designed that
    forgetting the break is a common error
  • To keep an intentionally missing break from being
    corrected, add a comment

28
Label empty statements
  • Sometimes you intentionally use a loop with an
    empty statement body
  • Rule 66 Label empty statements.
  • while ((c reader.read()) space) //
    Empty body
  • This is because the semicolon is small and easy
    to overlook
  • I prefer a different solution use an empty block
    as the statement body
  • while ((c reader.read()) space)

29
Dont repeat the code
  • Rule 60 Describe why the code is doing what it
    does, not what the code is doing.
  • Another way of saying this isComments should
    not echo code.
  • Heres a typical example of a bad comment
  • count 0 // set count to zero
  • You should assume that anyone reading your
    internal comments knows some Java!

30
Use the active voice
  • Rule 34 Use the active voice, and omit needless
    words
  • // zero out the array
  • // each of the elements of the array is set to//
    zero by the following loop
  • Writing comments is still writing--all the rules
    for good writing apply to comments
  • Best reference The Elements of Style, by Strunk
    and White

31
Debugging statements
  • We sometimes put in debugging statements that we
    plan to remove afterwards
  • Simple trick start these temporary statements
    in the first column, so you can find them easily
  • boolean legalLocation(int row, int
    col) System.out.println("In legalLocation "
    row " " col) return row gt
    0 row lt numRows
    column gt 0 column lt numCols

32
The End
33
The End
Write a Comment
User Comments (0)
About PowerShow.com