1 / 36

Top 10 Java Style Conventions

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.

mariel
Download Presentation

Top 10 Java Style Conventions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Top 10 Java Style Conventions Ed Gibbs

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

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

  4. Indent nested code • Bad examples: public void getName() { return this.name } try { EmployeeManagerDao dao = EmployeeFactory.getInstance(); } catch (DataException e) { e.printStackTrace(); }

  5. Indent nested code • Good examples: public void getName() { return this.name } try { EmployeeManagerDao dao = EmployeeFactory.getInstance(); } catch (DataException e){ e.printStackTrace(); }

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

  7. 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; }

  8. 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; }

  9. Join the vowel generation • Elements of Java Style #12 • Abbreviations reduce readiblity.

  10. Join the vowel generation • Bad examples: private FBean exec(String ref) { // do something } public void procLn (String ln) { // do something }

  11. Join the vowel generation • Good examples: private LoanPackageFormBean executeUpdate(String loanReferenceNumber) { // do something } public String processLineFormatting (String line) { // do something }

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

  13. Capitalize only the first letter in acronyms • Bad examples: setWALTSSeparator(); createPersonDAO(); loadXMLReprentation();

  14. Capitalize only the first letter in acronyms • Good examples: setWaltsSeparator(); createPersonDao(); loadXmlReprentation();

  15. Use nouns when naming classes • Elements of Java Style #19 • Classes define things. • Classes should be easily identifiable from their names.

  16. Use nouns when naming classes • Bad examples: Wfn00; BirdClass; Proc;

  17. Use nouns when naming classes • Good examples: Wfn00;  Loan; BirdClass;  Bird; Proc;  ProcessController;

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

  19. Use lowercase for the first word and capitalize only the first letter after • Bad examples: GetAmount(); EXEC(); Start();

  20. Use lowercase for the first word and capitalize only the first letter after • Good examples: GetAmount();  getAmount(); EXEC();  execute(); Start();  start();

  21. Pluralize the names of collection references • Elements of Java Style #27 • Allows the reader to differentiate between single value and multiple value variables.

  22. Pluralize the names of collection references • Bad examples: ArrayList borrower = new ArrayList(); String[] setting = new String[] {“false”, “verbose”};

  23. Pluralize the names of collection references • Good examples: ArrayList borrowers = new ArrayList(); String[] settings = new String[] {“false”, “verbose”};

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

  25. All uppercase with underscores for constants • Elements of Java Style #31 • Capitalization distinguishes constants from other non-final variables.

  26. 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”;

  27. 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”;

  28. Define small classes and small methods. • Elements of Java Style #69 • Easier to: • Design • Code • Test • Document • Read • Understand • Use

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

  30. 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(); }

  31. 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(); }

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

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

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

  35. 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)

  36. Goal: Readable source code Public void authenticateUser() { findAuthenticationMethod(); if (isNetworkConnection()) { authenticateHost(); } String password = getPasswordFromUser(); if (invalidPassword(password) { soundAlarm(); } }

More Related