Sunday, April 18, 2010

Refactoring challenge: finding a better name

A common code smell is that a name containing the word "And". For example, consider class below:
	private final static class ObjectAndGetSetter
{
private final IGetAndSet getAndSetter;
private final Object value;
...
//getters and setters
}
public static interface IGetAndSet
{
public Method getGetter();
public Method getSetter();
}

Both the IGetAndSet and ObjectAndGetSetter names contain the word "And". Why is it a bad thing? Because there are multiple concepts in the name (e.g., the concepts of getter and setter in IGetAndSet), indicating that the single concept has not been spelled out yet. For this case, for IGetAndSet, I think the single concept is "property". For ObjectAndGetSetter, the single concept is "property of a given instance". So, I'd change the code as:
	private final static class InstanceProperty
{
private final IProperty property;
private final Object instance;
...
//getters and setters
}
public static interface IProperty
{
public Method getGetter();
public Method getSetter();
}

Now the challenge: in Spring MVC there is a ModelAndView class:
public class ModelAndView {
/** View instance or view name String */
private Object view;
/** Model Map */
private ModelMap model;
...
}

How do you rename it? Or is it good enough? Post your suggestions as comments.

2 comments:

  1. Ah yes, the whole "And" thing.
    Lets be realistic, a lot of the time the ROI on separating out some of the most basic concepts just because they are lumped together (yet directly relate to each other) is just not worth it.
    There is becoming far too much theoretical non-sense for the real world.

    ReplyDelete
  2. Hi Steven,
    I agree with you that we shouldn't spend a lot of time beautifying our code. In general, my advice is not to think about problems without writing code for more than 5-10 minutes. A much better approach is to discuss with team members to try to tackle the problem. Even then, if no suitable solution is found, the team should just move forward.
    In addition, note that a programmer's ability to write beautiful code is not static: the more exercises he does and the more he sees how others do it, the better he will be.

    ReplyDelete