Member-only story

A new approach to avoiding a large amount of if-else code

Beck Moulton
6 min readMay 14, 2024

--

Today, I’m going to bring you a super invincible new coding trick. As long as you read it, I guarantee that your code will be as smooth as using a certain shampoo, not only removing dandruff but also smoother.

We’re going to talk about those love-hate technical points: custom exceptions, global exception catching, assertions .

0x1

Control exception flow

First, let’s talk about custom exceptions.

You know, in Java world, we usually use if-else statements to check for conditions that give us a headache.

For example, user login:

// 伪代码
if (验证码 != 8888) {
return "验证码错误";
}
// 处理其他业务逻辑
return "登录成功";

However, have you ever thought about what would happen if we used exceptions to control the process instead of if-else?

For example, in your login method, if the verification code is incorrect, instead of returning an error message, an exception will be thrown with a “bang” sound.

// 伪代码
if (验证码 != 8888) {
throw new ServiceException("验证码错误");
}
// 处理其他业务逻辑
return "登录成功";

Does it sound a bit crazy? But that’s the charm of custom exceptions, which can make your code look like it’s in a movie, with each exception being a plot twist.

Here encapsulates a business class exception class ServiceException, which inherits the runtime exception…

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

Responses (1)