Kotlin Code Smell 24 - Tackling Too Many Attributes

Kotlin Code Smell 24 - Tackling Too Many Attributes

Trimming the Attribute Fat

Problem

  • Low Cohesion

  • Coupling

  • Maintainability

  • Readability

Solution

  1. Identify methods related to specific groups of attributes.

  2. Cluster these methods together.

  3. Break down the original class into smaller, more focused objects based on these clusters.

  4. Replace existing references with new objects.

Examples

- DTOs

- Denormalized table rows

Sample Code

Wrong

class ExcelSheet (
          val filename: String,
          val fileEncoding: String,
          val documentOwner: String,
          val documentReadPassword: String,
          val documentWritePassword: String,
          val creationTime: LocalDateTime,
          val updateTime: LocalDateTime,
          val revisionVersion: String,
          val revisionOwner: String,
          val previousVersions: List<String>,
          val documentLanguage: String,
          val cells: List<Cell>,
          val cellNames: List<String>,
          val geometricShapes: List<Shape>,
)

Right

class ExcelSheet (
          val fileProperties: FileProperties,
          val securityProperties: SecurityProperties,
          val datingProperties: DocumentDatingProperties,
          val revisionProperties: RevisionProperties,
          val languageProperties: LanguageProperties,
          val content: DocumentContent,

)

// The object now has fewer attributes, resulting in improved
// testability.
// The new objects are more cohesive, more testable, and lead to fewer
// conflicts, making them more reusable. Both FileProperties and
// SecurityProperties can be reused for other documents. Additionally,
// rules and preconditions previously found in fileProperties will be
// relocated to this object, resulting in a cleaner ExcelSheet
// constructor.

Conclusion

Bloated objects know too much and are very difficult to change due to cohesion.

Developers change these objects a lot, so they bring merge conflicts and are a common problem source.

Credits

Did you find this article valuable?

Support Yonatan Karp-Rudin by becoming a sponsor. Any amount is appreciated!