I am working on a functionality and have confuded about the length of the method.There are certain points are read but not sure what is best or a standard
- A method should be as long as required to perform the task for which it is designed.
- can read the whole method without the need for scrolling and it fits onto the page.
There are others points also.
I have a static helper method and whose lengths is getting increased, so i have the option of either to create more static helper methods and distribute the tasks to those methods but than it seems like i am creating unnecessary static methods.
Other approach is to create another helper class and delegate some work to methods defined in the helper class
I am not sure what is best way/standard way to do this.
In general, both of those points are very good things to consider. One of the main reasons you already mentioned: It makes the code more readable and easier to digest.
The other benefit from splitting up your methods and creating helper methods is one that won’t manifest itself immediately. Instead, one day you’ll be working on a system where you have users who are Customers, and you’ll need to implement a feature where you’ll need to create admin users, or Vendors, or some other abstract version of a person.
You’ll find yourself thinking about how you’re going to save the vendor’s orders, or the vendor’s whatever, to the database and you’ll need to generate some form of something or other that is used to identify the order, and you’ll realize that the code you wrote to do this same action for the customer will work with a Vendor object just as well as a Customer object.
However, if all of that code was strong together in the same method that handles everything related to Customers, you’d be using what we call cut and paste reusability. Which involves going through your previously-written code and cutting and pasting relevant parts and creating a copy that is mostly similar but with very subtle differences. (Note: This is generally considered a bad practice.)
But when you write small, concise methods that do one thing only and one thing really well, you find that you’re able to take those building blocks you’ve already built and then use them to build other things, saving you time, saving QA time, and in general lowering the maintenance costs of the project, allowing the product to move forward, and allowing you to move forward and do cooler stuff.
However, one last point to consider is that it is possible to overdo it, or over-architect. There is a fine line between too long and too short, and you may be tempted to split your methods up too much. If you get to the point where splitting up your methods makes it too hard to work with, then consider that you may be taking it a little too far. Good luck!