Write Simple and No-surprise Code

And improve your productivity in the long run

Liu Tao
Liu Tao
Jul 3, 2019 · 5 min read
Image for post
Image for post
Photo by Khai Sze Ong on Unsplash

Why should we write simple code

First thing first, try your best to avoid code

If possible, use annotation

Use control only when unavoidable

if (a != null && 
a.getItem() != null &&
a.getItem().getValue() != null) {
return process(a.getItem().getValue());
} else {
return false;
}
Optional.ofNullable(a)
.map(A::getItem)
.map(Item:getValue)
.map(this::process)
.orElse(false);
list.streams().forEach(p -> {
if (p.isValid()) {
process(p);
}
})
list.streams()
.filter(P::isValid)
.forEach(this::process)

Extract more data from your code

let caseInSensitive = (val1, val2) => {
val1 = _.capitalize(val1 || “”);
val2 = _.capitalize(val2 || “”);
return val1 === val2;
}
let normal = (val1, val2) => {
return val1 === val2;
}
let properties = [{
“path”: “addressLine1”,
“comparator”: caseInSensitive
},{
“path”: “streetNumber”,
“comparator”: normal
}
]
let addressComprator = (addr1, addr2) => {
return _.every(properties, prop => {
let val1 = _.get(addr1, prop.path);
let val2 = _.get(addr2, prop.path),
return prop.comparator(val1, val2);
});
}

Separate business logic from error handling

if (dto != null) {
result1 = processA(dto);
}

if (result1 != null) {
result2 = processB(result1);
}

if (result2 != null) {
result3 = processC(result2);
}

return result3 != null;
Optional.ofNullable(dto)
.map(this::processA)
.map(this::processB)
.map(this::processC)
.map(r -> r != null)
.orElse(false)

Summary

The Startup

Medium's largest active publication, followed by +730K people. Follow to join our community.

Liu Tao

Written by

Liu Tao

Microservices developer in payment industry, https://www.linkedin.com/in/tao-liu-241b559/

The Startup

Medium's largest active publication, followed by +730K people. Follow to join our community.

Liu Tao

Written by

Liu Tao

Microservices developer in payment industry, https://www.linkedin.com/in/tao-liu-241b559/

The Startup

Medium's largest active publication, followed by +730K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store