So I have this problem: in order to structure my code hierarchically, for every new tiny thing, I create a separate sub-folder, file, class … and in it one 10-line function. It is an anti-pattern.
Lately I have been trying to err on the opposite side. That is, when I need something new, instead of dreaming up grand hierarchies, I just type the code somewhere inside the existing classes.
This is beginning to look like another anti-pattern, and I wander which is the lesser evil.
So the pattern is the following: write everything here and now, and, when the need arises, refactor the code out to a separate class. Kind of refactorable God.
Am I using this as an excuse to write God classes? Or is there a pattern/worklfow, similar to this one, that I can adopt? What are the indicators that things are going well/terrible?
5
I don’t remember the chapter, but the author of the working with legacy code
but I think the book suggest the following workflow :
-
make sure you have tests. If you can’t test your code without
modifying it, only perform the most basic/easy modifications needed. -
code a test for the new functionality
-
code the functionality directly where you want the work to happen and make the test pass
-
refactor to remove duplication and make the code SOLID compliant.
Even without test, I tend to follow a similar pattern: first get the thing to work in the simplest and easiest way, then immediately refactor until you are satisfied with the code organization. If you wait, you (or your colleague) will pay a higher price of trying to understand messy code.
The fact that you first solve the problem in the most simple and straightforward way helps you to avoid over-engineering the solution. Focusing first on correctness then on readability/architecture really helps you to be productive.
When creating a new method, first think:
-
Does this method correspond to a property or a behavior of an object, or:
-
Is it something completely new?
In the first case, you’ll rather put it in the corresponding class. In the second case, indeed, you’ll create a new class.
The problem with the first case is that sometimes, you’ll end up with a class too big. This is a hint that the class should be refactored into multiple smaller classes. What is big or not depends on the circumstances. For example:
Rectangle
{
int x;
int y;
int width;
int height;
}
can easily be refactored into:
Rectangle
{
Point position;
Size size;
}
Point
{
int x;
int y;
}
Size
{
int width;
int height;
}
3