DEV Community

Yonatan Karp-Rudin
Yonatan Karp-Rudin

Posted on • Originally published at yonatankarp.com on

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>,
)

Enter fullscreen mode Exit fullscreen mode

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.

Enter fullscreen mode Exit fullscreen mode

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.


I hope you enjoyed this journey and learned something new. If you want to stay updated with my latest thoughts and ideas, feel free to register for my newsletter. You can also find me on LinkedIn or Twitter. Let's stay connected and keep the conversation going!


Credits

Top comments (2)

Collapse
 
isthemartin profile image
Martin Morales

Sounds good, just if we need to change a value on a property in a far level from base class could be a problem (data classes nested), like this: excelSheet.copy(fileProperties = FileProperties.copy(path = fileProperties.path)), I'm seeing this code in MVI patterns in updater class

Collapse
 
yonatankarp profile image
Yonatan Karp-Rudin

In such case you can use some libraries like Arrow that giving you exactly this possibility with the usage of lens - you can find more info about it here: arrow-kt.io/learn/immutable-data/l...