A complicated method can be made more readable by making it a composition of smaller methods:
void add(Object element) { if (!readOnly) { int newSize = size + 1; if (newSize > elements.length) { Object[] newElements = new Object[elements.length + 10]; for (int i = 0; i < size; i++) { newElements[i] = elements[i]; } elements = newElements; } elements[size++] = element; } }
void add(Object element) { if (readOnly) return; if (atCapacity()) grow(); addElement(element); }
A method should not have too many nested blocks of code. To make it more comprehensible extract private methods, so that it will be a composition of a few shorter, lower level methods. Improved method looks like a cooking recipe and can be understood at a glance.
J. Kerievsky, Refactoring to Patterns
Discuss Downvote Upvote Votes: 0