saveourtool / diktat

Strict coding standard for Kotlin and a custom set of rules for detecting code smells, code style issues and bugs
https://diktat.saveourtool.com
MIT License
521 stars 39 forks source link

`VARIABLE_NAME_INCORRECT_FORMAT` false positive when a property has a backing field #1711

Closed 0x6675636b796f75676974687562 closed 9 months ago

0x6675636b796f75676974687562 commented 1 year ago

Describe the bug

Consider this idiomatic example taken directly from https://kotlinlang.org:

package com.example

class MutableTableContainer {
    private var _table: Map<String, Int>? = null

    val table: Map<String, Int>
        get() {
            if (_table == null) {
                _table = hashMapOf()
            }
            return _table ?: throw AssertionError("Set to null by another thread")
        }
}

Diktat 1.2.5 warns:

MutableTableContainer.kt:4:17: [VARIABLE_NAME_INCORRECT_FORMAT] variable name should be in lowerCamelCase and should contain only latin (ASCII) letters or numbers and should start from lower letter: _table (diktat-ruleset:identifier-naming)

Probably we should make an exception for backing properties whenever there's an explicit backing field with the corresponding name (xyz_xyz) and of the same type.

Requirements:

  1. the backing field should be private (or have a lower visibility than that of the property);
  2. the backing field should have a matching name (xyz_xyz);
  3. the backing field should have the same type as the property (either convert both types to a simple name, or resolve to a FQN before you compare; nullable subtypes should be permitted: Map<String, Int>Map<String, Int>?);
  4. the backing field should have no accessors/modifiers of its own;
  5. the property should have at least an accessor, or a modifier, or both.

Related:

Expected behavior

No warning should have been reported.

Observed behavior

A warning was reported.

Steps to Reproduce

Check the above code example with Diktat.

Environment information