4. 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.
9. 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();
}
}
10. Disuse of helper
libraries
String name = FilenameUtils.getBaseName(
parameter.getFileName());
String extension = FilenameUtils.getExtension(
parameter.getFileName());
11. Misuse of inheritance
• public class SuperMap<K, V> extends
HashMap<K,V>{
• @Override
• public V get(Object key) {
• …
• }
• }
12. Upcasting
public abstract class BaseClass {
public void do() {
((DerivedClass) this).validate();
}
}
class DerivedClass extends BaseClass {
public void validate() {
}
}
13. Lack of synchronization
public class ScreenManager {
private static ScreenManager instance;
public static ScreenManager getInstance() {
if (instance == null) {
instance = new ScreenManager();
}
return instance;
}
}
14. State inconsistency
public class AccountManager {
private boolean inProgress = false;
public void submit() {
if (inProgress) {
return;
}
inProgress = true;
…
inProgress = false;
}
}
15. State inconsistency
public class AccountManager {
private final Lock lock = new ReentrantLock();
public void submit() {
lock.lock();
…
lock.unlock();
}
}
16. State inconsistency
public class AccountManager {
private final Lock lock = new ReentrantLock();
public void submit() {
try {
lock.lock();
…
} finally {
lock.unlock();
}
}
}
17. Platform-dependent API
File tmp = new File("C:Temp1.tmp");
File exp = new File("export-2013-02-01T12:30.txt");
File f = new File(path +'/'+ filename);
18. 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);
26. Impossible exception
try {
... do risky stuff ...
} catch(SomeException e) {
// never happens hopefully
throw new IllegalStateException(e.getMessage(), e);
}
27. Unnecessary Calendar
Calendar cal = new
GregorianCalender(TimeZone.getTimeZone("Europe/Kyiv"));
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, 8);
date = cal.getTime();
41. Collection<User> users = ...
if (users != null && !users.isEmpty()) {
int i = 0;
for (User user : user) {
if (i > 0)
break;
output.setUserId(user.getId());
i++;
}}