I use in the project Spring and Hibernate, different ServiceDAO, accessing data, already have about 30 methods, I wondered if it is worth breaking them for the sake of increasing productivity, or the number of methods in a class does not affect its download speed?

  • 3
    I do not think that affects. - Anton Sorokin

2 answers 2

Does not affect.

The speed is influenced by the code in the methods, not by the number of them in the class, since the code is executed multiple times, and the classes are loaded once. The download speed of the bytecode is so high that any differences will be imperceptible. Winning, even insignificant, will not be in any case because instead of one class with 30 methods, three with 10 each will be loaded.

A more general idea: if you decide to seriously engage in optimization, the first thing you need to measure the speed of code execution, find the slowest places and focus on them. Hardly the slowest part will be the work of the class loader.

Method calls, class loading, JIT compilation, as a rule, work quickly. Querying a database or accessing services will take thousands of times longer. Running the garbage collector and loading the entity from the cache are hundreds of times slower. You can save on nanoseconds, but this makes little sense when seconds are wasted.

is it worth breaking them for the sake of increased productivity

Not worth it. It is worth breaking classes for organizing logic and increasing readability.

PS “Premature optimization is the root of all evil.” Donald Knuth

  • And if all methods like getUserByLogin (), getUsersByRating (), getUsersByTags (). On what basis they can be broken, I do not quite understand - Eltsov Danil
  • @EltsovDanil To be honest, it is difficult to give some practical advice. Look where these methods are applied, it is possible to separate them with respect to business logic. And yes, not the fact that the class needs to be broken. - default locale
  • one
    @EltsovDanil By the way, you can try to prepare a sample code and publish it with the label [inspection code]. Perhaps seeing the code, local experts will suggest some specific steps for improvement. - default locale

"Break classes" should be in accordance with architectural principles, rather than guided by the speed of their loading. If you have 30 methods in one class, then you clearly violate the principle of sole responsibility, at least.

  • Does the principle of sole responsibility somehow limit the number of methods? - Vlad Mamaev
  • @VladMamaev Robert Martin in his textbook work "Clean Code" claims that this is one of the "smells" of bad code and a clear sign of violation of this principle. - Sergey Gornostaev