javamethodsrefactoringparameter-objectlong-parameter-list

How to refactor long parameter lists into a parameter object in Java?


I am currently trying to refactor the getRGB,getSubimage and setRGB methods in the BufferedImage class. I am fairly new to Java and want to create good code; the problem is my parameter list is becoming very long and is causing problems for me. I found the parameter object as a solution however I am struggling to implement it.

Can I get a representation of how the following method can be improved with a parameter object;

public void setRGB​(int startX, int startY, int w, int h, int[] rgbArray, int offset, int scansize)


Solution

  • Well, based on the information you provided, that's not much, what you want it's quite simple. So, you should wrap all these parameters inside a class (this class should follow the JavaBeans specifications and you should definitely should read about it, if you still didn't), like these:

    public class RGB {
        private int startX;
        private int startY;
        private int w;
        private int h;
        private int[] rgbArray;
        private int offset;
        private int scansize;
    
    // getters and setters
    
    }
    

    And then, your method will only receive an object that is a representation of this class:

         public void setRGB​(RGB rgb) {...}