重复空检查的最佳实践
Best practice for repeated null checks
我的应用程序有一个 public 区域,以及一个必须对用户进行身份验证的区域,例如带有聊天的页面。在最低级别,我有我的 authenticationService,我可以在其中通过检查 null 来检查用户是否已通过身份验证:
authenticationService.currentUser
当我为空安全更新此功能时,我将此变量声明为:
User? _currentUser;
然而,在聊天组件中,我也经常需要访问用户,因为我知道用户必须已经通过身份验证才能访问这个区域,所以我使用“!”很喜欢这样:
authenticationService.currentUser!
此外,我至少在开发过程中对某些入口点使用断言来捕获错误:
assert(authenticationService.currentUser != null);
有没有比使用“!”更好的方法呢?很多在这些领域,基本上在这里禁用空安全并希望最好?
我会避免直接访问 _currentUser
变量,而是通过两个不同的 getters:
User get currentUser =>
_currentUser ?? (throw StateError("Not authenticated"));
bool get isAuthenticated => _currentUser != null;
这使状态逻辑保持在几个方法的本地,现在您自己的工作是确保您只在知道它已通过身份验证时才阅读 currentUser
。这与现在没有什么不同,如果你犯了一个错误,你会得到一个比 !
.
更易读的错误
(因为你的变量被称为 _currentUser
并且你的代码正在做 .currentUser
,你可能已经有一个 getter 包装变量)。
我的应用程序有一个 public 区域,以及一个必须对用户进行身份验证的区域,例如带有聊天的页面。在最低级别,我有我的 authenticationService,我可以在其中通过检查 null 来检查用户是否已通过身份验证:
authenticationService.currentUser
当我为空安全更新此功能时,我将此变量声明为:
User? _currentUser;
然而,在聊天组件中,我也经常需要访问用户,因为我知道用户必须已经通过身份验证才能访问这个区域,所以我使用“!”很喜欢这样:
authenticationService.currentUser!
此外,我至少在开发过程中对某些入口点使用断言来捕获错误:
assert(authenticationService.currentUser != null);
有没有比使用“!”更好的方法呢?很多在这些领域,基本上在这里禁用空安全并希望最好?
我会避免直接访问 _currentUser
变量,而是通过两个不同的 getters:
User get currentUser =>
_currentUser ?? (throw StateError("Not authenticated"));
bool get isAuthenticated => _currentUser != null;
这使状态逻辑保持在几个方法的本地,现在您自己的工作是确保您只在知道它已通过身份验证时才阅读 currentUser
。这与现在没有什么不同,如果你犯了一个错误,你会得到一个比 !
.
(因为你的变量被称为 _currentUser
并且你的代码正在做 .currentUser
,你可能已经有一个 getter 包装变量)。