5 Ways to Clean (Your Java Class)
My favorite analogies to writing code have to do urban planning and personal organization — two of my most favorite subjects. You may remember my post about Marie Kondo. And I’m constantly lured by blog posts that give me tips on how to clean my bathroom mirror using homemade cleaners. This is not one of those posts.
Yet, when reading about classes in Clean Code, I was tickled by this question: “ Do you want your tools organized into toolboxes with many small drawers each containing well-defined and well-labeled components? Or do you want a few drawers that you just toss everything into?” As in, do you want your code to exist in small classes or do you want to have a few classes that house everything? What a great way to think about classes!
Here are some guidelines for writing classes (some of which you’ve seen before, but serve as a good reminder):
- Each class should be small and have a single responsibility. The Single Responsibility Principle (SRP) states that a class should have and only one reason to change. The rule of thumb is that you should be able to write a brief description of the class in about 25 words. For my programs, I try to outline the structure in the README and describe methods.
- Each class should have a small number of instance variables.
- Each class should be cohesive — methods and variables of the class are co-dependent. You should note how many methods actually use class variables.
- Break large functions into smaller ones; break large classes into smaller well-named ones. This one goes without saying. If your function is deeply indented, you know you should stop. Refactoring inevitably leads to longer programs, since you’re using more descriptive names, function/class declarations, and whitespace and other formatting techniques for readability.
- Classes should depend upon abstractions, not concretions — per Dependency Inversion Principle (DIP). There are concrete classes (that have implementation details) and abstract classes (which only deal with concepts). Since code will undoubtedly change, interfaces and abstract classes can help isolate the impact of changing those details.