Skip to Main Content
Prefactoring
book

Prefactoring

by Ken Pugh
September 2005
Intermediate to advanced content levelIntermediate to advanced
240 pages
6h 28m
English
O'Reilly Media, Inc.
Content preview from Prefactoring

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: ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Understanding Unittest.Mock

Understanding Unittest.Mock

Mario Corchero
Java™ Performance

Java™ Performance

Charlie Hunt, Binu John

Publisher Resources

ISBN: 0596008740Supplemental ContentCatalog PageErrata