Skip to content

[Suggest a feature] Logical AND (&&) to execute code if it meets the condition #2867

Closed as not planned
@titoworlddev

Description

@titoworlddev

I know that this operator (&&) already exists in dart but I would like it to have a use other than the ones it has.

It is common that sometimes we want to simply execute a small code only when a condition is met, for example:

String dart = 'awesome';
if (dart == 'awesome') {
  print('Dart is $dart');
}

Which is a bit long, but no problem, it can be shortened by putting it like this:

if (dart == 'awesome') print('Dart is $dart');

But when the condition gets a bit longer, the linter forces you to use the brackets because if you use clean code the execution after the condition would go on the line below. Which as I said, the linter forces you to put brackets.
For example:

String dart = 'awesome';
String dartVersion = '3.0.0';
String flutter = 'beautiful';
if (dart == 'awesome' && flutter == 'beautiful' && dartVersion == '3.0.0') {
  print('Dart $dartVersion and Flutter are very nice!');
}

This, if you want your code to not have unnecessary lines, can lead you to use ternaries and have codes like this:

dart == 'awesome' && flutter == 'beautiful' && dartVersion == '3.0.0'
      ? print('Dart $dartVersion and Flutter are very nice!')  : 0;

But of course, this can still be ugly because if we only need one execution, why put : 0;.

All this leads me to the use of the && operator as a solution to these cases. This could lead us to cleaner codes. For example, I am going to reduce the first code I put, and at the end I will use the && operator so that all the differences can be seen together.
Here the example:

String dart = 'awesome';
// Long way
if (dart == 'awesome') {
  print('Dart is $dart');
}

// Long way in 1 line
if (dart == 'awesome') print('Dart is $dart');

// reduced with ternary
dart == 'awesome' ? print('Dart is $dart') : 0;

// Clean code using the && operator
dart == 'awesome' && print('Dart is $dart');

I think this is much cleaner and easier to use for the cases that I have said. It would be nice to add it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions