java枚举中的布尔
重点 (Top highlight)
Booleans are the first data type any programmer learns. And why not? They’re the simplest of the lot with only two states: a true
and a false
.
布尔值是任何程序员学习的第一个数据类型。 那么为何不? 它们是仅有两个状态中最简单的一个: true
和false
。
While it’s tempting to use boolean flag values in your codebases for managing state machines, it can easily lead to code complexity, readability, and scalability issues as your code evolves.
尽管很想在代码库中使用布尔标志值来管理状态机,但随着代码的发展,它很容易导致代码复杂性,可读性和可伸缩性问题。
Generally, flag arguments divide a function’s logic, forcing it to do more than one thing based on the value. This can lead to tangled implementations in business logic. Your codebase could easily end up with the following tree structure:
通常,标志参数对函数的逻辑进行划分,从而迫使该函数基于该值执行多项操作。 这可能导致业务逻辑中的实现复杂。 您的代码库很容易以以下树结构结尾:
![Image for post](https://miro.medium.com/max/9999/1*bwiAiq6C8UOVgImOTt6YKQ.png)
背景故事 (Backstory)
Let me take you through a story to highlight the weaknesses of boolean arguments in state machines and function arguments.
让我带您一个故事,重点介绍状态机和函数参数中布尔参数的弱点。
A group of software developers was once building a module that manages the user’s state. One of them insisted on using booleans since the requirement had only two states: ONLINE
and OFFLINE
. Despite the majority not fully agreeing with the proposal, they went ahead since it looked quick, easy, and straightforward.
一组软件开发人员曾经构建了一个管理用户状态的模块。 其中之一坚持使用布尔值,因为要求只有两个状态: ONLINE
和OFFLINE
。 尽管大多数人并不完全同意该提案,但由于它看上去快速,简单,直接,他们还是继续进行。
Eventually, functions like the one below started creeping up in their codebase:
最终,下面的函数开始在其代码库中爬行:
func setUserState(isUserOnline : Bool)
Soon, a new developer joined the team and wondered what the following statement really means:
不久,一个新的开发人员加入了该团队,并想知道以下语句的真正含义: