Marty Andrews

artful code

Sunday, January 7, 2007

Fixing a static method code smell

Static methods are a clue that a piece of code might not be conforming well to object oriented design principles. Its probably not as well designed as it could be, or as reusable as it could be. Most of all, its probably not as testable as it could be. The contents of the method often belong on one of the objects being worked on, and sometimes belong in a whole new object unto themselves.

The first clue for how to fix it is to look at the parameters being worked on in the method. If it is, then you can convert the method to an instance method on that object. IntelliJ IDEA has a refactoring option called "Convert To Instance Method...", which will ask you which parameter to move the method to. If you're not using IntelliJ IDEA, you can move the method to the appropriate Object, delete the parameter, and use this instead.

public class AccountFunctions {public static void withdraw(Long amountInCents, Account account) {// ...}}


public class Account {public void withdraw(Long amountInCents) {// ...}}

The second clue for how to fix it is to look at the local variables being used in the method. It's possible that the contents of the method belongs on one of them instead of one of the parameters. Maybe a singleton object is being accessed in the method for example. In this case, the solution is similar to the first option, except that the parameters all still exist.

public class CartFunctions {public static void addItemToCart(Long itemId) {Cart cart = Cart.getInstance();List items = cart.getItems();items.add(itemId);}}


public class Cart {public void addItem(Long itemId) {// ...}}

The third clue for how to fix it is to create a completely new class just for the static method. The parameters on the method become instance variables, and a constructor should be created that takes them as parameters. The method itself becomes an instance method on that class that uses the instance variables instead of having parameters to it.

public class DatabaseFunctions {public static String buildSelectStatement(String tableName, Collection columns,Collection conditions, Collection orderBys) {// ...}}


public class Query {private String _tableName;private Collection _columns;private Collection _conditions;private Collection _orderBys;public Query(String tableName, Collection columns, Collection conditions, Collection orderBys) {}public String toSql() {// ...}}

1 comment: