0
Java anti-patterns:             Dark knight rises.Сергей Моренец28 февраля 2013 г.
Agenda• Design patterns• Anti-patterns overview• Q&A
Design patterns• Design Patterns: Elements of Reusable Object-Oriented  Software• Published on October 21, 1994• Authors a...
Hero of the day
Java Anti-docs/*** Rejects current task*/public void approve() { …}
Inline conversionint recordId = -1;try {    recordId = Integer.parseInt(columnRecordId);} catch (NumberFormatException e) ...
Exception handler            avoidanceValidationResultCollector vrc = collector.validate();if(vrc.hasError()) {   Validati...
Disuse of helper              librariesif (param.getFileName() != null &&param.getFileName().length() > 4) {try {    if (p...
Disuse of helper             librariesString name = FilenameUtils.getBaseName(parameter.getFileName());String extension = ...
Misuse of inheritance• public class SuperMap<K, V> extends  HashMap<K,V>{•   @Override•   public V get(Object key) {•   …•...
Upcastingpublic abstract class BaseClass {public void do() {  ((DerivedClass) this).validate();}}class DerivedClass extend...
Lack of synchronizationpublic class ScreenManager {private static ScreenManager instance;public static ScreenManager getIn...
State inconsistencypublic class AccountManager {private boolean inProgress = false;public void submit() {  if (inProgress)...
State inconsistencypublic class AccountManager {  private final Lock lock = new ReentrantLock();    public void submit() {...
State inconsistencypublic class AccountManager {private final Lock lock = new ReentrantLock();public void submit() {try { ...
Platform-dependent APIFile tmp = new File("C:Temp1.tmp");File exp = new File("export-2013-02-01T12:30.txt");File f = new F...
Platform-dependent APIFile tmp = File.createTempFile("myapp","tmp");File exp = new File("export-2013-02-01_1230.txt");File...
Infinitive heapbyte[] pdf = toPdf(file);
Infinitive heapFile pdf = new File(file);InputStream in = new FileInputStream(pdf);
Unbuffered streamsInputStream in = new FileInputStream(file);int b;while ((b = in.read()) != -1) {...}
Unbuffered streamsInputStream in = new BufferedInputStream(newFileInputStream(file))
Wrong propagationtry {  …} catch(ParseException e) {   LOGGER.error(e.getMessage());   throw new RuntimeException();   thr...
Wrong propagationtry {} catch(ParseException e) {throw new RuntimeException(e.getMessage(), e);}
Impossible exceptiontry {... do risky stuff ...} catch(SomeException e) {// never happens}
Impossible exceptiontry {... do risky stuff ...} catch(SomeException e) {// never happens hopefullythrow new IllegalStateE...
Unnecessary CalendarCalendar cal = newGregorianCalender(TimeZone.getTimeZone("Europe/Kyiv"));cal.setTime(date);cal.add(Cal...
Unnecessary Calendardate = new Date(date.getTime() + 8L * 3600L * 1000L);
Misleading calendarCalendar c = Calendar.getInstance();c.set(2009, Calendar.JANUARY, 15);c.getTime() - ?
Misleading calendarCalendar c = new GregorianCalendar(timeZone);c.set(2009, Calendar.JANUARY, 15);
Global constantspublic interface Constants {  String version = "1.0";  String dateFormat = "dd.MM.yyyy";  String configFil...
Static initializersclass Cache {private static final Timer timer = new Timer();}
Static initializersclass Cache {private static Timer timer;public static startTimer() {timer = new Timer();}}
Reflection overuseClass beanClass = ...if (beanClass.newInstance() instanceof TestBean) ...
Reflection overuseClass beanClass = ...if (TestBean.class.isAssignableFrom(beanClass)) ...
Map iterationMap<String, String> map = …;for (String key : map.keySet()) {   String value = map.get(key);   …}
Map iterationMap<String, String> map = …;for (Entry<String, String> entry : map.entrySet()) {  String key = entry.getKey()...
Time measurementlong startTime = System.currentTimeMillis();  ...long elapsedTime = System.currentTimeMillis() -startTime;
Time measurementlong startTime = System.nanoTime();...long elapsedTime = (System.nanoTime() - startTime) /1000000;
Q&A• Сергей Моренец, morenets@mail.ru
Collection<User> users = ...      if (users != null && !users.isEmpty()) {              int i = 0;              for (User ...
Anti patterns
Upcoming SlideShare
Loading in...5
×

Anti patterns

4,751

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
4,751
On Slideshare
0
From Embeds
0
Number of Embeds
11
Actions
Shares
0
Downloads
4
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "Anti patterns"

  1. 1. Java anti-patterns: Dark knight rises.Сергей Моренец28 февраля 2013 г.
  2. 2. Agenda• Design patterns• Anti-patterns overview• Q&A
  3. 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. 4. Hero of the day
  5. 5. Java Anti-docs/*** Rejects current task*/public void approve() { …}
  6. 6. Inline conversionint recordId = -1;try { recordId = Integer.parseInt(columnRecordId);} catch (NumberFormatException e) { recordId = 0;}
  7. 7. Exception handler avoidanceValidationResultCollector vrc = collector.validate();if(vrc.hasError()) { ValidationResult result = vrc.getError(); errorText = result.getErrorText();} else if(vrc.getErrorCode() == CPFErrorID.getNoCPFError()) {}
  8. 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. 9. Disuse of helper librariesString name = FilenameUtils.getBaseName(parameter.getFileName());String extension = FilenameUtils.getExtension(parameter.getFileName());
  10. 10. Misuse of inheritance• public class SuperMap<K, V> extends HashMap<K,V>{• @Override• public V get(Object key) {• …• }• }
  11. 11. Upcastingpublic abstract class BaseClass {public void do() { ((DerivedClass) this).validate();}}class DerivedClass extends BaseClass {public void validate() {}}
  12. 12. Lack of synchronizationpublic class ScreenManager {private static ScreenManager instance;public static ScreenManager getInstance() {if (instance == null) { instance = new ScreenManager();}return instance;}}
  13. 13. State inconsistencypublic class AccountManager {private boolean inProgress = false;public void submit() { if (inProgress) { return; } inProgress = true; … inProgress = false;}}
  14. 14. State inconsistencypublic class AccountManager { private final Lock lock = new ReentrantLock(); public void submit() { lock.lock(); … lock.unlock();}}
  15. 15. State inconsistencypublic class AccountManager {private final Lock lock = new ReentrantLock();public void submit() {try { lock.lock(); … } finally { lock.unlock();}}}
  16. 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. 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. 18. Infinitive heapbyte[] pdf = toPdf(file);
  19. 19. Infinitive heapFile pdf = new File(file);InputStream in = new FileInputStream(pdf);
  20. 20. Unbuffered streamsInputStream in = new FileInputStream(file);int b;while ((b = in.read()) != -1) {...}
  21. 21. Unbuffered streamsInputStream in = new BufferedInputStream(newFileInputStream(file))
  22. 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. 23. Wrong propagationtry {} catch(ParseException e) {throw new RuntimeException(e.getMessage(), e);}
  24. 24. Impossible exceptiontry {... do risky stuff ...} catch(SomeException e) {// never happens}
  25. 25. Impossible exceptiontry {... do risky stuff ...} catch(SomeException e) {// never happens hopefullythrow new IllegalStateException(e.getMessage(), e);}
  26. 26. Unnecessary CalendarCalendar cal = newGregorianCalender(TimeZone.getTimeZone("Europe/Kyiv"));cal.setTime(date);cal.add(Calendar.HOUR_OF_DAY, 8);date = cal.getTime();
  27. 27. Unnecessary Calendardate = new Date(date.getTime() + 8L * 3600L * 1000L);
  28. 28. Misleading calendarCalendar c = Calendar.getInstance();c.set(2009, Calendar.JANUARY, 15);c.getTime() - ?
  29. 29. Misleading calendarCalendar c = new GregorianCalendar(timeZone);c.set(2009, Calendar.JANUARY, 15);
  30. 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. 31. Static initializersclass Cache {private static final Timer timer = new Timer();}
  32. 32. Static initializersclass Cache {private static Timer timer;public static startTimer() {timer = new Timer();}}
  33. 33. Reflection overuseClass beanClass = ...if (beanClass.newInstance() instanceof TestBean) ...
  34. 34. Reflection overuseClass beanClass = ...if (TestBean.class.isAssignableFrom(beanClass)) ...
  35. 35. Map iterationMap<String, String> map = …;for (String key : map.keySet()) { String value = map.get(key); …}
  36. 36. Map iterationMap<String, String> map = …;for (Entry<String, String> entry : map.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); …}
  37. 37. Time measurementlong startTime = System.currentTimeMillis(); ...long elapsedTime = System.currentTimeMillis() -startTime;
  38. 38. Time measurementlong startTime = System.nanoTime();...long elapsedTime = (System.nanoTime() - startTime) /1000000;
  39. 39. Q&A• Сергей Моренец, morenets@mail.ru
  40. 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++; }}
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×