Top Banner
Java anti-patterns: Dark knight rises. Сергей Моренец 28 февраля 2013 г.
41

Anti patterns

Dec 27, 2014

Download

Documents

Alex Tumanoff

 
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Anti patterns

Java anti-patterns:Dark knight rises.

Сергей Моренец28 февраля 2013 г.

Page 2: Anti patterns

Agenda

• Design patterns• Anti-patterns overview• Q & A

Page 3: Anti patterns
Page 4: Anti patterns

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.

Page 5: Anti patterns

Hero of the day

Page 6: Anti patterns

Java Anti-docs/*** Rejects current task*/ public void approve() { …}

Page 7: Anti patterns

Inline conversionint recordId = -1;

try { recordId = Integer.parseInt(columnRecordId);} catch (NumberFormatException e) { recordId = 0;}

Page 8: Anti patterns

Exception handleravoidance

ValidationResultCollector vrc = collector.validate();

if(vrc.hasError()) { ValidationResult result = vrc.getError(); errorText = result.getErrorText();} else if(vrc.getErrorCode() == CPFErrorID.getNoCPFError()) {}

Page 9: Anti patterns

Disuse of helper libraries

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

Page 10: Anti patterns

Disuse of helper libraries

String name = FilenameUtils.getBaseName( parameter.getFileName());

String extension = FilenameUtils.getExtension( parameter.getFileName());

Page 11: Anti patterns

Misuse of inheritance• public class SuperMap<K, V> extends

HashMap<K,V>{

• @Override• public V get(Object key) {• …• }• }

Page 12: Anti patterns

Upcastingpublic abstract class BaseClass {

public void do() { ((DerivedClass) this).validate();}}

class DerivedClass extends BaseClass {public void validate() {}}

Page 13: Anti patterns

Lack of synchronization

public class ScreenManager {

private static ScreenManager instance;

public static ScreenManager getInstance() {if (instance == null) { instance = new ScreenManager();}return instance;}}

Page 14: Anti patterns

State inconsistencypublic class AccountManager {private boolean inProgress = false;

public void submit() { if (inProgress) { return; } inProgress = true; … inProgress = false;}}

Page 15: Anti patterns

State inconsistencypublic class AccountManager { private final Lock lock = new ReentrantLock();

public void submit() { lock.lock(); … lock.unlock();}}

Page 16: Anti patterns

State inconsistencypublic class AccountManager {private final Lock lock = new ReentrantLock();

public void submit() {try { lock.lock(); … } finally { lock.unlock();}}}

Page 17: Anti patterns

Platform-dependent API

File tmp = new File("C:\\Temp\\1.tmp");

File exp = new File("export-2013-02-01T12:30.txt");

File f = new File(path +'/'+ filename);

Page 18: Anti patterns

Platform-dependent API

File 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);

Page 19: Anti patterns

Infinitive heapbyte[] pdf = toPdf(file);

Page 20: Anti patterns

Infinitive heapFile pdf = new File(file);InputStream in = new FileInputStream(pdf);

Page 21: Anti patterns

Unbuffered streamsInputStream in = new FileInputStream(file);int b;while ((b = in.read()) != -1) {...}

Page 22: Anti patterns

Unbuffered streamsInputStream in = new BufferedInputStream(new FileInputStream(file))

Page 23: Anti patterns

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

Page 24: Anti patterns

Wrong propagationtry {} catch(ParseException e) {throw new RuntimeException(e.getMessage(), e);}

Page 25: Anti patterns

Impossible exceptiontry {... do risky stuff ...} catch(SomeException e) {// never happens}

Page 26: Anti patterns

Impossible exceptiontry {... do risky stuff ...} catch(SomeException e) {// never happens hopefullythrow new IllegalStateException(e.getMessage(), e); }

Page 27: Anti patterns

Unnecessary CalendarCalendar cal = new GregorianCalender(TimeZone.getTimeZone("Europe/Kyiv"));cal.setTime(date);cal.add(Calendar.HOUR_OF_DAY, 8);date = cal.getTime();

Page 28: Anti patterns

Unnecessary Calendardate = new Date(date.getTime() + 8L * 3600L * 1000L);

Page 29: Anti patterns

Misleading calendar Calendar c = Calendar.getInstance();c.set(2009, Calendar.JANUARY, 15);c.getTime() - ?

Page 30: Anti patterns

Misleading calendar Calendar c = new GregorianCalendar(timeZone);c.set(2009, Calendar.JANUARY, 15);

Page 31: Anti patterns

Global constantspublic interface Constants { String version = "1.0"; String dateFormat = "dd.MM.yyyy"; String configFile = ".apprc"; int maxNameLength = 32; String someQuery = "SELECT * FROM ...";}

Page 32: Anti patterns

Static initializersclass Cache {private static final Timer timer = new Timer();}

Page 33: Anti patterns

Static initializersclass Cache {private static Timer timer;

public static startTimer() {timer = new Timer();}}

Page 34: Anti patterns

Reflection overuse

Class beanClass = ... if (beanClass.newInstance() instanceof TestBean) ...

Page 35: Anti patterns

Reflection overuse

Class beanClass = ... if (TestBean.class.isAssignableFrom(beanClass)) ...

Page 36: Anti patterns

Map iterationMap<String, String> map = …;

for (String key : map.keySet()) { String value = map.get(key); …}

Page 37: Anti patterns

Map iterationMap<String, String> map = …;

for (Entry<String, String> entry : map.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); …}

Page 38: Anti patterns

Time measurementlong startTime = System.currentTimeMillis(); ...long elapsedTime = System.currentTimeMillis() - startTime;

Page 39: Anti patterns

Time measurementlong startTime = System.nanoTime();...long elapsedTime = (System.nanoTime() - startTime) / 1000000;

Page 40: Anti patterns

Q&A

• Сергей Моренец, [email protected]

Page 41: Anti patterns

Collection<User> users = ...if (users != null && !users.isEmpty()) {

int i = 0;for (User user : user) {

if (i > 0)break;

output.setUserId(user.getId());i++;

}}