Take the 2-minute tour ×

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:

  1. add this field value into the constructor
  2. create 2 subclasses, replace original field usage with some protected method and override it in subclasses
  3. 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?

share|improve this question
Knowing what you mean by "in certain situations" is the key to giving you a good answer. Please edit your question to specify if the new value should apply to some instances while other ones would continue using the static final, if you want to set a new value into the static final permanently to be used from that point on, or to do something else. –  dasblinkenlight Nov 15 '12 at 16:06
You forgot option 4 which is to use a static initializer to set the value. This depends on your situations but since it is an unusual choice I thought I would mention it. –  Sign Nov 15 '12 at 16:19
add comment

2 Answers

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.

share|improve this answer
add comment

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

share|improve this answer
add comment

Your Answer


