One of the goals in programming is to break down a complex problem into many individual pieces of code.  Not all of those pieces of code need to be exposed to other parts of the program, just the important bits.  A Java Class normally encapsulates all inner logic, exposing just the methods it needs to.

Callers do not need to know the inner workings of a class to call a method on it, and generally should not need to know.

Exception: do not encapsulate the trivial.  For example, create a StringUtil class for all String manipulation activities rather than a separate StringReverser class and a separate StringCamelCase class.

For example, imagine a case where messages need to be sent to an external Twitter API.  A junior programmer might cut and paste the same Twitter client access code in the many places where it was needed, polluting the important application code with things like message timeouts, error handling, etc.    

An experienced developer would create a TwitterClientService that knows all about communicating with Twitter:

/**
 * The class for sending messages to Twitter
  
 * It contains any shared logic that specific runner
 * subclasses will reuse. This class should contain
 * no specific information related to a kind of runner.
 */
public class TwitterClientService
{
    /**
     * Sends a twitter message to the currently configured account,
     * fixing lengths if too long to send.
     * @param message The message to send  
     * @throws TwitterException on all errors. Usually no need to catch  
     *         as the framework will deal with it.
     */
    public void sendTwitterMessage(String message)  
        throws TwitterException
    {
        :
    }
}
blog comments powered by Disqus