2022/5/30/Dart/Effective Dart/Styleの訳

 

A surprisingly important part of good code is good style.

良いコードのために意外と重要なのが、良いスタイルです。

 

Consistent naming, ordering, and formatting helps code that isthe same look the same.

名前、順序、書式を統一することで、同じコードが同じように見えるようになります。

 

It takes advantage of the powerful pattern-matching hardware most of us have in our ocular systems.

これは、私たちの眼球システムに備わっている強力なパターンマッチングのハードウェアを利用したものです。

 

If we use a consistent style across the entire Dart ecosystem, it makes it easier for all of us to learn from and contribute to each others’ code.

Dartエコシステム全体で一貫したスタイルを使用すると、私たち全員がお互いのコードから学び、貢献することが容易になります。


Contents

Identifiers(識別子、命名規則)

Identifiers come in three flavors in Dart.

Dartには、3種類の識別子があります。

 

  • UpperCamelCase names capitalize the first letter of each word, including the first.

アッパーキャメルケース : 一番最初の文字も含め、各々の言葉の最初の文字を大文字にします。

 

  • lowerCamelCase names capitalize the first letter of each word, except the first which is always lowercase, even if it’s an acronym.

ローワーキャメルケース : 頭文字であっても一番最初の文字は常に小文字です。それ以外の各々の言葉の最初の文字を大文字にします。

 

  • lowercase_with_underscores names use only lowercase letters, even for acronyms, and separate words with _.

ローワーケースwithアンダースコア : すべての文字を小文字で書き、単語同士をアンダースコアでつなぎます。


DO name types using UpperCamelCase.

型名(クラス名など)はUpperCamelCaseで命名する。

Classes, enum types, typedefs, and type parameters should capitalize the first letter of each word (including the first word), and use no separators.

クラス、列挙型、typedef、そして型引数はUpperCamelCaseで記述します。

good

class SliderMenu { ... }

class HttpRequest { ... }

typedef Predicate<T> = bool Function(T value);

 


This even includes classes intended to be used in metadata annotations.

これには、メタデータアノテーションで使用することを目的としたクラスも含まれる。

good

class Foo {
  const Foo([Object? arg]);
}

@Foo(anArg)
class A { ... }

@Foo()
class B { ... }

 


If the annotation class’s constructor takes no parameters, you might want to create a separate lowerCamelCaseconstant for it.

アノテーションクラスのコンストラクターがパラメーターを受け取らない場合は、別のlowerCamelCase定数を作成することをお勧めします。

good

const foo = Foo();

@foo
class C { ... }

 


DO name extensions using UpperCamelCase.

extensionもUpperCamelCaseで命名する。

Like types, extensions should capitalize the first letter of each word (including the first word), and use no separators.

型名と同様、extensionもUpperCamelCaseで命名します。

good

extension MyFancyList<T> on List<T> { ... }

extension SmartIterable<T> on Iterable<T> { ... }

 


DO name libraries, packages, directories, and source files using lowercase_with_underscores.

ライブラリ、パッケージ、ディレクトリ、ソースファイル名はlowercase_with_underscoresで命名する。

 

Some file systems are not case-sensitive, so many projects require filenames to be all lowercase. Using a separating character allows names to still be readable in that form.

ファイルシステムによっては大文字と小文字が区別されないため、多くのプロジェクトではファイル名をすべて小文字にする必要があります。区切り文字を使用することで、そのような形式でも名前を読みやすくなります。

good↓

library peg_parser.source_scanner;

import 'file_system.dart';
import 'slider_menu.dart';

 

bad↓

library pegparser.SourceScanner;

import 'file-system.dart';
import 'SliderMenu.dart';

 

Note: This guideline specifies how to name a library if you choose to name it. It is fine to omit the library directive in a file if you want.

注: このガイドラインではライブラリを命名する場合の説明をしています。ライブラリ名の命名は省略しても構いません。


DO name import prefixes using lowercase_with_underscores.

import prefixesはlowercase_with_underscoresで命名します。

good↓

import 'dart:math' as math;
import 'package:angular_components/angular_components.dart' as angular_components;
import 'package:js/js.dart' as js;

 

bad↓

import 'dart:math' as Math;
import 'package:angular_components/angular_components.dart' as angularComponents;
import 'package:js/js.dart' as JS;

 


DO name other identifiers using lowerCamelCase.

上記以外の識別子はlowerCamelCaseで命名します。

Class members, top-level definitions, variables, parameters, and named parameters should capitalize the first letter of each word except the first word, and use no separators.

クラスメンバー、トップレベルでの宣言、変数、パラメータ、名前付きパラメータは、最初の単語を除く各単語の最初の文字を大文字にし、セパレータを使用しないでください。

var count = 3;

HttpRequest httpRequest;

