Jim McMaster’s Post

View profile for Jim McMaster, graphic

Java Software Engineer

The next code smell I want to highlight is one of my personal pet peeves, Primitive Obsession. This means using a primitive or String for a value just because it sort-of fits, rather than using a well-designed object. Yes, there is effort in creating the object, but that effort pays off many times over. What do I mean? How about using a float to represent money just because it has a decimal point. That *always* causes problems. You always have to deal with imprecision and rounding errors. You need a Money class that can store exact values, handle multiple currencies and perform conversions. Another horrible idea is to use a String (or even worse, an int) to hold a phone number. You often need to parse out a country code or an exchange by splitting the String or dividing the int. You can express these concepts directly in a TelephoneNumber class. The same goes for using String to represent an address. Use an Address object to hold a name (which should also be an object), a house number, street name, apartment number, city, province. Postal code and country. The same goes for dates, times, ranges and other types. Of course, Java has already defined classes for those. Any time you have a value in a primitive and keep having to split it apart to use it, you really need to define an object.The appropriate refactoring is “Replace Data Value With Object”. Sometimes, we use a primitive to represent a type code, which can also cause problems. You should use an enum or a class. If you don’t depend on the type code to affect behavior of the system, use “Replace Type Code With Class.” If you do use it for branching, then you can consider “Replace Type Code With Subclasses”, or “Replace Type Code With State/Strategy”. Another smell is storing parts of a value in an Array, then having to pick out pieces by knowing the indices of those pieces. If you find yourself doing this, you can use “Replace Array With Object”. Sometimes, you might have pieces of a value in individual primitive fields and parameters. In this case, you can put them together with “Extract Class” or “Introduce Parameter Object.” Shoe-horning complex values into a primitive is always a bad idea. You may think it is “easier” or “less work”, but it always comes back to bite you. You can find descriptions of the refactorings at https://lnkd.in/gdJjNQcF

Encapsulate Collection

Encapsulate Collection

refactoring.com

To view or add a comment, sign in

Explore topics