在Android App中实现状态机

I’m sure you’ve all seen this type of code:

我确定你们都看过这种类型的代码:

This actually doesn’t look so bad, but as your branches grow, it will add cognitive load each time you read the lines. Also, what happens when you write this?

这实际上看起来还不错,但是随着分支的增长,每次您阅读台词时都会增加认知负荷。 另外,写这篇文章时会发生什么?

if (isLoading && errorMessage != null)

That doesn’t even make sense and is actually an invalid case, i.e. your app does not handle this, but it is writable and nothing can invalidate it.

这甚至没有任何意义,实际上是无效的案例,即您的应用程序无法处理此问题,但是它是可写的,没有什么可以使它无效。

One tool that can help you maintain this type of complexity is a state machine. There are many ways to implement a state machine in your code, starting with simple custom state machines to formal state machines that accept states and inputs.

状态机是可以帮助您维持这种复杂性的一种工具。 有多种方法可以在代码中实现状态机,从简单的自定义状态机到接受状态和输入的正式状态机。

什么是状态机? (What is a state machine?)

If you took a course about Automata in college, this should be familiar. It is a computational model that consists of states and transition functions. A transition function reads an input and determine the next state. A program cannot be in two states at any given time.

如果您在大学学习过有关Automata的课程,则应该很熟悉。 它是一个由状态和转换函数组成的计算模型。 转换功能读取输入并确定下一个状态。 程序在任何给定时间都不能处于两种状态。

Let’s start with an example: fetching data from an endpoint. The program can have 3 states: loading, success, and error. A state machine also has a starting state, which coincidentally here is named “not started” but you can name it anything you want. Here, the starting state indicates that the API is not called yet.

让我们从一个示例开始:从端

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值