Anti patterns

  • 4,681 views
Uploaded on

 

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
4,681
On Slideshare
0
From Embeds
0
Number of Embeds
11

Actions

Shares
Downloads
4
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Java anti-patterns: Dark knight rises.Сергей Моренец28 февраля 2013 г.
  • 2. Agenda• Design patterns• Anti-patterns overview• Q&A
  • 3. Design patterns• Design Patterns: Elements of Reusable Object-Oriented Software• Published on October 21, 1994• Authors are Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, referred as Gang of Four• Creational, structural and behavioral patterns.
  • 4. Hero of the day
  • 5. Java Anti-docs/*** Rejects current task*/public void approve() { …}
  • 6. Inline conversionint recordId = -1;try { recordId = Integer.parseInt(columnRecordId);} catch (NumberFormatException e) { recordId = 0;}
  • 7. Exception handler avoidanceValidationResultCollector vrc = collector.validate();if(vrc.hasError()) { ValidationResult result = vrc.getError(); errorText = result.getErrorText();} else if(vrc.getErrorCode() == CPFErrorID.getNoCPFError()) {}
  • 8. Disuse of helper librariesif (param.getFileName() != null &&param.getFileName().length() > 4) {try { if (param.getFileName().contains(".")) { name = param.getFileName().substring(0,param.getFileName().lastIndexOf(".")); } else name = attach.getFileName();} catch (Exception e) { e.printStackTrace();String errorMessage = e.getMessage(); } }
  • 9. Disuse of helper librariesString name = FilenameUtils.getBaseName(parameter.getFileName());String extension = FilenameUtils.getExtension(parameter.getFileName());
  • 10. Misuse of inheritance• public class SuperMap<K, V> extends HashMap<K,V>{• @Override• public V get(Object key) {• …• }• }
  • 11. Upcastingpublic abstract class BaseClass {public void do() { ((DerivedClass) this).validate();}}class DerivedClass extends BaseClass {public void validate() {}}
  • 12. Lack of synchronizationpublic class ScreenManager {private static ScreenManager instance;public static ScreenManager getInstance() {if (instance == null) { instance = new ScreenManager();}return instance;}}
  • 13. State inconsistencypublic class AccountManager {private boolean inProgress = false;public void submit() { if (inProgress) { return; } inProgress = true; … inProgress = false;}}
  • 14. State inconsistencypublic class AccountManager { private final Lock lock = new ReentrantLock(); public void submit() { lock.lock(); … lock.unlock();}}
  • 15. State inconsistencypublic class AccountManager {private final Lock lock = new ReentrantLock();public void submit() {try { lock.lock(); … } finally { lock.unlock();}}}
  • 16. Platform-dependent APIFile tmp = new File("C:Temp1.tmp");File exp = new File("export-2013-02-01T12:30.txt");File f = new File(path +/+ filename);
  • 17. Platform-dependent APIFile tmp = File.createTempFile("myapp","tmp");File exp = new File("export-2013-02-01_1230.txt");File f = new File(path +File. pathSeparator+ filename);File dir = new File(path);File f = new File(dir, filename);
  • 18. Infinitive heapbyte[] pdf = toPdf(file);
  • 19. Infinitive heapFile pdf = new File(file);InputStream in = new FileInputStream(pdf);
  • 20. Unbuffered streamsInputStream in = new FileInputStream(file);int b;while ((b = in.read()) != -1) {...}
  • 21. Unbuffered streamsInputStream in = new BufferedInputStream(newFileInputStream(file))
  • 22. Wrong propagationtry { …} catch(ParseException e) { LOGGER.error(e.getMessage()); throw new RuntimeException(); throw new RuntimeException(e.toString()); throw new RuntimeException(e.getMessage()); throw new RuntimeException(e);}
  • 23. Wrong propagationtry {} catch(ParseException e) {throw new RuntimeException(e.getMessage(), e);}
  • 24. Impossible exceptiontry {... do risky stuff ...} catch(SomeException e) {// never happens}
  • 25. Impossible exceptiontry {... do risky stuff ...} catch(SomeException e) {// never happens hopefullythrow new IllegalStateException(e.getMessage(), e);}
  • 26. Unnecessary CalendarCalendar cal = newGregorianCalender(TimeZone.getTimeZone("Europe/Kyiv"));cal.setTime(date);cal.add(Calendar.HOUR_OF_DAY, 8);date = cal.getTime();
  • 27. Unnecessary Calendardate = new Date(date.getTime() + 8L * 3600L * 1000L);
  • 28. Misleading calendarCalendar c = Calendar.getInstance();c.set(2009, Calendar.JANUARY, 15);c.getTime() - ?
  • 29. Misleading calendarCalendar c = new GregorianCalendar(timeZone);c.set(2009, Calendar.JANUARY, 15);
  • 30. Global constantspublic interface Constants { String version = "1.0"; String dateFormat = "dd.MM.yyyy"; String configFile = ".apprc"; int maxNameLength = 32; String someQuery = "SELECT * FROM ...";}
  • 31. Static initializersclass Cache {private static final Timer timer = new Timer();}
  • 32. Static initializersclass Cache {private static Timer timer;public static startTimer() {timer = new Timer();}}
  • 33. Reflection overuseClass beanClass = ...if (beanClass.newInstance() instanceof TestBean) ...
  • 34. Reflection overuseClass beanClass = ...if (TestBean.class.isAssignableFrom(beanClass)) ...
  • 35. Map iterationMap<String, String> map = …;for (String key : map.keySet()) { String value = map.get(key); …}
  • 36. Map iterationMap<String, String> map = …;for (Entry<String, String> entry : map.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); …}
  • 37. Time measurementlong startTime = System.currentTimeMillis(); ...long elapsedTime = System.currentTimeMillis() -startTime;
  • 38. Time measurementlong startTime = System.nanoTime();...long elapsedTime = (System.nanoTime() - startTime) /1000000;
  • 39. Q&A• Сергей Моренец, morenets@mail.ru
  • 40. Collection<User> users = ... if (users != null && !users.isEmpty()) { int i = 0; for (User user : user) { if (i > 0) break; output.setUserId(user.getId()); i++; }}