Submission: switch (...) instanceof feature
Ulf Zibis
Ulf.Zibis at gmx.de
Wed Apr 22 07:07:09 PDT 2009
Interesting recipe! Thanks.
See my comment below...
Am 22.04.2009 15:39, Gabriel Belingueres schrieb:
> You may try to get rid of the instanceof by using "another level of
> indirection". For example in this case, with a Strategy as the cache
> value:
>
> interface ValueStrategy {
> CharSet lookup();
> }
>
> class CharSetContentStrategy implements ValueStrategy {
> CharSet value;
> public Charset lookup() {
> ....
> }
> }
>
> class StringContentStrategy implements ValueStrategy {
> String value;
> public Charset lookup() {
> ....
> }
> }
>
> declare:
> final Map<String, ValueStrategy> cache;
>
> then the lookup method would be:
>
> synchronized Charset lookup(String lowCanonical) {
> ValueStrategy v = cache.get(lowCanonical);
> return v.lookup();
> }
>
> Please note that in some point the above code may require that you
> make an instanceof to know which strategy to create, but this code can
> be isolated in a unique method, instead of in many methods as you have
> now. (For example, creating a factory class of strategies.)
>
> (Of course, another different question is if this will perform faster
> than using instanceof everywhere.)
>
>
.. another different questions:
- if strategies like this will be reasonable regarding footprint of
whole application.
- readability of code for externals
- isolating the instanceof code to *additional* unique method will not
really solve the issue. In my case, the lookup method *is* the unique
method.
-Ulf
More information about the coin-dev
mailing list