Code Smell 122 - Primitive Obsession
Objects are there for the picking. Even the smallest ones.
2 min read
TL;DR: Use small objects instead of primitive ones.
Small Objects Missing
Fail Fast principle violation.
Subset violations: Emails are a subset of strings, Valid Ages are a subset of Real, Ports are a subset of Integers, etc.
We spread Logic and Behavior in many places.
Create Small Objects
Build missing abstractions using MAPPER
We are very lazy to create small objects.
We are also lazy to separate What and How
We like very much to understand the internals of how things work.
We need to start thinking in a whitebox way and looking at the protocol and behavior of small components.
//Samples borrowed with permission from //https://towardsdev.com/why-a-host-is-not-a-string-and-a-port-is-not-an-integer-595c182d817c var port = 8080; var in = open("example.org", port); var uri = urifromPort("example.org", port); var address = addressFromPort("example.org", port); var path = pathFromPort("example.org", port);
//Samples borrowed with permission from //https://towardsdev.com/why-a-host-is-not-a-string-and-a-port-is-not-an-integer-595c182d817c const server = Port.parse(this, "www.kivakit.org:8080"); //Port is a smallobject with responsibilities and protocol let in = port.open(this); const uri = port.asUri(this); const address = port.asInetSocketAddress(); const path = port.path(this, "/index.html");
We can automate checks on constructors for small objects missing opportunities.
- Primitive Obsession
We need to transform our strings, numbers, and arrays into small objects
Primitive Obsession — A Code Smell that Hurts People the Most
Photo by K. Mitch Hodge on Unsplash
Iteration allows us to progressively approach some goal. We can discard the steps that take us further away and prefer the steps that move us nearer. This is in essence how evolution works. It is also at the heart of how modern machine learning (ML) works.
This article is part of the CodeSmell Series.