Java – Constructor Injection, design for testability


I have this code (you probably can ignore that it is Swing code), but I usually end up with too many arguments in my constructor. Should I use model bean class and then pass that object in the constructor?

public BrowserFrame(final JTextField url, final JTextArea response, final JTextField command, final JButton actionButton) {

    this.urlField = url;
    this.responseArea = response;
    this.commandField = command;
    this.actionButton = actionButton;


In this code, I am considering adding more objects, used by this class. Do I keep just adding more args and pass them in the constructor. Possibly use setting injection?

But according to Misko, this is also code smell.

"Objects are passed in but never used directly (only used to get access to other objects)"

Best Solution

Having too many arguments in your constructor is a sign that your class has too many responsibilities. If you're just setting fields in your constructor, look to see if some of those fields are only used by a subset of the methods in the class. That's a sign that your arguments and methods can be split up into smaller classes with more focused responsibility.