1

Many a times a constructor has some params are optional while object creation. They are later on set with setters ( eg: during lazy initialization ).

My question is there can be some cases when a parameter can never be set via a constructor or a setter at all. For sake of this question, I am calling such instance variables - dormant. Asume a standard pizze example, where Pizza(cheese, chicken, toppings).. A customer may not want topping and may leave it dormant.

Is this considered bad practice ? If yes then are there any known patterns to clean such classes with dormant instance variables ?

Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86
JavaDeveloper
  • 5,320
  • 16
  • 79
  • 132

1 Answers1

2

I think that the Decorator Pattern is what you need:

The decorator pattern can be used to extend (decorate) the functionality of a certain object statically, or in some cases at run-time, independently of other instances of the same class.

See a .NET example here:

Please help me understand the "Decorator Pattern" with a real world example.

And here you can find a Java example:

Gang of Four – Decorate with Decorator Design Pattern

Community
  • 1
  • 1
Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86