Primitive Obsession Code Smell: How To Spot and Fix

Primitive obsession is slang for “you use too many simple types like numbers and strings to store data”. With classes, it’s harder because you must think more intently about what you want.

//This is easy
string ip = "8.8.8.8";
int numberOfRequests = 4;
int isTCP = true;


//This is also easy
public class NetworkUtility {
   private string ip;
   private int numberOfRequests;
   private bool isTCP;
}

It’s very easy to just start adding primitives to our code and things can get out of control quick.

The way to compact this is to simply turn things into objects:

public class NetworkSettings {
   private string ip;
   private int numberOfRequests;
   private bool isTCP;
}

public class NetworkUtility {
   //This is now one line instead of three
   private NetworkSettings settings;
}

Primitive obsession can also be found in function parameters.

sendNetworkRequest(string ip, int numberOfRequests, bool isTCP);

The way to refactor is Introduce Parameter Object, which is a fancy way of saying pass an object instead.

sendNetworkRequest(NetworkSettings settings);

Another way to refactor is Preserve Whole Object:

We may also just pass entire objects so that our params don’t get out of control.

//Bad
bool sendRequest = network.sendRequest(ip, numberofRequest, isTCP);

//Good
NetworkSettings settings = new NetworkSettings { 
     ip = "8.8.8.8";
     numberOfRequest = 3;
     isTCP = true
};
 bool sendRequest = network.sendRequest(networkSettings);

We could even take this code further by replacing “type codes”. Type codes are “dangerous” abstractions because they are special codes that only you understand.

For example:

public class NetworkSetting {
    private int SUCCESS;
    private int FAIL;
}

The type codes we describe are essentially meaningless. We might have a hint at what FAIL means, but it is very unclear.

That is why replacing Type Code with Class, Subclass, and/or State is our friend:

public class StatusCode {
   private int SUCCESS = 200;
   private int FAIL = 404;
}

Leave a Reply

Your email address will not be published. Required fields are marked *