360 likes | 543 Views
Top 10 Java Style Conventions. Ed Gibbs. Overview. All java development is supposed to follow The Elements of Java Style. While 100% compliance isn’t necessary you should have a good reason. Standardized code is easier to read and easier to maintain. This is mostly a reminder presentation.
E N D
Top 10 Java Style Conventions Ed Gibbs
Overview • All java development is supposed to follow The Elements of Java Style. • While 100% compliance isn’t necessary you should have a good reason. • Standardized code is easier to read and easier to maintain. • This is mostly a reminder presentation.
Indent nested code • Elements of Java Style #5 • Curly braces { start at the end of the line that introduces the project • Closing brace } goes at the end on it’s own line
Indent nested code • Bad examples: public void getName() { return this.name } try { EmployeeManagerDao dao = EmployeeFactory.getInstance(); } catch (DataException e) { e.printStackTrace(); }
Indent nested code • Good examples: public void getName() { return this.name } try { EmployeeManagerDao dao = EmployeeFactory.getInstance(); } catch (DataException e){ e.printStackTrace(); }
Use meaningful names • Elements of Java Style #9 • Use a name that will be meaningful for a developer who reads your code 2 years later. • Avoid single character variables. • Doesn’t apply to temporary counter variables like ‘i’ in a for loop.
Use meaningful names • Bad examples: Person p = new Person(); //… a lot of other code p.setId(1); Date d = p.getBirthDate(); Date cur = new Date(); boolean v = false; if (d.after(cur)) { v = false; } else { v = true; }
Use meaningful names • Good examples: Person person = new Person(); //… a lot of other code person.setId(1); Date personBirthDate = p.getBirthDate(); Date currentDate = new Date(); boolean validBirthDate = false; if (personBirthDate.after(currentDate)) { validBirthDate = false; } else { validBirthDate = true; }
Join the vowel generation • Elements of Java Style #12 • Abbreviations reduce readiblity.
Join the vowel generation • Bad examples: private FBean exec(String ref) { // do something } public void procLn (String ln) { // do something }
Join the vowel generation • Good examples: private LoanPackageFormBean executeUpdate(String loanReferenceNumber) { // do something } public String processLineFormatting (String line) { // do something }
Capitalize only the first letter in acronyms • Elements of Java Style #13 • Eliminates confusion when uppercase letters act as separators. • Especially important if two acronyms follow each other. • It’s not unusual to see code with some acronyms capitalized and others not.
Capitalize only the first letter in acronyms • Bad examples: setWALTSSeparator(); createPersonDAO(); loadXMLReprentation();
Capitalize only the first letter in acronyms • Good examples: setWaltsSeparator(); createPersonDao(); loadXmlReprentation();
Use nouns when naming classes • Elements of Java Style #19 • Classes define things. • Classes should be easily identifiable from their names.
Use nouns when naming classes • Bad examples: Wfn00; BirdClass; Proc;
Use nouns when naming classes • Good examples: Wfn00; Loan; BirdClass; Bird; Proc; ProcessController;
Use lowercase for the first word and capitalize only the first letter after • Elements of Java Style #22 • The capitalization allows the name to be read more easily. • Lowercase first word differentiates between methods and constructors.
Use lowercase for the first word and capitalize only the first letter after • Bad examples: GetAmount(); EXEC(); Start();
Use lowercase for the first word and capitalize only the first letter after • Good examples: GetAmount(); getAmount(); EXEC(); execute(); Start(); start();
Pluralize the names of collection references • Elements of Java Style #27 • Allows the reader to differentiate between single value and multiple value variables.
Pluralize the names of collection references • Bad examples: ArrayList borrower = new ArrayList(); String[] setting = new String[] {“false”, “verbose”};
Pluralize the names of collection references • Good examples: ArrayList borrowers = new ArrayList(); String[] settings = new String[] {“false”, “verbose”};
Pluralize the names of collection references • Java 1.5 feature for collections is generics. • These define collections at instantiation. Map<String, String> numbers = new HashMap<String, String>(); numbers.put(“0”, “zero); numbers.put(“1”, “one”); String valueAtZero = numbers.get(“0”);// no cast to String
All uppercase with underscores for constants • Elements of Java Style #31 • Capitalization distinguishes constants from other non-final variables.
All uppercase with underscores for constants • Bad examples: public final static String smtp = “smtp.edfund.org”; public final static int c_Success = “0”; public final static int c_Failure = “1”;
All uppercase with underscores for constants • Good examples: public final static String SMTP_SERVER = “smtp.edfund.org”; public final static int CVS_SUCCESS = “0”; Public final static int CVS_FAILURE = “1”;
Define small classes and small methods. • Elements of Java Style #69 • Easier to: • Design • Code • Test • Document • Read • Understand • Use
Define small classes and small methods. • General rule of thumbs: • 5-10 lines of code in a method • 10 or less methods • Involves a lot of refactoring to simpler concepts • OK, to violate this rule occasionally say for setting a lot of properties in a JavaBean.
public void substitute(String reqId, PrintWriter out) throws IOException { // Read in the template file String templateDir = System.getProperty(TEMPLATE_DIR, ""); StringBuffer sb = new StringBuffer(""); try { FileReader fr = new FileReader(templateDir + "template.html"); BufferedReader br = new BufferedReader(fr); String line; while(((line=br.readLine())!="")&&line!=null) sb = new StringBuffer(sb + line + "\n"); br.close(); fr.close(); } catch (Exception e) { } sourceTemplate = new String(sb); try { String template = new String(sourceTemplate); // Substitute for %CODE% int templateSplitBegin = template.indexOf("%CODE%"); int templateSplitEnd = templateSplitBegin + 6; String templatePartOne = new String(template.substring(0, templateSplitBegin)); String templatePartTwo = new String(template.substring(templateSplitEnd, template.length())); code = new String(reqId); template = new String(templatePartOne + code + templatePartTwo); // Substitute for %ALTCODE% templateSplitBegin = template.indexOf("%ALTCODE%"); templateSplitEnd = templateSplitBegin + 9; templatePartOne = new String(template.substring(0, templateSplitBegin)); templatePartTwo = new String(template.substring(templateSplitEnd, template.length())); altcode = code.substring(0,5) + "-" + code.substring(5,8); out.print(templatePartOne + altcode + templatePartTwo); } catch (Exception e) { System.out.println("Error in substitute()"); } out.flush(); out.close(); }
String readTemplate(Reader reader) throws IOException { BufferedReader br = new BufferedReader(reader); StringBuffer sb = new StringBuffer(); try { String line = br.readLine(); while (line!=null) { sb.append(line); sb.append("\n"); line = br.readLine(); } } finally { try {if (br != null) br.close();} catch (IOException ioe_ignored) {} } return sb.toString(); } void substituteCode ( String template, String pattern, String replacement, Writer out) throws IOException { int templateSplitBegin = template.indexOf(pattern); int templateSplitEnd = templateSplitBegin + pattern.length(); out.write(template.substring(0, templateSplitBegin)); out.write(replacement); out.write(template.substring(templateSplitEnd, template.length())); out.flush(); } public void substitute(String reqId, PrintWriter out) throws IOException { StringWriter templateOut = new StringWriter(); substituteCode(sourceTemplate, "%CODE%", reqId, templateOut); String altId = reqId.substring(0,5) + "-" + reqId.substring(5,8); substituteCode(templateOut.toString(), "%ALTCODE%", altId, out); out.close(); }
Place types that are used together in the same package. • Elements of Java Style #104 • Packaging is a way of organizing related classes • Classes are typically dependent on classes in the same package
Place types that are used together in the same package. • Bad examples: /org.edfund.facs Dialer.java PersonBean.java PersonForm.java PersonAction.java DateUtils.java /org.edfund.facs.business Dialer.java StartDialerAction.java DateUtils.java /org.edfund.facs.domain Person.java PersonForm.java /org.efund.facs.struts DialerDispatchAction.java Address.java
Place types that are used together in the same package. • Good examples: org.edfund.facs.business DialerManager.java CallService.java org.edfund.facs.domain Person.java Address.java org.edfund.facs.struts.actions StartDialerAction.java org.edfund.facs.struts.forms PersonForm.java LoginForm.java org.edfund.facs.persistence PersonDao.java PersonDaoFactory.java PersonDaoSqlMapImpl.java org.efund.facs.util DateUtils.java
Next Actions • Review The Elements of Java Style • Modify IDE to support conventions • Review your own code • Reviewing source code checking tools for addition to automated builds. (Clover, Checkstyle)
Goal: Readable source code Public void authenticateUser() { findAuthenticationMethod(); if (isNetworkConnection()) { authenticateHost(); } String password = getPasswordFromUser(); if (invalidPassword(password) { soundAlarm(); } }