void align(bool clearItems) {
  // ...
}

 


PREFER using lowerCamelCase for constant names.

In new code, use lowerCamelCase for constant variables, including enum values.

const定数や列挙型の値はlowerCamelCaseで命名しましょう。

good↓

const pi = 3.14;
const defaultTimeout = 1000;
final urlScheme = RegExp('^([a-z]+):');

class Dice {
  static final numberGenerator = Random();
}

 

bad↓

const PI = 3.14;
const DefaultTimeout = 1000;
final URL_SCHEME = RegExp('^([a-z]+):');

class Dice {
  static final NUMBER_GENERATOR = Random();
}

 


You may use SCREAMING_CAPS for consistency with existing code, as in the following cases:

SCREAMING_CAPSは、以下のように既存のコードとの整合性を保つために使用することができます。

 

  • When adding code to a file or library that already uses SCREAMING_CAPS.

すでにSCREAMING_CAPSが使われているファイルやライブラリにコードを追加する場合。

 

  • When generating Dart code that’s parallel to Java code—for example, in enumerated types generated from protobufs.

Javaコードと並列するDartコードを生成する場合、例えばprotobufsから生成される列挙型において。

 

Note: We initially used Java’s SCREAMING_CAPS style for constants. We changed for a few reasons:

注 : 当初私たちはJavaのSCREAMING_CAPSスタイルを定数に使用していましたが、いくつかの理由で変更しました。

 

  • SCREAMING_CAPS looks bad for many cases, particularly enum values for things like CSS colors.

SCREAMING_CAPSは多くの場合、特にCSSカラーのようなもののためのenum値には悪い印象を与えるから。

 

  • Constants are often changed to final non-const variables, which would necessitate a name change.

const定数は、しばしば(constではない)final定数に変更する必要(場合)が出てきます。そういう場合に定数名を変更しないといけないから。

 

  • The values property automatically defined on an enum type is const and lowercase.

自動的に定義されるenum(列挙型)のvaluesフィールドはconstであり、lowercaseであるから。


DO capitalize acronyms and abbreviations longer than two letters like words.

 

Capitalized acronyms can be hard to read, and multiple adjacent acronyms can lead to ambiguous names. For example, given a name that starts with HTTPSFTP, there’s no way to tell if it’s referring to HTTPS FTP or HTTP SFTP.

大文字にした頭字語は読みにくく、また、複数の頭字語が隣接していると、曖昧な名前になる可能性があります。例えば、HTTPSFTPで始まる名前があった場合、それがHTTPS FTPを指しているのか、HTTP SFTPを指しているのかを見分ける方法はありません。

 

To avoid this, acronyms and abbreviations are capitalized like regular words.

これを避けるため、頭字語や略語は通常の単語と同様に大文字で表記しています。

 

Exception: Two-letter acronyms like IO (input/output) are fully capitalized: IO. On the other hand, two-letter abbreviationslike ID (identification) are still capitalized like regular words: Id.

例外 : IO (input/output) のような2文字の頭字語は完全に大文字にします。IO。一方、ID (identification) のような2文字の略語は、通常の単語と同様に大文字で表記されます。Id。

good↓

class HttpConnection {}
class DBIOPort {}
class TVVcr {}
class MrRogers {}

var httpRequest = ...
var uiHandler = ...
var userId = ...
Id id;

 

bad↓

class HTTPConnection {}
class DbIoPort {}
class TvVcr {}
class MRRogers {}

var hTTPRequest = ...
var uIHandler = ...
var userID = ...
ID iD;

 


PREFER using _, __, etc. for unused callback parameters.

Sometimes the type signature of a callback function requires a parameter, but the callback implementation doesn’t use the parameter.

コールバック関数の型名(型の宣言)にはパラメータが必要ですが、コールバックの実装ではパラメータを使用しない場合があります。

 

In this case, it’s idiomatic to name the unused parameter _.

この場合、未使用のパラメータに _ という名前を付けるのが慣用的です。

 

If the function has multiple unused parameters, use additional underscores to avoid name collisions: __, ___, etc.

関数に複数の未使用パラメータがある場合、名前の衝突を避けるため、

一つ目の引数 : _

二つ目の引数 : __

三つ目の引数 : ___

のように命名しましょう。

good

futureOfVoid.then((_) {
  print('Operation complete.');
});

 

This guideline is only for functions that are both anonymous and local. These functions are usually used immediately in a context where it’s clear what the unused parameter represents.

このガイドラインは無名関数でなおかつローカル関数である関数のためのものです。通常このような状況では、関数は即時に使用され、未使用のパラメータが何を表しているかが明らかな事が多い。

 

In contrast, top-level functions and method declarations don’t have that context, so their parameters must be named so that it’s clear what each parameter is for, even if it isn’t used.

