- Put your Android Studio on a diet
- How to make a deep clean of your Android Studio & Gradle junk files to fix up the mess.
- Clear your project directory
- Gradle cleaning
- Android Studio cleanup
- Extra cleaning
- Разбираемся с Clean Code в Android
- Что такое «Чистый Код»?
- Я должен заботиться об этом?
- Признаки Чистого кода
- Пишите осознанные имена
- Имена классов
- Имена методов
- Пишите код, придерживаясь SOLID принципов
- Принцип единственную ответственности (S)
- Принцип открытости/закрытости (О)
- Принцип подстановки Барбары Лисков (L)
- Принцип разделения интерфейса
- Принцип инверсии зависимостей
- Code cleanup
- Code cleanup profiles
- Create a new custom cleanup profile
- Run code cleanup
- Clean up the selection or the whole file
- Clean up multiple files, projects, or entire solution
- Clean up code before committing it to Git
- Silent cleanup
- Assign a profile for silent code cleanup
- Run code cleanup in silent mode
- Available code cleanup tasks
- VB.NET
- JavaScript-like languages
- JavaScript
- TypeScript
Put your Android Studio on a diet
How to make a deep clean of your Android Studio & Gradle junk files to fix up the mess.
Do you know that when you’re updating your Android Studio, Gradle or even dependencies, some old files are still present on your machine and can waste some disk free space?
On our laptops, disk space is limited and clearing those files will make you gain a lot of free space available. Having too many junk files may also slow down your machine and your builds!
In my case, I was also having strange build errors or gradle sync failures when it was working on my colleague’s machine.
It was time to do some deep cleaning and put our Android Studio on a diet by following some simple steps.
Clear your project directory
- Obviously, try to clean your project from android studio : “ Build -> Clean Project”. This will clear your build folders.
- Clear the cache of Android Studio using “ File -> Invalidate Caches / Restart” choose “ Invalidate and restart option” and close Android Studio.
- Remove your .gradle directory from the root of your project. It contains some Gradle cache files.
- Delete also the .idea directory ( make a backup before). It contains some project configuration files.
- Restart Android Studio.
Big project directories can weight around 500MB to 1GB.
Gradle cleaning
Now let’s take a look at Gradle files. If none of the above suggestions fix your problem, try these:
/.gradle directory. This is the Gradle home directory, containing caches, daemons and wrappers files. This is a really huge one, mine was
Inside those directories, you’ll have sub-directories for each version of Gradle you’ve been using. So, the more projects you have with different Gradle versions, the more sub-directories you will have.
You can delete those 3 directories:
- caches: Gradle cache files.
- daemon: essentially logs files of Gradle daemons.
- wrapper: different distributions of Gradle downloaded on you machine.
Android Studio cleanup
- Go to your Android home, usually
/.android and clear build-cache and cache directories. There are few MB to free here (
100MB for me)
In the
/Library/ directories, you will find the Android Studio preferences files, settings and plugins. You can clear the directories of previous version of Android Studio (> 1GB per version of AS). Starting with version 3.3, Android Studio will propose you to remove them after an update.
Android SDK cleaning
On Android Studio, check the SDK Manager and remove the following items:
- Old SDKs you don’t use anymore. I guess you’ll not miss the Android 3.0 SDK files.
- Remove the emulators you don’t use as they’re quite heavy ( some GB).
- I recommend to keep “Sources for Android xx” items as it will allow you to check the source code of the SDK from a previous version of Android & help you debugging.
- On the SDK Tools tab, click on “Show Packages Details” and uncheck the old build-tools or NDK versions.
- Delete unused emulators using the AVD.
You can gain easily 10GB with these steps.
Extra cleaning
There is some extra stuff you can clean too:
- Your download directory: you may have downloaded a lot of GIFs, video, Android Studio binaries that you can remove.
- Clear your local git branches that have been merged (don’t remove the ones that you still need!).
- Delete all those photoshopped pictures of your colleagues ( ͡° ͜ʖ ͡°).
- Clear your recycle bin.
That’s it ! You’ve gained some precious disk space on your machine and maybe fixed some weird issues with your Android Studio.
I don’t recommend to do a full clean everyday, you’ll waste time and your build time will be quite longer so you’ll be less productive. Take it only as a “spring cleaning” ritual.
I hope it helped you, and don’t forget to follow the Marie Kondo mantra and only keep things that spark joy.
Источник
Разбираемся с Clean Code в Android
Вы читаете эту статью по двум причинам. Первая — Вы программист, вторая — Вы хотите быть лучшим программистом.
Представьте, что Вы находитесь в библиотеке и ищете какие-то книги. Если библиотека сортирована, имеет категории книг, то вы быстро отыщите нужную Вам. Кроме того, крутой дизайн интерьера и архитектура сделает пребывание в этой библиотеке довольно комфортным для Вас.
Как и при написании книг, если вы хотите создать что-то великое, то вы должны знать как писать и как организовывать свой код. Если у вас есть члены команды или кто-то еще, у кого есть Ваш (устаревший) код, им просто нужно увидеть имена переменных или пакеты или классы, и они сразу поймут. Им не нужно говорить «Е**л» я этот код и начинать его снова с нуля.
Что такое «Чистый Код»?
Когда я писал этот код, только Бог и я знал как он работает!
Теперь только Бог знает это!
Перед тем как ты попытаешься оптимизировать эту рутину и это не приведет к успеху (наиболее вероятно), пожалуйста увеличь счетчик затраченного времени для предостережения следующего разработчика
Всего потрачено часов: 567
Как Вы можете видеть, недостаточно закончить разработку быстрее. Если в будущем в этом коде не смогут разобраться, то это так же станет техническим долгом.
Ваш код имеет состояние «Чистый», если его может понять каждый член Вашей команды. Чистый код может быть прочитан и улучшен любым разработчиком, отличным от первоначального автора. С пониманием приходит читаемость, изменяемость, расширяемость и ремонтопригодность.
Я должен заботиться об этом?
Причина, по которой Вы должны заботиться о чистоте своего кода, заключается в том, что Вы описываете ход своих мыслей другим разработчикам. Именно поэтому Вы должны заботиться о том, что Ваш код был более элегантным, простым и читаемым.
Признаки Чистого кода
Отличие между хорошим программистом и профессионалом в том, что профессиональный программист понимает, что понятность кода первостепенна. Профессионал использует эту силу для написания кода, который понятен всем — Robert C. Martin
Пишите осознанные имена
Выбор хорошего имени, может занять много времени, но в последствии оно сэкономит больше. Имя переменной, функции, класса должно отвечать на все значимые вопросы. Оно должно рассказать Вам, почему оно существует, зачем оно нужно и как его использовать. Если имя требует комментария, то имя не раскрывает своего предназначения
Имена классов
Классы и объекты должны быть существительными, например Сustomer, WikiPage, Account, and AddressParser. Избегайте таких слов как Manager, Processor, Data, или Info. Помните так же, что имя класса не должно быть глаголом.
Имена методов
Имена методов же должны быть глаголами, например postPayment, deletePage или save. Модификаторы доступа, предикаты должны быть названы по их значению и с префиксом get, set и согласно стандарту JavaBean.
Перед тем, как мы продолжим сделайте небольшой перерыв, запаситесь кофе и печеньками
Окей, теперь перейдем к SOLID принципам
Пишите код, придерживаясь SOLID принципов
Эти принципы были разработаны дядюшкой Бобом, SOLID это аббревиатура, описывающая набор принципов, предназначенных для написания хорошего кода.
Принцип единственную ответственности (S)
Это означает, что каждый класс должен нести только одну ответственность. Никогда не должно быть более одной причины для изменения класса. Не надо добавлять все в свой класс, просто потому что Вы можете это сделать. Разбивайте большие классы на более маленькие и избегайте God Classes.
У нас есть RecyclerView.Adapter с бизнес логикой внутри onBindViewHolder
Это делает RecyclerView.Adapter не имеющим единственную ответственность, потому что он содержит бизнес логику внутри onBindViewHolder. Этот метод отвечает только за вставку данных во view.
Принцип открытости/закрытости (О)
Программные сущности должны быть открыты для расширения, но закрыты для модификации. Это означает, что если Вы разрабатываете класс А и ваши коллеги захотят изменить функцию внутри этого класса. Они смогут легко это сделать, расширив этот класс без изменения самого класса.
Простой пример класс RecyclerView.Adapter. Вы можете с легкостью расширить его и создать свой собственный адаптер с нестандартным поведением без модификации самого RecyclerView.Adapter.
Принцип подстановки Барбары Лисков (L)
Дочерний класс должен дополнять родительский, а не изменять его. Это означает, что подкласс должен переопределять методы родительского, которые не нарушают функциональность этого родительского класса. Например мы создаем интерфейс класса, который имеет onClick() слушатель а затем вы применяете слушатель в MyActivity и даете ему действие Toast, когда вызывается onClick ().
Принцип разделения интерфейса
Этот принцип гласит, что клиент не должен быть зависим от методов, которые он не использует.
Это означает, что если Вы хотите написать класс А и добавить в него функциональность другого класса В. Нет необходимости переопределять все классы А внутри класса В.
Пример: в нашей активити, нам нужно реализовать SearchView.OnQueryTextListener(), но нам нужен только onQuerySubmit() метод.
Как мы это сделаем? Легко! Просто создадим callback и класс, расширяющий SearchView.OnQueryTextListener()
И вот так мы добавим это к нашей view
Или так, используя Extension Function в Kotlin
Принцип инверсии зависимостей
Зависимость на абстракциях, без зависимости на что-то конкретное.
Определение инверсии зависимостей от дядюшки Боба состоит из двух понятий.
Модули верхних уровней не должны зависеть от модулей нижних уровней. Оба должны быть завязаны на абстракциях. Абстракции не должны зависеть от деталей. Детали должны зависеть от абстракций. Модули высоких уровней, которые реализуют комплексную логику, должны быть легко переиспользуемы без изменений в модулях нижнего уровня. Для этого Вам нужно ввести абстракцию, которая отделяет модули верхнего и нижнего уровней друг от друга.
Простой пример этого MVP паттерн. У Вас есть объект интерфейсов, который помогает Вам общаться с конкретными классами. Что имеется ввиду — классам UI (Activity/Fragment) не нужно знать фактическую реализацию методов презентера. Таким образом, если Вы делаете изменения внутри презентера, UI классы не должны волновать эти изменения
Давайте взглянем на пример
А теперь на активити
Таким образом мы создаем интерфейс, который абстрагирует реализацию презентатора, и наш класс view сохраняет ссылку на PresenterInterface.
Источник
Code cleanup
You can also run code cleanup using the command-line utility.
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.
Fixing inconsistent naming is not included in code cleanup because when batch-applied it can lead to naming conflicts.
Code cleanup profiles
Code cleanup can have various configurations (profiles) to apply in different cases according to your needs. There are three default profiles available out of the box:
Built-in: Reformat Code that only applies code formatting preferences
Built-in: Reformat & Apply Syntax Style that applies code formatting preferences and code syntax styles.
Built-in: Full Cleanup that applies all available cleanup tasks except updating file header.
These profiles help in most cases but you cannot configure them. If you want to run code cleanup with the custom set of cleanup tasks, you need to create a custom profile and specify the set of desired tasks there.
Code cleanup settings, including custom profiles, can be shared with fellow developers to ensure uniform look and feel of your code (see Layer-based settings for details).
Create a new custom cleanup profile
Press Ctrl+Alt+S or choose File | Settings (Windows and Linux) or JetBrains Rider | Preferences (macOS) from the menu.
Go to the cleanup profiles settings page: Editor | Code Cleanup .
Click Add on the top of the page. JetBrains Rider will create a new cleanup profile.
Select the newly created profile in the list of profiles.
Use the right pane to configure the list of tasks in the selected profile.
Click Save in the Settings dialog to apply the modifications and let JetBrains Rider choose where to save them, or save the modifications to a specific settings layer using the Save To list. For more information, see Layer-based settings.
Your newly created cleanup profile will be available in the Code Cleanup dialog ( Code | Code Cleanup ) when you are running code cleanup. You can also set this profile to be used for the silent cleanup.
Run code cleanup
JetBrains Rider can apply code cleanup to an arbitrarily selected block of code, all code in the current file, all files in a directory, files in the current VCS changelist, the current project, or even the current solution. Make sure that you select the right set of cleanup tasks by choosing the right cleanup profile.
Code cleanup is not applied to generated code. By default, JetBrains Rider provides the list of file masks and regions for generated code typically produced by Visual Studio (for example, Windows Form Designer-generated code). If necessary, you can edit the list of generated items on the Editor | Inspection Settings | Generated Code page of JetBrains Rider settings Ctrl+Alt+S .
Clean up the selection or the whole file
Select the scope where you want to clean up code:
Make a selection in the editor to clean up code in the selection.
Set the caret anywhere in the file to clean up code in the file.
Press Ctrl+E, C or choose Code | Reformat and Cleanup. from the main menu.
In the Code Cleanup dialog that opens, you can check and optionally change the scope for cleaning code and choose a cleanup profile to apply. Use the area to the right of the selected profile to check the tasks included in that profile.
If none of the available profiles suits you, click Edit , then choose one of the existing profiles and click Clone to create a new custom profile and save the changes.
Click OK to clean code in the selected scope.
You can clean up not only an individual file, but also multiple files in a directory, project or entire solution. To do so, you should run code cleanup from the Solution Explorer .
Clean up multiple files, projects, or entire solution
Select one or more items (files, directories, projects, or the solution) in the Solution Explorer .
Press Ctrl+E, C or choose Code | Reformat and Cleanup. from the main menu.
Choose a cleanup profile as described above.
Click OK to clean code in the selected scope.
You can also run code cleanup on code that you have recently modified and are going to commit to Git. JetBrains Rider will run the selected cleanup profile before committing.
Clean up code before committing it to Git
Press Ctrl+K or select Git | Commit from the main menu.
In the Commit tool window, click and in the Before Commit area, select the Cleanup with. checkbox.
Optionally, you can click Choose profile to specify the cleanup profile that should be used.
Click Commit or Commit and Push . JetBrains Rider will run code cleanup on the ranges selected for commit and then commit the changes.
Silent cleanup
You can also run code cleanup in the silent mode — that is, without displaying the Code Cleanup dialog. Since in this case you will not be able to choose a profile explicitly, you have to assign some cleanup profile to use for the silent code cleanup.
JetBrains Rider does not make a default selection of the silent cleanup profile. This means that until you select a profile by yourself, JetBrains Rider will open the Code Cleanup dialog whenever you launch silent code cleanup.
Assign a profile for silent code cleanup
Press Ctrl+Alt+S or choose File | Settings (Windows and Linux) or JetBrains Rider | Preferences (macOS) from the menu.
Go to the cleanup profiles settings page: Editor | Code Cleanup .
Select a cleanup profile on the left and click Set as default for silent cleanup at the top of the options page.
Click Save in the Settings dialog to apply the modifications and let JetBrains Rider choose where to save them, or save the modifications to a specific settings layer using the Save To list. For more information, see Layer-based settings.
Run code cleanup in silent mode
Do one of the following:
To run silent code cleanup in a specific code file, open it in the text editor or select it in the Solution Explorer .
To apply silent code cleanup to a set of files (directory, project, or solution), select the corresponding item in the Solution Explorer .
Press Ctrl+E, F or choose Code | Silent Reformat and Cleanup from the main menu. Alternatively, you can press Ctrl+Shift+A , start typing the command name in the popup, and then choose it there.
Available code cleanup tasks
The tables below list available cleanup tasks for different languages. If you need the cleanup to perform only a part of these tasks, you can create a custom cleanup profile for that.
Apply file layout
Reorders type members in files according to the rules configurable on the Editor | Code Style | C# | File Layout page of JetBrains Rider settings Ctrl+Alt+S . For more information, see Rearrange members with file and type layout patterns.
Update file header
Inserts or updates the file header comment
Apply ‘var’ style
Applies the rules for ‘var’ usage during the cleanup. The rules are configurable on the Editor | Code Style | C# | Syntax Style page of JetBrains Rider settings Ctrl+Alt+S .
Use explicit or implicit modifier definition for types
Applies the rule for type modifiers — whether on not to use the internal modifier explicitly. The rule is configurable on the Editor | Code Style | C# | Syntax Style page of JetBrains Rider settings Ctrl+Alt+S . For more information, see Code Syntax Style: Modifiers.
Use explicit or implicit modifier definition for type members
Applies the rule for type member modifiers — whether on not to use the private modifier explicitly. The rule is configurable on the Editor | Code Style | C# | Syntax Style page of JetBrains Rider settings Ctrl+Alt+S . For more information, see Code Syntax Style: Modifiers.
Applies the preferred order of type/member modifiers. The rule is configurable on the Editor | Code Style | C# | Syntax Style page of JetBrains Rider settings Ctrl+Alt+S . For more information, see Code Syntax Style: Modifiers.
Apply arguments style (named | positional)
Applies the preferences for named/positional arguments for specific types of parameters. The preferences are configurable on the Editor | Code Style | C# | Syntax Style page of JetBrains Rider settings Ctrl+Alt+S . For more information, see Code Syntax Style: Named/Positional Arguments.
Remove redundant parentheses
Removes redundant optional parentheses in cases specified on the Editor | Code Style | C# | Syntax Style page of JetBrains Rider settings Ctrl+Alt+S . For more information, see Code Syntax Style: Optional Parentheses.
Add parentheses to explicitly specify operation precedence
Adds optional parentheses to clarify precedence of operations in cases specified on the Editor | Code Style | C# | Syntax Style page of JetBrains Rider settings Ctrl+Alt+S . For more information, see Code Syntax Style: Optional Parentheses.
Add/remove braces around single statements
Adds or removes optional braces around single nested statements as specified on the Editor | Code Style | C# | Syntax Style page of JetBrains Rider settings Ctrl+Alt+S . For more information, see Code Syntax Style: Braces for Single Nested Statements.
Add/remove brackets for attributes
Applies the rules for multiple attributes as specified on the Editor | Code Style | C# | Syntax Style page of JetBrains Rider settings Ctrl+Alt+S . For more information, see Code Syntax Style: Multiple Attributes.
Apply code body style
Applies preferences for bodies of type members (expression body | statement body) as specified on the Editor | Code Style | C# | Syntax Style page of JetBrains Rider settings Ctrl+Alt+S . For more information, see Code Syntax Style: Bodies of Type Members.
Arrange trailing commas
Applies preferences for trailing commas in declarations with multiple items and similar constructs (object, array, and collection initializers, as well as enums and switch expressions) as specified on the Editor | Code Style | C# | Syntax Style page of JetBrains Rider settings Ctrl+Alt+S . For more information, see Code Syntax Style: Trailing Commas.
Apply object creation style (‘new()’ vs ‘new T()’)
Applies preferences for using the target-typed new operator in C# 9.0 and later as specified on the Editor | Code Style | C# | Syntax Style page of JetBrains Rider settings Ctrl+Alt+S . For more information, see Code Syntax Style: Object Creation (‘new()’ vs ‘new T()’).
Apply default value style (‘default’ vs ‘default(T)’)
Applies preferences for using optional type specification in default value expressions as specified on the Editor | Code Style | C# | Syntax Style page of JetBrains Rider settings Ctrl+Alt+S . For more information, see Code Syntax Style: Default Value Expressions (‘default’ vs ‘default(T)’).
Remove code redundancies
On the Editor | Inspection Severity page of JetBrains Rider settings Ctrl+Alt+S , in the Redundancies in Code categories for most languages, JetBrains Rider lists over 50 redundancies that have associated code inspections. Some of them require special attention, and you cannot process them in the batch mode. That leaves Code Cleanup with about 30 redundancies that it is able to remove automatically whenever you select Remove code redundancies in your cleanup profile.
Specifically, code cleanup:
Redundant empty constructors.
Explicit integer type specifiers in enumerations.
true specifiers in for statements.
Redundant type casts.
Redundant parentheses from attributes without arguments.
Explicit calls to base class constructors without arguments.
Redundant boolean comparisons.
Redundant braces from collection initializers with a single expression.
Redundant explicit delegate creation expressions.
Empty argument lists from object/collection initializers.
Redundant new keywords.
Redundant partial modifiers on type declarations where a type has a single part.
Redundant unsafe contexts and statements.
Redundant object.ToString() calls (for example, in a concatenation with a string or as an argument of a string.Format() call).
Redundant string.ToCharArray() calls.
Redundant specifications of argument types.
Signatures in anonymous methods where its parameters are not used in the method body.
Redundant field initializers.
Redundant explicit names in anonymous type properties.
Redundant nullable types where value type is implicitly convertible to nullable.
Nullable types to short form Nullable to T? .
Static method invocations to extension method calls where extension methods are invoked as static methods.
To implicitly typed array creation expressions when array type can be inferred from initializer.
Occurrences where static members of a type are accessed via derived members of the type.
Use auto-property, if possible
Replaces simple properties and corresponding backing fields with auto-properties. For more information, see Use auto-properties.
Make field read-only, if possible
Adds the ‘readonly’ keyword to fields that are assigned in the declaration or in a constructor and only have read usages. For more information, see Make fields readonly.
Make auto-property get-only, if possible
Removes the redundant set accessor on auto-properties that are initialized from the constructor/initializer and have no write usages. Note that this task only works for C# 6.0.
By default, JetBrains Rider automatically detects C# version based on the associated compiler. However, you can specify the target C# version explicitly for a project — press Alt+Enter on the project in the Solution Explorer and use the Language version selector on the Application page of the Project Properties dialog.
To set the C# version for all projects in your solution , specify it in a Directory.Build.props file in your solution directory as described here.
Applies the rules for qualifying type members. The rules are configurable on the Editor | Code Style | C# | Syntax Style page of JetBrains Rider settings Ctrl+Alt+S . For more information, see Code Syntax Style: Optional Member Qualifiers.
Fix built-in type references
Applies the rule for built-in type names (C# keyword or CLR type name). The rule is configurable on the Editor | Code Style | C# | Syntax Style page of JetBrains Rider settings Ctrl+Alt+S . For more information, see Code Syntax Style: Built-In Type References.
Includes the following configurable options:
Optimize ‘using’ directives
Removes unused namespace import directives
and sorts the namespace import directives: all System.* namespaces go first, sorted alphabetically by the second word after the dot; all other namespaces go next, in alphabetical order.. For more information, see Code Syntax Style: Namespace Imports.
Embrace ‘using’ directives in region
If this checkbox is selected, a new region for wrapping all namespace import directives is created during cleanup.
Allows specifying a name for the region wrapping namespace import directives.
Shorten qualified references
Replaces fully qualified names with short names when possible by importing namespaces, implementing settings configured on the Editor | Code Style | C# | Syntax Style page of JetBrains Rider settings Ctrl+Alt+S .
Reformats your code according to the preferences that you can configure on the Editor | Code Style | C# page of JetBrains Rider settings Ctrl+Alt+S . For more information, see Manage and apply formatting rules.
Reformat embedded XML doc comments
Reformats XML doc comments according to options configurable on the Editor | Code Style | C# | XML Doc Comments page of JetBrains Rider settings Ctrl+Alt+S .
Note that JetBrains Rider does not reformat plain comments like:
Collapse empty tags
Removes the closing tag if the tag body is empty.
Remove redundant attributes
Removes attributes, such as Freeze , modifiers , name , span , UpdateSourceTrigger , Mode if they are redundant in the context
Remove redundant resource
Removes resource references that are not used
Remove redundant property setters
Removes unused setters for the following properties: property , attached , style .
Remove redundant namespace alias
Remove all redundant namespace aliases in the scope of cleanup. Redundant aliases are also detected with the code inspection and can be removed with a quick-fix.
Remove redundant definitions
Removes definitions if they are redundant in the context
Remove forbidden attributes
Removes attributes, such as name , span if they are forbidden in the context
Reformats your code according to the preferences that you can configure on the Editor | Code Style | XML page of JetBrains Rider settings Ctrl+Alt+S . For more information, see Manage and apply formatting rules.
VB.NET
Remove code redundancies
Removes redundant code the same way as for C# Language
Optimize ‘import’ directives
Removes unused namespace import directives
Shorten qualified references
Replaces fully qualified names with short names when possible by importing namespaces, implementing settings configured on the Editor | Code Style | VB.NET | Syntax Style page of JetBrains Rider settings Ctrl+Alt+S .
Reformats your code according to the preferences that you can configure on the Editor | Code Style | VB.NET page of JetBrains Rider settings Ctrl+Alt+S . For more information, see Manage and apply formatting rules.
Reformat embedded XML doc comments
Reformats XML doc comments according to options configurable on the Editor | Code Style | C# | XML Doc Comments page of JetBrains Rider settings Ctrl+Alt+S .
Note that JetBrains Rider does not reformat plain comments like:
Rearranges CSS properties in the alphabetical order.
Reformats your code according to the preferences that you can configure on the Editor | Code Style | CSS page of JetBrains Rider settings Ctrl+Alt+S . For more information, see Manage and apply formatting rules.
JavaScript-like languages
Apply statement termination
Adds the optional semicolon ; at the end of statements in JavaScript, TypeScript, and JSON.
JavaScript
JavaScript cleanup tasks also apply to TypeScript code.
Normalize quotes around string literal
Applies the preferred quote style: single quote (‘) or double quote («). The preference can be configured on the Editor | Code Style | TypeScript | Syntax Style page of JetBrains Rider settings Ctrl+Alt+S .
Correct ‘var’ to ‘let’/’const’ where possible
let and const are supported in the following cases:
In JavaScript code, if the target JavaScript language level is ECMAScript 6 (you can choose it on the Languages & Frameworks | JavaScript page of JetBrains Rider settings Ctrl+Alt+S )
In TypeScript 1.4, if the target ECMAScript 6 is selected in the project properties.
In TypeScript 1.5 or later.
Move let/const to most possible inner scopes
Moves variables defined outside of a function/compound statement, and so on closer to their usages if there are no other usages in outer scopes.
Convert string concatenations to template strings
In JavaScript code, if the target JavaScript language level is ECMAScript 6 (you can choose it on the Languages & Frameworks | JavaScript page of JetBrains Rider settings Ctrl+Alt+S ), as well as in TypeScript 1.4 or later, this option will convert string concatenations to template strings. For example:
will be converted to
Reformats your code according to the preferences that you can configure on the Editor | Code Style | JavaScript page of JetBrains Rider settings Ctrl+Alt+S . For more information, see Manage and apply formatting rules.
Reformat embedded XML doc comments
Reformats XML doc comments according to options configurable on the Editor | Code Style | C# | XML Doc Comments page of JetBrains Rider settings Ctrl+Alt+S .
Note that JetBrains Rider does not reformat plain comments like:
TypeScript
Remove redundant qualifiers
Use this option to remove redundant type name qualifiers.
Optimize ‘import’ statements
Use this option to remove redundant ‘import’ statements or fully-qualified names according to the settings configurable on the Editor | Code Style | TypeScript | Syntax Style page of JetBrains Rider settings Ctrl+Alt+S .
Optimize reference comments
Use this option to remove redundant reference comments.
Synchronize ‘public’ presence with code style
This option lets you add or remove explicit ‘public’ modifier according to settings configurable on the Editor | Code Style | TypeScript | Syntax Style page of JetBrains Rider settings Ctrl+Alt+S .
Add explicit ‘any’ type annotation if needed
This option lets you add explicit ‘any’ annotation to types according to settings configurable on the Editor | Code Style | TypeScript | Syntax Style page of JetBrains Rider settings Ctrl+Alt+S .
Synchronize type annotation presence with code style
This option lets you enforce explicit/implicit typing according to settings configurable on the Editor | Code Style | TypeScript | Syntax Style page of JetBrains Rider settings Ctrl+Alt+S .
Fix relative path style in ‘require’ if needed
Applies the Relative file reference style in ‘require’ code style preference for relative paths in the require keyword. For example, import X = require(«file1») or import X = require(«./file1») . You can configure this preference on the Editor | Code Style | TypeScript | Syntax Style page of JetBrains Rider settings Ctrl+Alt+S .
Use ‘as’ instead of type assertions
which is a recommended way to avoid ambiguity with JSX syntax.
Reformats your code according to the preferences that you can configure on the Editor | Code Style | HTML page of JetBrains Rider settings Ctrl+Alt+S . For more information, see Manage and apply formatting rules.
Normalize quotes around attribute value
Applies the preferred quote style: single quote (‘) or double quote («).
Источник