<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nagendran P on Medium]]></title>
        <description><![CDATA[Stories by Nagendran P on Medium]]></description>
        <link>https://medium.com/@nagendran.p?source=rss-333b38c1fc12------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*1TF2Rqt9hrhr_n-9</url>
            <title>Stories by Nagendran P on Medium</title>
            <link>https://medium.com/@nagendran.p?source=rss-333b38c1fc12------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 22:45:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nagendran.p/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Kotlin Koin — Android Tutorial]]></title>
            <link>https://medium.com/@nagendran.p/kotlin-koin-android-tutorial-e63e7575109e?source=rss-333b38c1fc12------2</link>
            <guid isPermaLink="false">https://medium.com/p/e63e7575109e</guid>
            <category><![CDATA[kotlin-koin]]></category>
            <dc:creator><![CDATA[Nagendran P]]></dc:creator>
            <pubDate>Thu, 30 Dec 2021 13:04:14 GMT</pubDate>
            <atom:updated>2021-12-30T13:04:14.874Z</atom:updated>
            <content:encoded><![CDATA[<h2>Kotlin Koin — Android Tutorial</h2><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dBzT3n80vDuPP2hwTGpwHw.jpeg" /></figure><p>We have been using the Dependency Injection framework quite a few times like Dagger in our project</p><p>In this blog, we are going to learn about Koin, a new dependency injection framework for Android Developers</p><p>We are going to discuss,</p><ul><li>What is Koin?</li><li>Understanding terminologies in Koin</li><li>Setting up your project</li><li>Project Structure</li><li>Integrating Koin</li></ul><h3>What is Koin?</h3><p>Koin is a DI framework for Kotlin developers, completely written in Kotin.</p><p>It is very light weighted. It supports the Kotlin DSL feature. It is one of the easy DI frameworks which doesn’t require a steep learning curve to get hold of it.</p><h3>Understanding Terminologies in Koin</h3><p>While working with Koin, there are few terminologies we need to understand before getting started.</p><ul><li><strong>module</strong> — it creates a module in Koin which would be used by Koin to provide all the dependencies.</li><li><strong>single</strong> — it creates a singleton that can be used across the app as a singular instance.</li><li><strong>factory</strong> — it provides a bean definition, which will create a new instance each time it is injected.</li><li><strong>get()</strong> — it is used in the constructor of a class to provide the required dependency.</li></ul><h3>Setting up your project</h3><p>Here, we are going to set up the Android Project.</p><p><strong>Create a Project</strong></p><ul><li>Start a new Android Studio Project</li><li>Select Empty Activity and Next</li><li>Name: Koin-Tutorial</li><li>Package name: com.mindorks.framework.mvvm</li><li>Language: Kotlin</li><li>Finish</li><li>Your starting project is ready now</li></ul><p><strong>Add dependencies</strong></p><p>Add the following dependencies in the app’s build.gradle file,</p><pre>implementation &quot;androidx.recyclerview:recyclerview:{latest-version}&quot;<br>implementation &#39;android.arch.lifecycle:extensions:{latest-version}&#39;<br>implementation &#39;com.github.bumptech.glide:glide:{latest-version}&#39;<br>implementation &#39;androidx.activity:activity-ktx:{latest-version}&#39;</pre><p>Now our project is ready with dependencies.</p><h3>Integrating Koin</h3><p>To setup Koin in your project, we would add the following in your app’s build.gradle,</p><pre><em>//koin</em><br>implementation &quot;org.koin:koin-android-viewmodel:{latest-version}&quot;<br>implementation &quot;org.koin:koin-android:{latest-version}&quot;</pre><p>This is the only required setup we need to do to get started with Koin.</p><p>Now, let’s break the further tasks in steps.</p><p><strong>Step 01.</strong></p><p>We will first create our Application class App like,</p><pre><strong>class</strong> <strong>App</strong> : <strong>Application</strong>()</pre><p>and we will update the Manifest file like,</p><pre>android:name=&quot;.App&quot;</pre><p><strong>Step 02.</strong></p><p>Now, we will add the dependencies for Retrofit and <a href="https://blog.mindorks.com/mastering-kotlin-coroutines-in-android-step-by-step-guide">Kotlin-Coroutines</a> in the app’s build.gradle like,</p><pre><em>// Networking</em><br>implementation &quot;com.squareup.retrofit2:retrofit:{latest-version}&quot;<br>implementation &quot;com.squareup.retrofit2:converter-moshi:{latest-version}&quot;<br>implementation &quot;com.squareup.okhttp3:okhttp:{latest-version}&quot;<br>implementation &quot;com.squareup.okhttp3:logging-interceptor:{latest-version}&quot;</pre><pre><em>// Coroutine</em><br>implementation &quot;org.jetbrains.kotlinx:kotlinx-coroutines-android:{latest-version}&quot;<br>implementation &quot;org.jetbrains.kotlinx:kotlinx-coroutines-core:{latest-version}&quot;</pre><p>Now, in the project what we will do is, we will do an API call and show a list of users.</p><p>We will also use Kotlin-Coroutine for multithreading. Now, we will create <strong>api</strong>, <strong>model</strong>, <strong>repository</strong> packages inside the data layer. It will have files like,</p><p>Then, ApiService looks like,</p><pre><strong>interface</strong> <strong>ApiService</strong> {</pre><pre>    <strong>@GET</strong>(&quot;users&quot;)<br>    suspend fun <strong>getUsers</strong>(): Response&lt;List&lt;User&gt;&gt;</pre><pre>}</pre><p>ApiHelper looks like,</p><pre><strong>interface</strong> <strong>ApiHelper</strong> {</pre><pre>    suspend fun <strong>getUsers</strong>(): Response&lt;List&lt;User&gt;&gt;<br>}</pre><p>And finally, the ApiHelperImpl looks like,</p><pre><strong>class</strong> <strong>ApiHelperImpl</strong>(<strong>private</strong> <strong>val</strong> <strong>apiService</strong>: <strong>ApiService</strong>) : <strong>ApiHelper</strong> {</pre><pre>    override suspend fun <strong>getUsers</strong>(): Response&lt;List&lt;User&gt;&gt; = apiService.getUsers()</pre><pre>}</pre><p>Also, for <strong>BASE_URL</strong>, we will add the following in the defaultConfig block in the app&#39;s build.gradle file,</p><pre>buildConfigField &#39;String&#39;, &#39;BASE_URL&#39;, &quot;\&quot;https://5e510330f2c0d300147c034c.mockapi.io/\&quot;&quot;</pre><p>The User data class looks like,</p><pre>data class <strong>User</strong>(<br>    @Json(name = &quot;id&quot;)<br>    val id: Int = 0,<br>    <strong>@Json</strong>(name = &quot;name&quot;)<br>    val name: String = &quot;&quot;,<br>    <strong>@Json</strong>(name = &quot;email&quot;)<br>    val email: String = &quot;&quot;,<br>    <strong>@Json</strong>(name = &quot;avatar&quot;)<br>    val avatar: String = &quot;&quot;<br>)</pre><p>Now, inside the MainRepository, we will update the code like,</p><pre><strong>class</strong> <strong>MainRepository</strong> (<strong>private</strong> <strong>val</strong> <strong>apiHelper</strong>: <strong>ApiHelper</strong>) {</pre><pre>    suspend fun <strong>getUsers</strong>() =  apiHelper.getUsers()</pre><pre>}</pre><p>Now, we are done setting up the data layer, and let’s move to the DI part of the project.</p><p><strong>Step 03.</strong></p><p>Now, we will create a package <strong>di -&gt; module</strong> and inside it, we will create AppModule, ViewModelModule, and RepositoryModule.</p><p>Inside AppModule first, we will create the functions we want to provide as dependencies. We will update the file like,</p><pre><strong>private</strong> fun <strong>provideNetworkHelper</strong>(context: Context) = NetworkHelper(context)</pre><pre><strong>private</strong> fun <strong>provideOkHttpClient</strong>() = <strong>if</strong> (BuildConfig.DEBUG) {<br>    val loggingInterceptor = HttpLoggingInterceptor()<br>    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)<br>    OkHttpClient.Builder()<br>        .addInterceptor(loggingInterceptor)<br>        .build()<br>} <strong>else</strong> OkHttpClient<br>    .Builder()<br>    .build()</pre><pre><strong>private</strong> fun <strong>provideRetrofit</strong>(<br>    okHttpClient: OkHttpClient,<br>    BASE_URL: String<br>): Retrofit =<br>    Retrofit.Builder()<br>        .addConverterFactory(MoshiConverterFactory.create())<br>        .baseUrl(BASE_URL)<br>        .client(okHttpClient)<br>        .build()</pre><pre><strong>private</strong> fun <strong>provideApiService</strong>(retrofit: Retrofit): ApiService = retrofit.create(ApiService::<strong>class</strong>.<strong>java</strong>)</pre><pre><strong>private</strong> <strong>fun</strong> <strong>provideApiHelper</strong>(<strong>apiHelper</strong>: <strong>ApiHelperImpl</strong>): <strong>ApiHelper</strong> = apiHelper</pre><p>Now, to create the file as a supported module for Koin, we will pass the functions as singleton instance to the module. The module is a collection of dependencies we are going to provide to the application. We will create a variable like,</p><pre>val appModule = <strong>module</strong> {<br>   <br>}</pre><p>and inside the module, we will pass the single instance of all the functions we created like,</p><pre>val appModule = <strong>module</strong> {<br>    single { provideOkHttpClient() }<br>    single { provideRetrofit(get(), BuildConfig.BASE_URL) }<br>    single { provideApiService(get()) }<br>    single { provideNetworkHelper(androidContext()) }<br>}</pre><p>Here, to provide the dependency as a singleton instance we use <strong>single{}</strong> and inside it, we will pass the function which will return the dependency as an instance to be used across the app.</p><p>We are using <strong>get()</strong> here to pass the dependency to the constructor. Using get it will only provide the constructor whose instance is already been provided by Koin.</p><p><strong>Step 04.</strong></p><p>Now, let’s update the RepositoryModule. Here, we will provide the MainRepository instance by,</p><pre>val repoModule = <strong>module</strong> {<br>    single {<br>        MainRepository(get())<br>    }<br>}</pre><p>Here, MainRepository requires ApiHelper in the constructor which will be provided by the Koin here.</p><p>And for ApiHelper, we would need the ApiHelperImpl part to be provided which is the extension for ApiHelper. Now, to pass the ApiHelper as a param, we need to provide it as well from the module.</p><p>To provide the ApiHelperImpl in the module, we will update the code and create a single instance like,</p><pre>single&lt;ApiHelper&gt; {<br>    <strong>return@single</strong> ApiHelperImpl(get())<br>}</pre><p>Here, we are providing a type if ApiHelper, and returning ApiHelperImpl and in ApiHelperImpl it takes ApiService as a constructor parameter which we are already providing from provideApiService function.</p><p><strong>Step 05.</strong></p><p>Now, we are going to use a MainViewModel for updating the UI. To provide dependencies in ViewModel we will update the ViewModelModule like,</p><pre>val viewModelModule = <strong>module</strong> {<br>    viewModel {<br>        MainViewModel(get(),get())<br>    }<br>}</pre><p>Here, you can see we are not using single, and in place of that we are using viewModel and inside it, we resolve the dependencies which we are providing from appModule.</p><p>Now, we are done providing the dependencies. Let us start now by injecting the dependencies.</p><p><strong>Step 06.</strong></p><p>Now, let’s start designing our ViewModel. We will update the ViewModel like,</p><pre><strong>class</strong> <strong>MainViewModel</strong>(<br>    <strong>private</strong> <strong>val</strong> <strong>mainRepository</strong>: <strong>MainRepository</strong>,<br>    <strong>private</strong> <strong>val</strong> <strong>networkHelper</strong>: <strong>NetworkHelper</strong><br>) : <strong>ViewModel</strong>() {</pre><pre>    <strong>private</strong> val _users = MutableLiveData&lt;Resource&lt;List&lt;User&gt;&gt;&gt;()<br>    val users: LiveData&lt;Resource&lt;List&lt;User&gt;&gt;&gt;<br>        get() = _users</pre><pre>    init {<br>        fetchUsers()<br>    }</pre><pre>    <strong>private</strong> fun <strong>fetchUsers</strong>() {<br>        viewModelScope.launch {<br>            _users.postValue(Resource.loading(<strong>null</strong>))<br>            <strong>if</strong> (networkHelper.isNetworkConnected()) {<br>                mainRepository.getUsers().let {<br>                    <strong>if</strong> (it.isSuccessful) {<br>                        _users.postValue(Resource.success(it.body()))<br>                    } <strong>else</strong> _users.postValue(Resource.error(it.errorBody().toString(), <strong>null</strong>))<br>                }<br>            } <strong>else</strong> _users.postValue(Resource.error(&quot;No internet connection&quot;, <strong>null</strong>))<br>        }<br>    }<br>}</pre><p>Here, we are passing MainRepository and NetworkHelper in the constructor of the ViewModel.</p><p>Here, we are fetching the users in the init block and inside the viewModelScope, we will check for internet connectivity and if the connectivity is ok then we go through the API call or else we set the value to LiveData with an error. This user LiveData is then observed in the MainActivity to display the items in the recyclerView.</p><p>NetworkHelper looks like,</p><pre><strong>class</strong> <strong>NetworkHelper</strong> <strong>constructor</strong>(<strong>private</strong> <strong>val</strong> <strong>context</strong>: <strong>Context</strong>) {</pre><pre>    fun <strong>isNetworkConnected</strong>(): Boolean {<br>        var result = <strong>false</strong><br>        val connectivityManager =<br>            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager<br>        <strong>if</strong> (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.M) {<br>            val networkCapabilities = connectivityManager.activeNetwork ?: <strong>return</strong> <strong>false</strong><br>            val activeNetwork =<br>                connectivityManager.getNetworkCapabilities(networkCapabilities) ?: <strong>return</strong> <strong>false</strong><br>            result = when {<br>                activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -&gt; <strong>true</strong><br>                activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -&gt; <strong>true</strong><br>                activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -&gt; <strong>true</strong><br>                <strong>else</strong> -&gt; <strong>false</strong><br>            }<br>        } <strong>else</strong> {<br>            connectivityManager.run {<br>                connectivityManager.activeNetworkInfo?.run {<br>                    result = when (type) {<br>                        ConnectivityManager.TYPE_WIFI -&gt; <strong>true</strong><br>                        ConnectivityManager.TYPE_MOBILE -&gt; <strong>true</strong><br>                        ConnectivityManager.TYPE_ETHERNET -&gt; <strong>true</strong><br>                        <strong>else</strong> -&gt; <strong>false</strong><br>                    }</pre><pre>                }<br>            }<br>        }</pre><pre>        <strong>return</strong> result<br>    }<br>}</pre><p><strong>Step 07.</strong></p><p>Now, we need to create the instance of ViewModel in the MainActivity so the values passed in the constructor of the ViewModel are passed to it.</p><p>To pass the instance of ViewModel we will create a variable called mainViewModel like,</p><pre><strong>private</strong> val mainViewModel : MainViewModel by <strong>viewModel</strong>()</pre><p>Here,<strong> by viewModel() </strong>creates the instance for the ViewModel and it will also resolve the dependency required by it.</p><blockquote>If we want to pass any dependency required by any class like Activity we use <strong>by inject() </strong>also known as field injection.</blockquote><p>Now, the MainActivity looks like,</p><pre><strong>class</strong> <strong>MainActivity</strong> : <strong>AppCompatActivity</strong>() {</pre><pre>    <strong>private</strong> val mainViewModel : MainViewModel by <strong>viewModel</strong>()<br>    <strong>private</strong> lateinit var adapter: MainAdapter</pre><pre>    override fun <strong>onCreate</strong>(savedInstanceState: Bundle?) {<br>        <strong>super</strong>.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br>        setupUI()<br>        setupObserver()</pre><pre>    }</pre><pre>    <strong>private</strong> fun <strong>setupUI</strong>() {<br>        recyclerView.layoutManager = LinearLayoutManager(<strong>this</strong>)<br>        adapter = MainAdapter(arrayListOf())<br>        recyclerView.addItemDecoration(<br>            DividerItemDecoration(<br>                recyclerView.context,<br>                (recyclerView.layoutManager as LinearLayoutManager).orientation<br>            )<br>        )<br>        recyclerView.adapter = adapter<br>    }</pre><pre>    <strong>private</strong> fun <strong>setupObserver</strong>() {<br>        mainViewModel.users.observe(<strong>this</strong>, Observer {<br>            when (it.status) {<br>                Status.SUCCESS -&gt; {<br>                    progressBar.visibility = View.GONE<br>                    it.data?.let { users -&gt; renderList(users) }<br>                    recyclerView.visibility = View.VISIBLE<br>                }<br>                Status.LOADING -&gt; {<br>                    progressBar.visibility = View.VISIBLE<br>                    recyclerView.visibility = View.GONE<br>                }<br>                Status.ERROR -&gt; {<br>                    <em>//Handle Error</em><br>                    progressBar.visibility = View.GONE<br>                    Toast.makeText(<strong>this</strong>, it.message, Toast.LENGTH_LONG).show()<br>                }<br>            }<br>        })<br>    }</pre><pre>    <strong>private</strong> fun <strong>renderList</strong>(users: List&lt;User&gt;) {<br>        adapter.addData(users)<br>        adapter.notifyDataSetChanged()<br>    }<br>}</pre><p>and the MainAdapter looks like,</p><pre><strong>class</strong> <strong>MainAdapter</strong>(<br>    <strong>private</strong> <strong>val</strong> <strong>users</strong>: <strong>ArrayList</strong>&lt;<strong>User</strong>&gt;<br>) : <strong>RecyclerView</strong>.<strong>Adapter</strong>&lt;<strong>MainAdapter</strong>.<strong>DataViewHolder</strong>&gt;() {</pre><pre>    <strong>class</strong> <strong>DataViewHolder</strong>(<strong>itemView</strong>: <strong>View</strong>) : <strong>RecyclerView</strong>.<strong>ViewHolder</strong>(<strong>itemView</strong>) {<br>        fun <strong>bind</strong>(user: User) {<br>            itemView.textViewUserName.text = user.name<br>            itemView.textViewUserEmail.text = user.email<br>            Glide.with(itemView.imageViewAvatar.context)<br>                .load(user.avatar)<br>                .into(itemView.imageViewAvatar)<br>        }<br>    }</pre><pre>    override fun <strong>onCreateViewHolder</strong>(parent: ViewGroup, viewType: Int) =<br>        DataViewHolder(<br>            LayoutInflater.from(parent.context).inflate(<br>                R.layout.item_layout, parent,<br>                <strong>false</strong><br>            )<br>        )</pre><pre>    override fun <strong>getItemCount</strong>(): Int = users.size</pre><pre>    override fun <strong>onBindViewHolder</strong>(holder: DataViewHolder, position: Int) =<br>        holder.bind(users[position])</pre><pre>    fun <strong>addData</strong>(list: List&lt;User&gt;) {<br>        users.addAll(list)<br>    }<br>}</pre><p>Now, we are almost done with setting up the project.</p><p><strong>Step 08.</strong></p><p>To run the app successfully, we will add the required permissions like,</p><pre>&lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot; /&gt;<br>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;</pre><p>and to initialize Koin in the project we will update the onCreate() of the application like,</p><pre>override fun <strong>onCreate</strong>() {<br>    <strong>super</strong>.onCreate()<br>    startKoin {<br>        androidContext(<strong>this@App</strong>)<br>        modules(listOf(appModule, repoModule, viewModelModule))<br>    }<br>}</pre><p>Here, we are passing the androidContext to the Koin container which you can see we are using it in the appModule while providing the NetworkHelper class.</p><p>We are also passing all the modules which we created in the di/modules package.</p><p>Now, we are done with the project and if you run the project, you would see the list of users being populated in the recyclerView.</p><p>Sample Project Link Below</p><p><a href="https://drive.google.com/drive/folders/1v3WR7GWfFITYrykXbptx60Cy4eCOJD7K?usp=sharing">https://drive.google.com/drive/folders/1v3WR7GWfFITYrykXbptx60Cy4eCOJD7K?usp=sharing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e63e7575109e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating detekt in the Android Studio]]></title>
            <link>https://medium.com/@nagendran.p/integrating-detekt-in-the-android-studio-442128e971f8?source=rss-333b38c1fc12------2</link>
            <guid isPermaLink="false">https://medium.com/p/442128e971f8</guid>
            <category><![CDATA[detekt]]></category>
            <dc:creator><![CDATA[Nagendran P]]></dc:creator>
            <pubDate>Thu, 14 Oct 2021 12:50:29 GMT</pubDate>
            <atom:updated>2021-10-14T12:50:29.924Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o7XPbIiHaVqv83NbQEhosA.jpeg" /></figure><p><strong>detekt</strong>, a static code analysis tool for Kotlin, helps you do all of this. It comes with a wide range of rule sets. It provides you with options to configure them, as well as the ability to add your own custom rules. So, adding this as a part of your CI steps can prove to be beneficial. CI stands for Continuous Integration, a process of ensuring features and bug fixes are added to an application regularly.</p><p>During the process you’ll learn about:</p><ul><li>detekt and its features.</li><li>Adding detekt to your project.</li><li>Rule sets available in detekt.</li><li>Writing custom rules and processors.</li></ul><h3>Understanding detekt</h3><p>detekt is a static analysis tool for the Kotlin programming language. It tries to improve your codebase by enforcing a set of rules. You can integrate it with your CI to help avoid code smells on your codebase. This is helpful — especially when working with a team of developers.</p><p>detekt has several features that make it a worthwhile addition to your project:</p><ul><li>It offers code-smell analysis for Kotlin projects.</li><li>It’s highly configurable — you can customize it according to your own needs.</li><li>You can suppress findings if you don’t want warnings for everything.</li><li>IDE, SonarQube and GitHub Actions integration.</li><li>You can specify code-smells threshold to break your builds or print warnings.</li><li>You can add code-smell baseline and suppression for legacy projects.</li></ul><h3>Looking at detekt Rule Sets</h3><p>The <strong>DetektSampleApp</strong> already includes a list of the rule sets and their descriptions. Rule sets contain a group of rules that check compliance with your code to improve the code quality. The rules don’t affect the functionality of your app. Here are the common rule sets that exist:</p><ol><li><strong>Comments</strong>: It provides rules that address issues in comments and documentation of the code. It checks header files, comments on private methods and undocumented classes, properties or methods.</li><li><strong>Complexity</strong>: This set contains rules that report complex code. It checks for complex conditions, methods, expressions and classes, as well as reports long methods and long parameter lists.</li><li><strong>Coroutines</strong>: The coroutines rule set analyzes code for potential coroutines problems.</li><li><strong>Empty-Blocks</strong>: It contains rules that report empty blocks of code. Examples include empty catch blocks, empty class blocks, empty function and conditional function blocks.</li><li><strong>Exceptions</strong>: It reports issues related to how code throws and handles exceptions. For example, it has rules if you’re catching generic exceptions among other issues related to handling exceptions.</li><li><strong>Formatting</strong>: This checks if your codebase follows a specific formatting rule set. It allows checking indentation, spacing, semicolons or even import ordering, among other things.</li><li><strong>Naming</strong>: It contains rules which assert the naming of different parts of the codebase. It checks how you name your classes, packages, functions and variables. It reports the errors in case you’re not following the set conventions.</li><li><strong>Performance</strong>: It analyzes code for potential performance problems. Some of the issues it reports include the use of ArrayPrimitives or misuse of forEach loop, for instance.</li><li><strong>Potential-Bugs</strong>: The potential-bugs rule set provides rules that detect potential bugs.</li><li><strong>Style</strong>: The style rule set provides rules that assert the style of the code. This will help keep code in line with the given code style guidelines.</li></ol><p>Each rule set contains a vast number of rules. This tutorial covers the most common rules, but don’t hesitate to check the <a href="https://detekt.github.io/detekt/comments.html">official documentation</a> to learn more about the rules.</p><h3>Adding detekt To Your Project</h3><p>You can easily add detekt to new or existing Kotlin projects. For existing projects, you’ll add some more customization to prevent many errors.</p><h3>Adding to New Projects</h3><p>detekt is available as a Gradle plugin. For new projects, add the plugin via the Gradle files.</p><p>Navigate to the project-level <strong>build.gradle</strong> file. Add the corresponding classpath in the dependencies block:</p><pre>classpath &quot;io.gitlab.arturbosch.detekt:detekt-gradle-plugin:1.18.1&quot;</pre><p>Here, you define the path that Gradle will use to fetch the plugin.</p><p>Next, you need to add the plugin to your project.</p><p>Below the dependencies block add this:</p><pre>apply plugin: &quot;io.gitlab.arturbosch.detekt&quot;</pre><p>With this, you apply the detekt plugin to your project. The final step of adding the plugin is to apply the plugin on the <strong>app</strong> level Gradle file.</p><p>Navigate to the app-level <strong>build.gradle</strong> file. Add this apply line:</p><pre>apply plugin: &quot;io.gitlab.arturbosch.detekt&quot;</pre><p>This enables you to use the plugin in the app module too. With this added, do a Gradle sync. After the sync is complete, your plugin is set and ready to use!</p><p><strong>Note</strong>: detekt requires <strong>Gradle 6.1 or higher</strong>. You can check the supported version from the <a href="https://detekt.github.io/detekt/compatibility.html">compatibility</a> documentation.</p><h3>Running detekt Terminal Command</h3><p>Now that we’re setup, Run the following command to see an initial report on your codebase:</p><pre>./gradlew detekt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iQ_lhbeqgucpMba5.png" /></figure><h3>Setting Up A Config</h3><p>Detekt is highly configurable to meet your team’s requirements. To start tinkering with configuration, generate a config file by running:</p><pre>$ ./gradlew detektGenerateConfig</pre><p>Open the newly generated file in &lt;project-root&gt;/config/detekt/detekt.yml<em> </em>to start playing with various configuration options. Here are a few our team has taken advantage of:</p><ul><li>Setting maxIssues to 0, because why tolerate a codebase that isn’t squeaky clean?</li><li>Enabling UndocumentedPublicClass and UndocumentedPublicFunction to enforce codebase documentation.</li><li>Enabling MissingWhenCase to ensure our when statements are exhaustive.</li><li>Enabling ignoreOverridden on the TooManyFunctions check, so that we don’t have to suppress on Activity and Fragment classes that often require many overrides.</li></ul><p>Open <strong>detekt.yml</strong>. It contains some rule sets and rules properties — for example, the comments section:</p><pre>comments:<br>  active: true<br>  excludes: &quot;**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt&quot;<br>  CommentOverPrivateFunction:<br>    active: false<br>  CommentOverPrivateProperty:<br>    active: false<br>  EndOfSentenceFormat:<br>    active: false<br>    endOfSentenceFormat: ([.?!][ \t\n\r\f&lt;])|([.?!:]$)<br>  UndocumentedPublicClass:<br>    active: false<br>    searchInNestedClass: true<br>    searchInInnerClass: true<br>    searchInInnerObject: true<br>    searchInInnerInterface: true<br>  UndocumentedPublicFunction:<br>    active: false</pre><p>As you can see, in order to enable or disable a given rule, you just have to set the boolean value active: true/false.</p><h3>If You’re Adding To An Existing Project</h3><p>The correct time to setup static code checks is always “now”, but what if your project is already in production and you have a couple hundred pre existing detekt warnings? Detekt allows you to specify a baseline file of warnings that will be ignored, so only new warnings cause failures. Here’s how to set it up:</p><p>First, run the following command to generate a baseline file:</p><pre>$ ./gradlew detektBaseline</pre><p>Then, add the following detekt config in app/build.gradle:</p><pre>detekt {<br>    // other detekt configuration goes here<br>    baseline = file(“$rootDir/detekt-baseline.xml”)<br>}</pre><p>Now, when running ./gradlew detekt, warnings listed in the baseline file will be ignored! You can update the baseline file at any time by re-running ./gradlew detektBaseline.</p><h3>Suppressing Issues</h3><p>To prevent detekt from displaying an issue on a specific method, you can use the @Suppress annotation.</p><pre>To see this in action, add this new method below potentialBugs():</pre><pre>@Suppress(&quot;EmptyFunctionBlock&quot;)<br>private fun sampleEmptyFuntion() {<br>}</pre><h3>Writing Custom detekt Rules</h3><p>As mentioned earlier, detekt allows you to extend its functionality by adding your own rules. Recently, the Kotlin Android Extensions plugin was <a href="https://android-developers.googleblog.com/2020/11/the-future-of-kotlin-android-extensions.html">deprecated</a>. This means using Kotlin Synthetic is no longer recommended. Before the introduction of <strong>ViewBinding</strong>, this was the go-to way of accessing views in Android apps. This deprecation affects so many projects. Using detekt, you can write a specific rule to check it and fail your build if there is a synthetic import.</p><p><strong>Note</strong>: You shouldn’t be using the Kotlin Android Extensions in your projects anymore. It’s used here to demonstrate how you can create custom detekt rules.</p><p>First, move to the <strong>customRules</strong> module and add these dependencies to <strong>build.gradle</strong>:</p><pre>// 1<br>compileOnly &quot;io.gitlab.arturbosch.detekt:detekt-api:1.17.1&quot;<br>// 2<br>testImplementation &quot;io.gitlab.arturbosch.detekt:detekt-api:1.17.1&quot;<br>testImplementation &quot;io.gitlab.arturbosch.detekt:detekt-test:1.17.1&quot;<br>testImplementation &quot;org.assertj:assertj-core:3.19.0&quot;<br>testImplementation &#39;junit:junit:4.13.2&#39;</pre><p>This code:</p><ol><li>Adds the detekt API dependency. You need this for writing the custom rules.</li><li>Adds test dependencies. To test your rules you need detekt-test. It also requires assertj-core as a dependency.</li></ol><p>Do a Gradle sync to add this dependencies. Next, inside the com.raywenderlich.android.customrules.rules package in the <strong>customRules</strong> module, add a new file. Name it <strong>NoSyntheticImportRule.kt</strong> and add the following:</p><pre>package com.raywenderlich.android.customrules.rules</pre><pre>import io.gitlab.arturbosch.detekt.api.*<br>import org.jetbrains.kotlin.psi.KtImportDirective<br>//1<br>class NoSyntheticImportRule : Rule() {<br>  //2<br>  override val issue = Issue(&quot;NoSyntheticImport&quot;,<br>      Severity.Maintainability, &quot;Don’t import Kotlin Synthetics &quot;<br>      + &quot;as it is already deprecated.&quot;, Debt.TWENTY_MINS)<br>  //3<br>  override fun visitImportDirective(<br>      importDirective: KtImportDirective<br>  ) {<br>    val import = importDirective.importPath?.pathStr<br>    if (import?.contains(&quot;kotlinx.android.synthetic&quot;) == true) {<br>      report(CodeSmell(issue, Entity.from(importDirective),<br>          &quot;Importing &#39;$import&#39; which is a Kotlin Synthetics import.&quot;))<br>    }<br>  }<br>}</pre><p>Here’s what’s happening:</p><ol><li>NoSyntheticImportRule extends Rule from the detekt API.</li><li>This is a method from Rule that defines your issue. In this case, you create an issue named <strong>NoSyntheticImport</strong>. You specify the debt for the issue, the severity of the issue and the message for detekt to show. The debt represents the time you need to fix the issue.</li><li>This method checks imports in your files and classes. Inside here you have a check to see if any of the import contains Kotlin synthetics. If it does, you report the code smell with a message.</li></ol><h3>Adding Your Own Rule to detekt</h3><p>With your rule class complete, your need to create a RuleSetProvider. This class lets detekt know about your rule. You create one by implementing RuleSetProvider interface.</p><p>On the same package as the file above, create another new file. Name it <strong>CustomRuleSetProvider.kt</strong> and add the following code:</p><pre>package com.raywenderlich.android.customrules.rules</pre><pre>import io.gitlab.arturbosch.detekt.api.Config<br>import io.gitlab.arturbosch.detekt.api.RuleSet<br>import io.gitlab.arturbosch.detekt.api.RuleSetProvider</pre><pre>class CustomRuleSetProvider : RuleSetProvider {<br>  override val ruleSetId: String = &quot;synthetic-import-rule&quot;<br>  override fun instance(config: Config): RuleSet = RuleSet(ruleSetId, listOf(NoSyntheticImportRule()))<br>}</pre><p>Implementing this interface provides detekt with a rule set containing your new rule. You also provide an id for your rule set. You can group as many rules as you&#39;d like in this rule set if you have other related rules.</p><p>Next, you need to let detekt know about your <strong>CustomRuleSetProvider</strong>. Navigate to the <strong>customRules</strong> module. Open <strong>src/main/resources/META-INF/services</strong>, and you’ll find <strong>io.gitlab.arturbosch.detekt.api.RuleSetProvider</strong>. Inside this file, add:</p><pre>com.raywenderlich.android.customrules.rules.CustomRuleSetProvider</pre><p>Here, you add the full qualified name for your <strong>CustomRuleSetProvider</strong>. detekt can now find the class, instantiate it and retrieve your rule set. This file notifies detekt about your CustomRuleSetProvider.</p><p>Woohoo! You’ve created your first custom rule. It’s time to test if your rule is working.</p><h3>Testing Your Custom Rule</h3><p>Inside the <strong>test</strong> directory in the <strong>customRules</strong> module, add a new Kotlin file to the package and name it <strong>NoSyntheticImportTest.kt</strong>. Add the following code:</p><pre>package com.raywenderlich.android.customrules.rules</pre><pre>import io.gitlab.arturbosch.detekt.test.lint<br>import org.assertj.core.api.Assertions.assertThat<br>import org.junit.Test</pre><pre>class NoSyntheticImportTest {<br>  @Test<br>  fun noSyntheticImports() {<br>    // 1<br>    val findings = NoSyntheticImportRule().lint(&quot;&quot;&quot;<br>       import a.b.c<br>       import kotlinx.android.synthetic.main.activity_synthetic_rule.*<br>       &quot;&quot;&quot;.trimIndent())<br>    // 2<br>    assertThat(findings).hasSize(1)<br>    assertThat(findings[0].message).isEqualTo(&quot;Importing &quot; +<br>        &quot;&#39;kotlinx.android.synthetic.main.activity_synthetic_rule.*&#39; which is a Kotlin Synthetics import.&quot;)<br>  }<br>}</pre><p>In the code above:</p><ol><li>You use lint() extension function, which executes the checks and returns the results. Inside the functions you&#39;ve added two imports. One is compliant and the other one is non-compliant.</li><li>Using the results from above, you do an assertion to check if the findings has a size of one. This is because you have one non-compliant import. You also do an assertion to check for message in your findings.</li></ol><p>Click the <strong>Run</strong> icon on the left side of noSyntheticImports(). You&#39;ll see your test passes as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*J2cQ03LdGyoq4JE-.png" /></figure><p>You can see your test for the custom rule passes. This means you can use your rule in a real project. You’ll learn how to do that next.</p><p><strong>Note</strong>: Don’t worry about the WARNING: An illegal reflective access operation has occurred message. It is relative to this test running on itself. This won&#39;t happen when using this rule for the <strong>app</strong> module.</p><h3>Using the Custom Rule in Your Project</h3><p>To use this new rule in your project, you’ll need to apply the customRules module in your <strong>app</strong> module. Navigate to the app-level <strong>build.gradle</strong> file and add the following to the dependencies section:</p><pre>detekt &quot;io.gitlab.arturbosch.detekt:detekt-cli:1.17.1&quot;<br>detekt project(&quot;:customRules&quot;)</pre><p>The first line is relative to detekt-cli dependency. detekt requires it to run your custom rule. The second line tells detekt to use your module as a dependency in order to be able to use your custom rule.</p><p>Have a look at the <strong>SyntheticRuleActivity</strong> class. As you can see, it has Kotlin Synthetic Import. You’ll use this class to test if the rule works.</p><pre>import kotlinx.android.synthetic.main.activity_synthetic_rule.*</pre><p>Last, you need to activate your rule set and include your rule in the configuration file. To do this, add the following code to <strong>detekt.yml</strong> just above the comments section:</p><pre>synthetic-import-rule:<br>  active: true<br>  NoSyntheticImportRule:<br>    active: true</pre><p>Run ./gradlew detekt on your terminal. You&#39;ll see these results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*jLl_LnBXbiP79rQQ.png" /></figure><p>detekt now reports an issue under synthetic-import-rule. It shows a debt of 20 minutes and points to the class that has the import.</p><p>Congratulations! You’ve made your first custom rule.</p><p>Sample Project Link = <a href="https://github.com/nagusmart/detekt_sample_app">https://github.com/nagusmart/detekt_sample_app</a></p><p>Thank You</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=442128e971f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>