cleancode.in

Clean code in Dart

Effective Dart: types in UpperCamelCase, every other name in lowerCamelCase, constants included, files in lowercase_with_underscores, lines of 80 characters or fewer, braces on every if and loop, and dart format for the layout.

What does Effective Dart ask for?

  • DO name packages, directories, and source files using lowercase_with_underscores source

From Effective Dart: Style.

How should Dart code look?

  • dart format does the layout. source
  • Lines of 80 characters or fewer. source

What else does it ask?

  • No prefix letters. source
  • Braces on every if, for and while. source

How are names written in Dart?

KindExampleRule
TypesShoppingCartTypes in UpperCamelCase. source
FunctionsaddItemOther names in lowerCamelCase. source
VariablesitemCountOther names in lowerCamelCase. source
ConstantsmaxItemsConstants in lowerCamelCase too. source

What does cleaner Dart look like?

Before
// CartScreen.dart
const MAX_ITEMS = 20;

class cart_screen {
  List<CartItem> l = [];

  void add(CartItem i) {
    if (l.length >= MAX_ITEMS) throw StateError('full');
    l.add(i);
  }
}
After
// cart_screen.dart
const maxItems = 20;

class CartScreen {
  final List<CartItem> items = [];

  void addItem(CartItem item) {
    if (items.length >= maxItems) {
      throw StateError('The cart holds $maxItems items at most.');
    }
    items.add(item);
  }
}

What changed?

  • The file in lowercase_with_underscores, the class in UpperCamelCase. source
  • The constant in lowerCamelCase, as Dart asks, not in capitals. source
  • Braces around the if’s body. source
  • The error says what went wrong, and the names say what they hold.