それに対して、トップレベル関数やメソッド定義は上記のような状況とは異なります。そのためこれらの引数は(例え使用されなくても)ちゃんと命名して、それぞれの引数が何のためのものかをわかりやすく示しましょう。

 


DON’T use a leading underscore for identifiers that aren’t private.

プライベートでない識別子の命名には、先頭にアンダースコアをつけない。

 

Dart uses a leading underscore in an identifier to mark members and top-level declarations as private.

Dartではクラスのメンバやトップレベルでの宣言の際、プライベートであることを示すために名前の先頭にアンダースコアをつけます。

 

This trains users to associate a leading underscore with one of those kinds of declarations. They see “_” and think “private”.

このため、Dartユーザーは先頭のアンダースコアをこれらの宣言のいずれか(プライベートな変数や関数の宣言)に関連付けるように訓練されています。Dartユーザーは”_”を見て “private “と認識します。

 

There is no concept of “private” for local variables, parameters, local functions, or library prefixes.

ローカル変数、パラメータ、ローカル関数、ライブラリ接頭辞には「プライベート」という概念はありません。

 

When one of those has a name that starts with an underscore, it sends a confusing signal to the reader. To avoid that, don’t use leading underscores in those names.

上記のような意味合いで先頭にアンダースコアをつけるとreader(コードを読む人)が混乱するので、

プライベートなメンバには先頭にアンダースコアをつける、

プライベートでないメンバには先頭のアンダースコアをつけない、

ようにしましょう。


DON’T use prefix letters.

Hungarian notation and other schemes arose in the time of BCPL, when the compiler didn’t do much to help you understand your code.

Hungarian notationなどのスキームは、コンパイラがコードを理解するための手助けをあまりしてくれなかったBCPLの時代に生まれました。

 

Because Dart can tell you the type, scope, mutability, and other properties of your declarations, there’s no reason to encode those properties in identifier names.

Hungarian notationなどを使ってもあまり意味はないので使わないようにしましょう。

good↓

defaultTimeout

 

bad↓

kDefaultTimeout

 


Ordering

To keep the preamble of your file tidy, we have a prescribed order that directives should appear in.

ファイルの前文を整頓するために、ディレクティブを表示する順番が決められています。

directive : 指示、指令、コンピュータへの指令、つまりコード。

 

Each “section” should be separated by a blank line.

それぞれのセクションは改行して見やすくしましょう。

 

A single linter rule handles all the ordering guidelines: directives_ordering.

単一のリンタールールdirectives_orderingがすべての順序付けガイドラインを処理します。


DO place “dart:” imports before other imports.

“dart:”インポートを他のインポートよりも前に記述する。

good↓

import 'dart:async';
import 'dart:html';

import 'package:bar/bar.dart';
import 'package:foo/foo.dart';

 


DO place “package:” imports before relative imports.

相対インポートの前に “package: “インポートを配置する。

good↓

import 'package:bar/bar.dart';
import 'package:foo/foo.dart';

import 'util.dart';

 


DO specify exports in a separate section after all imports.

すべてのインポートの後に、エクスポートを別のセクションで指定してください。

good↓

import 'src/error.dart';
import 'src/foo_bar.dart';

export 'src/error.dart';

 

bad↓

import 'src/error.dart';
export 'src/error.dart';
import 'src/foo_bar.dart';

 


DO sort sections alphabetically.

good↓

import 'package:bar/bar.dart';
import 'package:foo/foo.dart';

import 'foo.dart';
import 'foo/foo.dart';

 

bad↓

import 'package:foo/foo.dart';
import 'package:bar/bar.dart';

import 'foo/foo.dart';
import 'foo.dart';

 


Formatting

Like many languages, Dart ignores whitespace. However, humans don’t.

他の多くの言語と同様、Dartも空白を無視します。しかし人間は違います。

 

Having a consistent whitespace style helps ensure that human readers see code the same way the compiler does.

空白のスタイルを統一することで、読者がコンパイラと同じ方法でコードを見ることができるようになります。


DO format your code using dart format.

dart formatでコードをフォーマットしましょう。

 

Formatting is tedious work and is particularly time-consuming during refactoring.

フォーマットは面倒な作業で、リファクタリング時には特に時間がかかります。

 

Fortunately, you don’t have to worry about it.

しかし幸運なことに私たちはこれを気にする必要はありません。

 

We provide a sophisticated automated code formatter called dart format that does it for you.

私たちは、dart formatと呼ばれる洗練された自動コードフォーマッターを提供しています。

 

We have some documentation on the rules it applies, but the official whitespace-handling rules for Dart are whatever dart formatproduces.

適用されるルールに関するドキュメントがいくつかありますが、Dartの公式の空白処理ルールは、dart formatで生成されるものです。

 

