Today’s code smell is temporary fields. Like with all code smells, sometimes these aren’t a problem at all. For example, it’s pretty normal to have a user object with a bunch of optional fields. Sometimes you have users who just start out with a username and a password and fill in their profiles later and sometimes you have fields for stuff like social media accounts that only some users will ever fill in, but sometimes fields that only sometimes have a value are a problem.
One of the ways people try to fix the problem of a long parameter list is to make some of those parameters into fields and then set them later if they need to. Unfortunately that’s not really any better because it just hides some of the confusion under the rug instead of actually getting rid of it. Instead of it at least being obvious you have too many parameters, now you have a bunch of fields that may or may not get used depending on what the object is up to and you have to go hunting to figure out what’s going on.
Since professional programmers read code much more often than we write it, it’s a huge waste of time to have to go on an exploratory mission every time you need to understand that code again. If you do end up needing to update that code, best of luck figuring out which fields are important and whether your refactor / bug fix / new feature broke anything.
I had a heck of a time finding a code example for this code smell but fortunately so did Mark Seemann, who was frustrated enough by that to write not just an example of the smell but of how to refactor it too.
If you find this smell in your code, what do you do about it?
Pulling out the temporary bits into their own object and just using that is a good option (if that works for your code, of course). Isolating the fiddly bit makes the rest of the object cleaner and makes it clearer what the fiddly bit is up to. You can also add a null object (a special object where you put whatever defaults you use when one of your temporary fields is null). That way your normal processing code can be clean and simple instead of littered with null checks. Sometimes that just makes things more complicated, so it’s a bit of a judgement call.
If you’re having trouble figuring out what an object even does because most of its fields are null most of the time, see if some refactoring helps. You can always put it back the way it was if it’s worse afterwards :)