Suppose, I have a class with a constant static final field. Then I want in certain situations that field to be different. It still can be final, because it should be initialized in constructor. My question is, what strategy I should use:
- add this field value into the constructor
- create 2 subclasses, replace original field usage with some protected method and override it in subclasses
- Or create some composite class that will held instance of my class inside and somehow change that value?
Which approach should I use and why?
2
I think you need to ask why the field was set to final in the first place. The impression is that it wasn’t ever intended to be changed.
The fact that you need to change the value (or have multiple options for the value) indicates that the original assumptions driving the design are no longer valid.
I would recommend thinking about what function that field is actually serving and how best to provide that functionality to other objects. That might mean a small-ish factory pattern implementation, or it might be two separate properties that can be retrieved as the callers require. Your original question doesn’t provide enough context to suggest a more accurate alternative.
So I think your three options are solving the wrong problem. You’re trying to shoe-horn change into an element that was explicitly designed to not accept change. Find a better way of serving up that functionality based upon your application.
Option 3 will allow you to enforce atomicity of the Object Creation. You will be able to set the value in the other class since it has an aggregation to your class with the static final field.
Doing so is a simple yet powerful way to increase both the correctness and robustness of a given object: since it cannot fail to be correctly initialized, subsequent methods are free to deal with their own processing, and use whatever fields they need to do said processing, without concern for the correct initialization sequence of the object.
Resource – Reference