Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design Pattern to replace a method with many parameters [duplicate]

Java 1.6

I have a method with many parameters. This is not a constructor but a normal method.

 class A {
   public void m (int a, int b, boolean c, List<>...) { }
 }

How to replace a method to a better form ? As I understand the Builder design pattern is for contructors.

like image 997
Tony Avatar asked Dec 15 '22 02:12

Tony


2 Answers

If I face a method that has too many parameters I do the following steps usually:

  1. I try to identify an entity these parameters are related to and check if Preserve Whole Object refactoring can be used.

    You are getting several values from an object and passing these values as parameters in a method call. Send the whole object instead.

  2. If all these parameters are independent and I want to increase number of parameters I use another one common solution - Introduce Parameter Object refactoring.

    You have a group of parameters that naturally go together. Replace them with an object.

    In order to build that object other techniques and patterns can be used (e.g. Builder, Method chaining, Fluent interfaces).

like image 76
Ilya Palkin Avatar answered Dec 28 '22 06:12

Ilya Palkin


If the parameters naturally go together they can be substituted with the Parameter Object. If you don't want a long list of parameters in the constructor of the Parameter Object you can use the Builder design pattern to construct it. Another somewhat relevant technique is Preserve Whole Object.

like image 44
zafarkhaja Avatar answered Dec 28 '22 07:12

zafarkhaja