The remaining formatting guidelines are for the few things dart format cannot fix for you.

下記のフォーマットガイドラインは、dart formatが修正できないいくつかの事柄のためのものです。


CONSIDER changing your code to make it more formatter-friendly.

よりフォーマッタフレンドリーなコードに変更することを検討してください。

 

The formatter does the best it can with whatever code you throw at it, but it can’t work miracles.

フォーマッターは、あなたが投げかけたどんなコードにもベストを尽くしますが、奇跡を起こすことはできません。

 

If your code has particularly long identifiers, deeply nested expressions, a mixture of different kinds of operators, etc. the formatted output may still be hard to read.

特に長い識別子、深くネストした式、異なる種類の演算子などがコードに混在している場合、フォーマットされた出力が読みにくいかもしれません。

 

When that happens, reorganize or simplify your code. Consider shortening a local variable name or hoisting out an expression into a new local variable.

そんなときは、コードを整理したり、簡略化したりしましょう。ローカル変数名を短くしたり、式を新しいローカル変数に格納することを検討してください。

 

In other words, make the same kinds of modifications that you’d make if you were formatting the code by hand and trying to make it more readable.

つまり、手作業でコードを整形して読みやすくするのと同じような修正をするのです。

 

Think of dart format as a partnership where you work together, sometimes iteratively, to produce beautiful code.

美しいコードを書くためにdart formatの使用を検討してみましょう。


AVOID lines longer than 80 characters.

1行の文字数を80文字以内にしましょう。

 

Readability studies show that long lines of text are harder to read because your eye has to travel farther when moving to the beginning of the next line. This is why newspapers and magazines use multiple columns of text.

読みやすさの研究によると、長い行のテキストは、次の行の先頭に移動するときに目が遠くまで移動しなければならないため、読みにくくなることが分かっています。このため、新聞や雑誌では、複数の段組のテキストが使われています。

 

If you really find yourself wanting lines longer than 80 characters, our experience is that your code is likely too verbose and could be a little more compact.

もし、80文字以上の長い行が必要な場合は、コードが冗長すぎる可能性があり、もう少しコンパクトにする必要があると私たちは考えています。

 

The main offender is usually VeryLongCamelCaseClassNames. Ask yourself,

例えばVeryLongCamelCaseClassNamesのような感じです。 自問してみてください、

 

“Does each word in that type name tell me something critical or prevent a name collision?” If not, consider omitting it.

“その型名に含まれる各単語は、何か重要なことを教えてくれるのか、あるいは名前の衝突を防いでくれるのか?” そうでなければ、省略することを検討してください。

 

Note that dart format does 99% of this for you, but the last 1% is you. It does not split long string literals to fit in 80 columns, so you have to do that manually.

dart format はあなたの代わりに 99% の仕事を行ってくれますが、最後の 1% はあなたが行う必要があります。長い文字列リテラルを80文字に収まるように分割することはできませんので、あなたが手動で行う必要があります。

 

Exception: When a URI or file path occurs in a comment or string (usually in an import or export), it may remain whole even if it causes the line to go over 80 characters. This makes it easier to search source files for a path.

URIやファイルパスがコメントや文字列(通常はインポートやエクスポートの中)に含まれる場合、その行が80文字を超えることになっても、全体を残すことができます。これにより、ソースファイルのパス検索が容易になります。

 

Exception: Multi-line strings can contain lines longer than 80 characters because newlines are significant inside the string and splitting the lines into shorter ones can alter the program.

複数行の文字列には80文字を超える行を含めることができます。これは、文字列内で改行が重要であり、行を短い行に分割することはプログラムが変更になってしまうようなケースです。


DO use curly braces for all flow control statements.

curly braces(中カッコ( { } ))をすべてのフローコントロールステートメントで使いましょう

Doing so avoids the dangling else problem.

これによりdangling else問題を避けることができます。

good↓

if (isWeekDay) {
  print('Bike to work!');
} else {
  print('Go dancing or read a book!');
}

 


Exception: When you have an if statement with no else clause and the whole if statement fits on one line, you can omit the braces if you prefer:

else文無しのif文で、if文の中身が1行のみの場合、中カッコを省略しても良い。

good↓

if (arg == null) return defaultValue;

If the body wraps to the next line, though, use braces:

中身が2行以上の場合中カッコを使いましょう。

good↓

if (overflowChars != other.overflowChars) {
  return overflowChars < other.overflowChars;
}

 

bad↓

if (overflowChars != other.overflowChars)
  return overflowChars < other.overflowChars;

 

参考

https://dart.dev/guides/language/effective-dart/style

カテゴリーDart

“2022/5/30/Dart/Effective Dart/Styleの訳” への1件の返信

コメントを残す

メールアドレスが公開されることはありません。