flutterif-statementcoding-styleblocflutter-bloc

Which of these is the best structure of a if-statement in a BlocListener for a SignIn?


I'm designing an application that uses Flutter Bloc and i'm not sure which of the two approaches is better in terms of structure. One is shorter in terms of lines of code, while the other is more intuitive when writing quickly. Which one would be more correct for understanding the code?

Less code:

setState(() {
    if (state is SignInProcess) {
      signInRequired = true;
      return;
    } else {
      signInRequired = false;
      if (state is SignInFailure) {
        _errorMsg = "Invalid email or password";
      }
    }
});

More intuitive while writing:

if (state is SignInSuccess) {
  setState(() {
    signInRequired = false;
  });
} else if (state is SignInProcess) {
  setState(() {
    signInRequired = true;
  });
} else if (state is SignInFailure) {
  setState(() {
    signInRequired = false;
  _errorMsg = 'Invalid email or password';
  });
}

I don't expect the simplest code to be any of the options I provided. I'm open to other suggestions.


Solution

  • According to readability, both are readable.

    I think what you are trying to achieve is a conformation to KISS principle (Keep it Simple, Stupid).

    That principle states that your code should be as simple as possible which increase the readability and later maintenance.

    Both options in your question conform to KISS principle.

    If you seek a shorthand code (as suggested by @Md. Yeasin Sheikh):

    setState(
    (){
     signInRequired = state is SignInProcess 
     }
    );
    

    and guess what, it also conform to KISS principle, moreover it seems easy to be understandable.