Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Why can't Java developers allow magic values to appear in the code?

Shulou Source: shulou.com Published: 2022-06-01 05:14:28 10月03日 Update

This article introduces the knowledge of "Why Java development does not allow magic values to appear in the code". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Static constants replace magic values

An example like this:

If (billCount > 75) {/ / todo} else {/ / todo}

If colleagues who do not understand the business of this piece of business, when reading this code, they may wonder, what the hell is 75 and why it is compared with this number, is there any secret behind it? Perhaps only the developers at that time remembered, resulting in poor readability and maintainability of the code.

If you declare a constant to replace the magic value, it may greatly increase the readability and maintainability of the code.

Static final Integer BASIC_BILL_COUNT = 75

There are also some magic expressions, such as:

If (value > 60 & & value 60 & & value

Tags: Magic code events readability beans development examples content maintainability constants more knowledge expressions different practical annoying successful learning and then unhappy people Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker MySQL Shulou Technology Linux Redmi