Oct 26, 2019

[java] avoid these smells

For high performance/innovative projects, use Go/Rust.
For job
here are some bad smells of Java which should be avoid:

1.
https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.2/org/apache/commons/collections/CollectionUtils.html
CollectionUtils.isEmpty/isNotEmpty for checking container's emptiness and nullness

2.
This is simple idea in other languages.
For dynamic sized containers (C++'s vector), pre-assign size before using it
to prevent copy-and-extend

3.
Use StringBuilder since everything in Java is allocated on heap..

4.
Like C++ but more uglier(Java has this check at runtime, not compile time), Java has the concept of type of iterator.
If the passing in List<> is RandomAccess implemented, it can be traverse
with random location(e.g ArrayList/Stack/Vector,  C++'s Array/Vector)
https://docs.oracle.com/javase/8/docs/api/java/util/RandomAccess.html

if (list instanceof RandomAccess) ...

5.
Don't use fancy but awful performance anonymous type trick:
List<String> l = new ArrayList<>{
    add(1);
    add(3);
    };

6.
Use try-with-resource
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

Type implements:
1. java.io.Closeable
2. java.lang.AutoCloseable
Should use try-with-resource.

try-with resource will not suppress try block's exception which only throws
'finally's exception, this is unlike the use of try/finally

For retrieving suppress exception use:
Throwable.getSuppressed

7.
Java is full of sxxx, no, full of patterns
For Util class(do not use 'util' in Go, it doesn't make sense at all)
hide its constructor.

8.
Use:
Object.isNull everywhere

9.
Use:
String.valueOf

10.
Use:
@Deprecated

11.
Do not compare with different type with <>= operator
It's common concept in strong type languages.

12.
Return empty container instead of null.
Null itself is not part of the type of the container.
Use:
Collections.emptyXXX

13.
Again, beware function argument's nullness.
John Lakos' defensive programming is a good thing for Java engineers.
https://vsdmars.blogspot.com/2015/01/defensive-programming.html

14.
String.split() takes regex, beware to escape if necessary
~RTFM~

15.
Favor unchecked RuntimeException.
Checked exception is by design a flaw which Anders Hejlsberg has mentioned this almost 20 years ago:
https://www.artima.com/intv/handcuffs.html
C++ has dumped runtime exception and favor compile time check noexcept
some reference here:
https://stackoverflow.com/a/2190177
https://phauer.com/2015/checked-exceptions-are-evil/

16.
Unit test rule
A:Automatic(自动化)
I:Independent(独立性)
R:Repeatable(可重复)

17.
Unit test principle
B:Border,边界值测试,包括循环边界、特殊取值、特殊时间点、数据顺序等。
C:Correct,正确的输入,并得到预期的结果。
D:Design,与设计文档相结合,来编写单元测试。
E:Error,强制错误信息输入(如:非法数据、异常流程、业务允许外等),并得到预期的结果。

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.