Home > Enterprise >  Best practice for repeated null checks
Best practice for repeated null checks

Time:09-28

My app has a public area, and an area where users must be authenticated, for example a page with a chat. At the lowest level I have my authenticationService, where I can check if a user is authenticated by checking for null in:

authenticationService.currentUser

When I updated this functionality for null safety, I declared this variable as:

User? _currentUser;

However, within the chat-components I also often have to access the user, and since I know a user must already be authenticated to access this area I use "!" like this a lot:

authenticationService.currentUser!

Additionally I use assert on some entry-points to catch errors at least during development:

assert(authenticationService.currentUser != null);

Is there a better way than to use "!" a lot in these areas and basically disable the null safety here and hope for the best?

CodePudding user response:

I'd avoid direct access to the _currentUser variable, and instead go through two different getters:

User get currentUser => 
    _currentUser ?? (throw StateError("Not authenticated"));

bool get isAuthenticated => _currentUser != null;

That keeps the state logic local to a few methods, and it's now your own job to ensure you only read currentUser when you know it's authenticated. Which is no different from now, you just get a more readable error if you make a mistake than you get by !.

(Since your variable is called _currentUser and your code is doing .currentUser, you probably already have a getter wrapping the variable).

  • Related