6.3. Need Determines Class

If a class contains all the data required by a method, that method belongs in that class. Another class should not extract data from a class, manipulate it, and then put it back into that class.

Conversely, if a method does not require any data from an object, the method is probably not needed as a member of the class. It is a candidate for a helper class or a general library class. With Sam's system, we might need to display the title of a CDRelease in multiple lines. We might leave the task of breaking up the lines to the display widget, or we might do it ourselves if we want more control over how the title appears. Suppose that CDRelease had a get_title_by_lines( ) method to return the title in separate lines:

    class CDRelease
        {
        String title;
        static int CHARS_PER_LINE = 60;
        String [] get_title_by_lines( )
            {
            return break_into_lines(title, CHARS_PER_LINE);
            }
        String [] break_into_lines(String text_to_break_up, int chars_per_line)
            {
            // Break text into separate strings
            }
        }

The break_into_lines( ) method does not need to be part of the class. It does not manipulate any attributes directly. However, it looks like a useful tool for other classes. So the method seems appropriate for a separate utility class. For example:

    class StringHelper
        {
        static String [] break_into_lines(String text_to_break_up, int chars_per_
        line)
            {
            // Break into separate strings
            }
        }

With this method placed in StringHelper, we would write the get_title_by_lines( ) method as follows: ...

Get Prefactoring now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.