One of the goals in programming is to break down a complex problem into many individual pieces of code.  If some code is repeated many times, it may be a candidate for separation into a helper method.

A Java method can encapsulate a complex or wordy task, hiding away inner logic.  Access to the method is through the method signature only.

Callers do not need to know the inner workings of the method to call it (and should not need to know).

Exception: do not encapsulate the trivial.  For example, don't create a method with just one line of code in it unless you need to add validation or other common code to the method later.

In the following example a developer created an extra get() method that created no new functionality and saved zero lines of code:

:
public Media getMedia(long id ) throws DataAccessException
{
    return (Media)this.get(Media.class, id);
}

public User getUser(long id) throws DataAccessException
{
    return (User)this.get(User.class, id);
}

private BaseModel get(Class c, long id) throws DataAccessException
{
    return (BaseModel)getHibernateTemplate().get(c, id);
}
:

The code would have been much simpler as follows:

:
public Media getMedia(long id ) throws DataAccessException
{
    return (Media)getHibernateTemplate().get(Media.class, id);
}

public User getUser(long id) throws DataAccessException
{
    return (User)getHibernateTemplate().get(User.class, id);
}
:

Perhaps if developers regularly got the getHibernateTemplate() method call wrong, a tech lead might create a separate get() method but these kind of cut-and-paste code-by-example functions are usually coded correctly if the first example is coded correctly.

blog comments powered by Disqus