Skip to main content

Command Palette

Search for a command to run...

Kotlin Code Smell 24 - Tackling Too Many Attributes

Trimming the Attribute Fat

Updated
2 min read
Kotlin Code Smell 24 - Tackling Too Many Attributes

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

Kotlin Code Smells

Part 13 of 36

In this series, we will see several symptoms and situations that make us doubt the quality of our development. We will present possible solutions. Most are just clues. They are no hard rules.

Up next

Kotlin Code Smell 23 - Singletons

One Too Many: The Slippery Slope of Singleton Patterns

More from this blog

Yonatan Karp-Rudin | kotlin for backend developer skills | java for backend developer skills | SpringBoot | Tutorials

57 posts

Experienced Senior Software Engineer passionate about functional programming & Kotlin. Excels in app development, optimization, and team collaboration. Let's create something amazing!