Java pattern for future type change
What is the best way to program against an anticipated type change. Say, I may have to use Joda DateTime instead of开发者_如何学JAVA Java Date in the future. Since Java doesn't encourage anti pattern like typedef, what is the best way to ensure an easy refactoring in the future.
thanks.Certainly the "Single Responsibility Principle" or something near it and encapsulation should help limit dependency creep.
However, choice of basic types is an architectural decision. If you were to change string or integer types, you'd expect change across your code. Date isn't that much different.
Programming to interfaces and proper layering is the best defensive measure I can think of.
When you separate what is done from how it's done, you leave yourself the possibility of changing implementations without affecting clients as long as the interface is unchanged.
If you have to change the interface, or if you end up doing a new problem altogether, all bets are off. No language has built-in clairvoyance.
Wrap the API/type in question behind a wrapper interface, and use it only through the wrapper. Then you need to change only the wrapper code to switch the implementation.
This would be the general solution. However, Tom is right in pointing out that Date is so fundamental a type that choosing it should be an architectural decision, not to be changed often.
Sound to me like you want to accomplish "dynamic reclassification",
I think you should be able to achieve this with the State pattern.
Please review an example here: http://cnx.org/content/m17225/latest/
You could try eclipse's IAdaptable
What is the best way to program against an anticipated type change.
Keeping your design as simple and clean as possible, and maintaining a good suite of unit tests.
This helps you with all future changes, including unanticipated ones (which are much more common).
My take on this is that a good Java IDE can drastically reduce the pain of a large-scale change of data types. You search for points at which your code uses the old class, replace with the new class, and fix the ensuing compilation errors, and repeat. When you are done with the changes, run your unit / regression tests, fix the bugs and (touch wood!) you are done.
OK ... it may not be that simple. In particular:
- Reflective dependencies can be difficult to find.
- Dependencies in external wiring / configuration file can be difficult to find.
- A large-scale application comprised of components written / maintained by lots of people can be problematic. (You cannot really just hack on everyone elses code.)
精彩评论