StyleWhy style mattersTwo kinds of styleSyntactic styleBe consistent!Do it right the first timeIndent nested codeBreak up long linesDon’t use “hard” tabsUsing spacesUse meaningful namesMeaningful names: exceptions IMeaningful names: exceptions IIMeaningful names: exceptions IIINaming classes and interfacesNaming variablesNaming methodsNaming constantsCorrect (syntactic) style made easySemantic StyleThink smallDesign before you programTest firstKeep it DRY (Don’t Repeat Yourself)Refactor, early and oftenCommentDo user testingThe EndJan 14, 2019StyleWhy style mattersGood style isn’t just to make your code “look pretty”The most critical factor in style is readabilityIf a program is readable,It is easier to debugIt is easier to maintainIt is easier to upgradeFor “real” programs (those that actually get used), the time spent reading them far exceeds the time spent writing them2Two kinds of style“Syntactic” styleMostly pretty mechanical: Spacing, indentation, capitalization, etc.Eclipse can do a lot of this for youSome more conceptual, for example, the names of methods should be verbsSyntactic style is easier to define“Semantic” styleLargely or completely non-mechanicalRules are “slippery,” harder to describe and to applyLearned largely through experienceBut only if you are willing to experiment and try new approachesUltimately much more important than syntactic style3Syntactic style5Be consistent!Most times, you will enter an ongoing project, with established style rulesFollow them even if you don’t like themAs they are what your team is used to, they will be more readable to other members of your team6Do it right the first timeYou only write code once, but you read it many times while you’re trying to get it to workGood style makes it more readable and helps you get it right!You’re 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 quicklyGuess which program will be around longer and used by more people?7Indent nested codeAlways indent statements that are nested inside (under the control of) another statementif (itemCost <= bankBalance) { writeCheck(itemCost); bankBalance = bankBalance - itemCost;}The open brace always goes at the end of a lineThe matching close brace lines up with the statement being closedDon’t use C-style braces unless that is the already established standard for the project you are onIndentation should be consistent throughout the program4 spaces is the standard for Java (other languages may differ)8Break up long linesKeep your lines short enough to be viewed and printedMany people use 72 or 80 character limitsSuggestions on where to break a long line:It’s illegal to break a line within a quoted stringBreak after, not before, operatorsLine up parameters to a methodDon’t indent the second line of a control statement with a long test so that it lines up with the statements being controlled9Don’t use “hard” tabsA hard tab is an actual tab character in your textIt tells the program to go to the next tab stop (wherever that is)Not every program puts tab stops in the same placeIf you use hard tabs to indent, sooner or later your nice indentation will be ruinedGood editors can be set to use soft tabs (your tab characters are replaced with spaces)When you hit the tab key, the editor puts spaces into your file, not tab charactersWith soft tabs, your indentation is always safe10Using spacesUse spaces around all binary operators except “dot”: if (n > 1 && n % 2 == 1) n = 3 * n + 1; Do not use spaces just within parentheses: if ( x < 0 ) x = -x; // don’t do thisUse a space before and after the parenthesized test in a control statement: if (x < 0) {...} while (x < 0) {...}Do not use a space between a method name and its parameters; do put a space after each comma: int add(int x, int y) {...} a = add(3, k);11Use meaningful namesNames should be chosen very carefully, to indicate the purpose of a variable or methodIf the purpose changes, the name should be changedSpend a little time to choose the best name for each of your variables and methods!Long, multiword names are common in JavaEclipse will complete long names for you (control-space)However, if a name is too long, maybe you’re trying to use it for too many purposesDon’t change the name, separate the purposesDon’t abbreviate namesBut very common abbreviations, such as max for “maximum”, are OK12Meaningful names: exceptions IIt 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 loopThis is almost always better than trying to come up with a meaningful nameExample:for (int i = 1; i <= 10; i++) { for (int j = 1, j <= 10; j++) { System.out.println(" " + (i * j)); }}13Meaningful names: exceptions IILocal variables in methods may be given short, simple names, if:The purpose of the variable is obvious from context, andThe variable is used only briefly, in a small part of the programBut never use meaningless names for fields (class or instance variables) or classes or methods14Meaningful names: exceptions IIIIf variables have no special meaning, you can use names that reflect their typesFor 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 namess, t, u, or s1, s2, etc. are often used for Stringsp, q, r, s are often used for booleansw, x, y, z are often used for real numbers15Naming classes and interfacesCapitalize the first letter of each word, including the first word: PrintStream, Person, ExemptEmployeeUse nouns to name classes: ExemptEmployee, CustomerAccountClasses are supposed to represent thingsUse adjectives to name interfaces: Comparable, PrintableInterfaces are supposed to represent features16Naming variablesCapitalize the first letter of each word except the first: total, maxValueUse nouns to name variables: balance, outputLineVariables are supposed to represent values17Naming methodsCapitalize the first letter of each word except the first: display, displayImageMethods are capitalized the same as
View Full Document