揃っていないコードのインデントや改行などのフォーマットは、フォーマッタを使えば整えることができます。
ところで、C#において
- varを使うか使わないか
- privateなアクセス修飾子を明示するか
- 式形式のメソッドを使うかどうか
などのスタイルが統一されていない場合、どうすればいいでしょうか?
.NET向けJetBrains IDEである「Rider」では、Code Cleanupを使えば、フォーマットもスタイルも整えることができます。
また、余分なパラメーターや余分なコードも削除することができます。
この投稿では、RiderのCode Cleanupを紹介します。
Code Cleanupとは?
JetBrains Rider allows you to apply formatting and other code style preferences in a bulk mode to instantly eliminate code style violations in one or more files, in a project or in the entire solution.
Code Cleanupは、対象のコードのフォーマット・スタイルを規約・設定にそって整える機能です。
例えば、以下のコードはCode Cleanupによって
publicclassPlayer{ inthp; publicintHp{get{returnhp;}}publicPlayer(inthp){this.hp=hp;}}
次のようなコードになります。
publicclassPlayer{publicPlayer(inthp){Hp=hp;}publicintHp{get;}}
Code Cleanupによって、フォーマットが整えられ、getter onlyの自動実装プロパティに書き換えられました。
Code Cleanupの内容一部紹介
公式ドキュメント Code Cleanupより、一部を紹介します。
Apply file layout
: メンバの順番を並び替えるApply 'var' style
: ローカル変数において、varを使う、もしくは使わない。Code Styleの設定に依存。Use explicit or implicit modifier definition for types
: 型のinternalアクセス修飾子を明示するか、しない。Code Styleの設定に依存Use explicit or implicit modifier definition for type members
: 型のメンバのprivateアクセス修飾子を明示するか、しない。Code Styleの設定に依存Remove redundant parentheses
: 余分なカッコを減らすRemove code redundancies
: 余分なコードを排除するApply code body style
: 式形式のメソッドなどに置換するUse auto-property, if possible
: 可能なら自動実装プロパティに置換するMake field read-only, if possible
: 可能なら、readonlyキーワードをフィールドに追加するMake auto-property get-only, if possible
: getterのみの自動実装プロパティに変換する
JetBrains Rider allows you to apply formatting and other code style preferences in a bulk mode to instantly eliminate code style violations in one or more files, in a project or in the entire solution.
この一文からは、フォーマットとスタイルだけを変えるという想像をしますが、ガッツリコードを書き換える点に注意してください。(原則、同じ動作はするコードに書き換えます。)
同じような動作はしますがコンパイル後のMSILとしては、全く別のコードになります。
Code Cleanupの使い方
メニューから、Code | Code Cleanup ...
を選択すると、以下のウィンドウが開きます。
Code Cleanupの対象と設定をそれぞれ選択してOKボタンを押すと、Code Cleanupが実行されます。
または、Show Reformat Code Dialog
から、Code Cleanupの有無を選択することもできます。
Code Cleanupの対象
Code Cleanupは、ソリューション全体、プロジェクト全体、コミットされていないファイル、カスタムスコープ、開いているファイルから選択できます。
また、テキストを選択し、選択したテキストの中身に対してCode Cleanupをかけることもできます。Code Cleanupしたいテキストを選択し、アクションリストを表示し(Alt + Enter)、リストの中から、Cleanup selection
を選んでください。
Code Cleanupの設定
Code Cleanupの設定は、Built-inでいくつか設定が作成されています。
Preference | Editor | Code Cleanup
において、その設定を編集したり、コピーして編集したりできます。
また、自分で0から作ることも可能です。自分のプロジェクトに合った設定を作ってみてください。
Commit時のCode Cleanup
Riderからgit commit
をした際に、Code Cleanupを実行するよう、設定できます。
https://www.jetbrains.com/help/rider/2019.2/Commit_Changes_Dialog.html#before_commit
Unityに関するバグ
Unityにおける、Code Cleanupに関する問題として、次のようなコードが
publicclassMover:MonoBehaviour{[SerializeField]privatefloatspeed;publicfloatSpeed{get=>speed;set=>speed=value;}}
次のようなコードに変更されてしまうというものがありました。
publicclassMover:MonoBehaviour{[field:SerializeField]publicfloatSpeed{get;set;}}
普通のC#としては問題がないのですが、Unityとしてはバッキングフィールドの名前が大事なので、こうなってしまうCode Cleanupの項目が使えませんでした。
この問題は、Rider 2019.3で解消される予定です。