Java Forum / General / July 2006
instanceof NOT (always) bad? The instanceof myth.
dmx_dawg@hotmail.com - 20 Jun 2006 19:03 GMT Hi all.
I just decided to write a message regarding the myth that the use of the instanceof keyword is categorically bad. Not all java programmers have fallen prey to the myth, but after years on the newsgroups it has almost gotten to the point where if it was discovered that you used instanceof anywhere in your app, it *must* be because you have a poorly designed system.
Is this a situation of 'bad-practice-phobia', where the fear of being thought of as a newbie programmer (or worse, a 'hack' who still 'doesn't get' OO) makes people create the most elaborately complex and unmaintainable designs to avoid using a specific 'bad practice'?
I think what's very often forgotten is that a bad practice can never be reduced to something as simplistic as 'never ever use keyword X'. All bad practices have there 'scope of ill-use'--which may be very big--but are almost never (if ever) absolute.
Specifics:
Alex Blewitt's Javaworld article ================================ It has been said that, in most cases, instanceof should not be used to test for object equality (see [BLEWITT1]) as it can break the symmetric property of the equals method's equivalence relation. In this case, using the getClass method of Object is the appropriate choice. This makes a lot of sense.
But notice that Mr. Blewitt's article never simply says 'always use getClass over instanceof'. He explicitly states a specific situation in which using instanceof is not appropriate. So next time someone cites Mr. Blewitt's article to prove your use of instanceof is bad without even seeing your code, you can be fairly certain they've probably never actually read the article. They are simply deep in the 'instanceof is always, always bad' myth.
Yoe see, getClass will always return the runtime class of an object and is useless if what you want to determine is whether an object falls within a specific inheritance hierarchy. In the example below, we want to determine if an object's class implements a specific interface. Here getClass does not help us.
class A implements IShared { }
A a = new A();
a instanceof A; // true a instanceof IShared; // true
a.getClass() == A.class // true a.getClass() == IShared.class // false
Now, of course, this is a contrived example with no context, but the need to check whether an object can be polymorphically treated as a specific type--wherever that type may exist in its inheritance hierarchy--can often be useful in practice (see the references section for some specific examples of this, such as those uses found in the Ecplipse framework).
Avoiding instanceof =================== Another thing you may find on the net are people who will try their darndest to provide you with an example of how you can get around using instanceof. They will explain that you need their complex, difficult to maintain, cyclic-dependency-creating solutions because your design is bad (you used instanceof right?... so it *must* be bad), and that your solution will certainly be a nightmare to maintain in the future. Let's take a brief look at some of the common 'solutions'.
Use method overloading instead ============================== Some may say that you simply need to overload a number of methods with different class parameters. Why use instanceof to determine if an object's class implements a specific interface? Let the overloading functionality of the language do this for you!
The problem is that
interface Animal { public void move(); }
class Fish implements Animal { public void move() { System.out.println("swim!"); }
public void eatAlgae(){} }
class Mouse implements Animal { public void move() { System.out.println("scurry!"); }
public void makeHoleInWall(){} }
So now we can create methods such as
class Test {
public void scare(Mouse m) { m.move(); m.makeHoleInWall(); }
public void scare(Fish fish) { f.move(); f.eatAlgae(); }
public Test() { Animal fish = new Fish();
scare(fish); // does not compile }
}
So what happened? Why doesn't this even compile? Because the fish object's compile-time type is Animal, *not Fish*. Of course, we could get around this by creating a new scare(Animal a) method, but then we're right back where we started.
Visitor (and Proxy Visitor) =========================== Another option that is often brought up is the use of the Visitor pattern. The problem with this is that it creates a huge maintenance issue. Visitor requires updating all of the 'visitable' classes every time we add new visitable class into the pattern.
Why not use adapter classes then? The problem is that in Java, its not always simple for 'visitable' classes to extend a 'VistableAdapter' (to avoid implementing an accept method for every possible visitable class) due Java's single inheritance (e.g.: if your class is already extending a class, you're out of luck unless you want to get into some messy code). This turns the Visitor pattern into a maintenance nightmare.
Now I have obviously skimmed over this one very quickly, but this is because Robert C. Martin has already ready written on this better than I could. Check out his web page on the subject [MARTIN1], as well (if you have ACM Portal access) his published paper on it [MARTIN2].
Other people using instanceof ============================= I encourage people to check out some of the other sources I've listed here. Maybe if people found out that the Eclipse framework uses instanceof [OTAKU], or if after they read an article by Bill Venners with a section explicitly titles 'When to use instanceof' [VENNERS], they will see that one should always beware of grand sweeping generalizations in any situation. So go ahead and use instanceof when it's appropriate, avoid it when it's not appropriate, and don't believe the hype!
Cheers!
Michael N. Christoff
References ========== BLEWITT Object equality--Writing equals and hashCode methods for data objects http://www.javaworld.com/javaworld/jw-06-2004/jw-0614-equals.html
MARTIN1 Visitor vs instanceof http://butunclebob.com/ArticleS.UncleBob.VisitorVersusInstanceOf
MARTIN2 Acyclic visitor http://portal.acm.org/citation.cfm?id=273456&dl=ACM&coll=portal
VENNERS See section "When to use instanceof" at the following link: http://www.artima.com/objectsandjava/webuscript/PolymorphismInterfaces1.html
OTAKU See section "Extensibility the interface way" http://www.beust.com/weblog/archives/2005_06.html
Oliver Wong - 20 Jun 2006 19:43 GMT > I think what's very often forgotten is that a bad practice can never be > reduced to something as simplistic as 'never ever use keyword X'. All > bad practices have there 'scope of ill-use'--which may be very big--but > are almost never (if ever) absolute. Never use keyword "goto" (unless your goal is to make your Java code not compile).
> Specifics: > [quoted text clipped - 13 lines] > probably never actually read the article. They are simply deep in the > 'instanceof is always, always bad' myth. Actually, I think it's a good idea to use instanceof in the equals() method. Here's how I usually implement it (written off the top of my head, might contain some syntax errors, but hopefully the semantics is clear):
<code> class Foo { private int myField;
@Overrides public boolean equals(Object other) { if (other == this) { return true; } if (other instanceof Foo) { return this.equals((Foo)other); } return false; }
public boolean equals(Foo other) { if (other == this) { return true; } if (!this.getClass().equals(other.getClass())) { /*this is explained below*/ return other.equals(this); } if (this.myField != other.myField) { return false; } return true; } } </code>
The .getClass() conditional is basically checking whether other's exact class is Foo, or if it is a strict-subclass of Foo. In the case that it is exactly a Foo, then we have all the information we need to determine equality, and so the method proceeds as normal.
In the case that "other" is a subclass of Foo, then I invoke that subclasses equals() method, because the subclass would knows more about Foo than Foo knows about the subclass.
Note that with this pattern, all subclasses of Foo *MUST* override the equals(Foo) method, or else you'll end up with an infinite recursion.
[...]
> Use method overloading instead > ============================== [quoted text clipped - 60 lines] > get around this by creating a new scare(Animal a) method, but then > we're right back where we started. I'm not sure that this example is an argument for/against using instanceof. At best, it's an argument against Java's choice of resolving method calls based on the declared type of a reference, rather than the runtime type. A cleaner design that doesn't involve instanceof or its lack thereof might be:
<code> public interface Animal { public void actScared(); }
public class Test { public Test() { Animal fish = new Fish(); fish.actScared(); } } </code>
> Visitor (and Proxy Visitor) > =========================== [quoted text clipped - 14 lines] > I could. Check out his web page on the subject [MARTIN1], as well (if > you have ACM Portal access) his published paper on it [MARTIN2]. I only read [MARTIN1], and it seems the main argument is to "avoid recompiling", which IMHO isn't a significant gain.
- Oliver
Daniel Dyer - 20 Jun 2006 22:37 GMT > Yoe see, getClass will always return the runtime class of an object and > is useless if what you want to determine is whether an object falls > within a specific inheritance hierarchy. In the example below, we want > to determine if an object's class implements a specific interface. > Here getClass does not help us. This isn't an argument for or against instanceof, but you can achieve what you describe by using the Class object returned by getClass:
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#isAssignableFrom(ja va.lang.Class)
Dan.
 Signature Daniel Dyer http://www.dandyer.co.uk
Twisted - 21 Jun 2006 08:04 GMT > This isn't an argument for or against instanceof, but you can achieve what > you describe by using the Class object returned by getClass: > http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#isAssignableFrom(ja va.lang.Class) "Foo.class.isAssignableFrom(object.getClass())" is just a very roundabout and awkward version of "object instanceof Foo" is it not? ;)
Daniel Dyer - 21 Jun 2006 09:33 GMT >> This isn't an argument for or against instanceof, but you can achieve >> what [quoted text clipped - 3 lines] > "Foo.class.isAssignableFrom(object.getClass())" is just a very > roundabout and awkward version of "object instanceof Foo" is it not? ;) Yes, but the point is that the OP claimed it was not possible. instanceof would be preferable in most situations, but isAssignable from can be useful in a situation where you don't know at compile-time exactly which class that you are using.
Dan.
 Signature Daniel Dyer http://www.dandyer.co.uk
Chris Smith - 20 Jun 2006 22:39 GMT > I just decided to write a message regarding the myth that the use of > the instanceof keyword is categorically bad. Not all java programmers > have fallen prey to the myth, but after years on the newsgroups it has > almost gotten to the point where if it was discovered that you used > instanceof anywhere in your app, it *must* be because you have a poorly > designed system. On these newsgroups? I've followed these newsgroups for many years (since about 1998) and haven't gotten that impression. Nevertheless, if the impression has been given, then it is incorrect.
What has often been said is that avoiding runtime type dependencies in general is a good idea whenever possible. Typically, though, this advice is applied to reflection instead of use of the instanceof keyword. I can also see that there are a lot of places where someone unfamiliar with OO programming may wish to use instanceof, but which should be replaced with polymorphism. Again, though, I see no justification for an absolute rule forbidding instanceof. Indeed, inheritance is often poorly applied to situations where it breaks proper separation of concerns.
> It has been said that, in most cases, instanceof should not be used to > test for object equality (see [BLEWITT1]) as it can break the symmetric > property of the equals method's equivalence relation. In this case, > using the getClass method of Object is the appropriate choice. This > makes a lot of sense. I am completely with you on this one. I have noticed a tendency (not so much on this newsgroup, but in other places, at least, such as introductory textbooks of fly-by-night tutorial web sites that are sometimes posted here) to do the following:
1. Assume that the programmer intends to write a certain kind of very mechanical implementation of the equals or hashCode methods.
2. Draw conclusions about how to uphold their contracts, on the basis of these mechanical implementations.
3. Forget that less mechanical implementations are possible.
This tendency is exaggerated by the section (which is a good one, by the way) in Josh Bloch's Effective Java that gives a mechanical way to handle hashCode (but that *also* notes that it only applies to information that is relevant to object identity... a qualification that is often lost in translation), and by the kinds of silly introductory examples to overriding hashCode and equals that are frequently in intro textbooks or tutorials.
An excellent example of where this does NOT apply is java.util.List. The contract for java.util.List.equals contains a requirement that any List should compare equal to any other List with the same contents. I think this is a very poor requirement, but it is nevertheless a requirement. Beginning an implementation of MyList.equals by comparing this.getClass() to other.getClass() is a sure-fire guarantee of breaking the contract.
What is true, though, is that in the absence of some specification for how to declare dissimilar classes, the task shoulod be considered impossible... i.e., they should always be considered unequal. That specification logically ought to occur in the documentation of some supertype. Hence, it may be valid to say that instanceof should never be used to check equals UNLESS there is some specification in some supertype that defines equality for some containing inheritance sub- hierarchy.
> Another thing you may find on the net are people who will try their > darndest to provide you with an example of how you can get around using > instanceof. They will explain that you need their complex, difficult > to maintain, cyclic-dependency-creating solutions because your design > is bad (you used instanceof right?... so it *must* be bad), and that > your solution will certainly be a nightmare to maintain in the future. Hopefully, you don't mean to include here situations in which someone provides not only general advice on how to avoid using instanceof, but also specific negative consequences of the use of instanceof, and how their proposed solutions avoids those drawbacks. For example, one common problem with instanceof is that it introduces a single point that must be extended in order to completely integrate a new subtype into the system. If the solution can avoid this by moving certain type-specific code into the subclass itself, this is nearly always a good thing. Therefore, there is reason to be cautious with this keyword when working in a situation where the list of possible subtypes is not theoretically limited, such as when working with a hierarchy of objects representing different accounting policies for various legal jurisdictions.
> Use method overloading instead > ==============================
> Visitor (and Proxy Visitor) > =========================== You missed the obvious one. If possible, take the type-specific behavior, and move it into a polymorphic method of the class. Doing so can require some creativity in design... but that's because you're really doing design rather than following someone's furmulaic answer. Design is a creative process. It involves finding and using the abstractions that are inherent to the system.
My suspicion is that when most advice is given to avoid instanceof, this is what is meant. Don't use instanceof, but rather identify and describe the inherent abstractions that allow you to write something that applies to all relevant types. If the advice is taken to mean something else, such as that a specific trick should be employed to remove the keyword in an automatable way, then someone has profoundly missed the point.
> Other people using instanceof > ============================= Note that most of the really good examples of using instanceof come from writing code that is inherently somewhat dynamic systems. The only exception I can think of comes from so-called "marker" interfaces, which are problematic from a design standpoint anyway; or from backward- compatibility limitations that prevent making appropriate changes to a common supertype.
 Signature Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation
Chris Uppal - 21 Jun 2006 12:33 GMT > An excellent example of where this does NOT apply is java.util.List. > The contract for java.util.List.equals contains a requirement that any > List should compare equal to any other List with the same contents. I > think this is a very poor requirement, but it is nevertheless a > requirement. I hadn't realised that. Live and learn...
I like the idea that a List<java.awt.Point> can be equal to a List<byte[]> ;-)
> My suspicion is that when most advice is given to avoid instanceof, this > is what is meant. Don't use instanceof, but rather identify and [quoted text clipped - 3 lines] > remove the keyword in an automatable way, then someone has profoundly > missed the point. +1 (and in spades).
> Note that most of the really good examples of using instanceof come from > writing code that is inherently somewhat dynamic systems. The only > exception I can think of comes from so-called "marker" interfaces, which > are problematic from a design standpoint anyway; or from backward- > compatibility limitations that prevent making appropriate changes to a > common supertype. And +1 again.
-- chris
Twisted - 21 Jun 2006 21:03 GMT > I like the idea that a List<java.awt.Point> can be equal to a List<byte[]> ;-) I think it's more that a LinkedList<Foo> may be equal to an ArrayList<Foo>. I expect sets are even more flexible, comparing equal no matter what order the objects are in too. :)
> +1 (and in spades). > > And +1 again. What's this -- an obscure way of saying "I agree" or "Seconded"? You do realize it is possible to take conciseness *too* far? :)
Chris Smith - 21 Jun 2006 22:40 GMT > > +1 (and in spades). > > > > And +1 again. > > What's this -- an obscure way of saying "I agree" or "Seconded"? You do > realize it is possible to take conciseness *too* far? :) It is a means of expressing agreement.
I believe it originated (at least I first saw it) in open-source software project practices. In that setting, it's an official voting mechanism: someone makes a suggestion about a course of action on the project mailing list, and any active developers (often, committers) for the project may post +1 or -1 or 0, and the votes are all tallied at the end to see whether the vote passed or failed.
I doubt it is used merely for conciseness; it's a sort of cultural heritage thing, as well.
 Signature Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation
Timo Stamm - 21 Jun 2006 23:06 GMT Chris Smith schrieb:
>>> +1 (and in spades). >>> [quoted text clipped - 12 lines] > > I doubt it is used merely for conciseness; If you call for votes on a topic and receive hundreds of replies, the conciseness of +1/-1 is very useful. It is much easier to count occurrences of "+1" instead of having to consider dozens of variants of the expression of agreement. It also helps to keep a voting thread from trailing off.
Timo
Twisted - 22 Jun 2006 03:03 GMT > > I believe it originated (at least I first saw it) in open-source > > software project practices. In that setting, it's an official voting [quoted text clipped - 10 lines] > the expression of agreement. It also helps to keep a voting thread from > trailing off. Wouldn't putting a poll feature in a forum where this is done be better still?
And that's leaving aside the horrible revelation. I thought software design by committee (much MS stuff comes to mind) was bad enough. There's also software design by democracy? Oh no!
Timo Stamm - 22 Jun 2006 09:28 GMT Twisted schrieb:
>>> I believe it originated (at least I first saw it) in open-source >>> software project practices. In that setting, it's an official voting [quoted text clipped - 12 lines] > Wouldn't putting a poll feature in a forum where this is done be better > still? Does your news reader have a poll feature? Or your email client? Keep it simple.
> And that's leaving aside the horrible revelation. I thought software > design by committee (much MS stuff comes to mind) was bad enough. > There's also software design by democracy? Oh no! "I've never heard of it before but it is bad"
Chris Smith - 22 Jun 2006 15:22 GMT > And that's leaving aside the horrible revelation. I thought software > design by committee (much MS stuff comes to mind) was bad enough. > There's also software design by democracy? Oh no! Perhaps, but I think things are much better than this worst case, in practice.
The problem with "design by committee" (in the way that the term is normally used, which actually doesn't much apply to Microsoft as I understand it from friends who've worked there) is that you bring in a bunch of people with vested interests in certain design decisions and begin a huge compromise process. For example, (not I'm using random names and features here; please don't assume anything about real products based on the section below!) Oracle wants this kludgy syntax used by the SQL standard because they have already implemented it, while DB2 wants the Entry-level compliance requirements weakened to the point that their product is considered compliant, and meanwhile, Sybase doesn't want to break their customers existing code by having to implement a standard that contradicts their existing product. Generally, everyone gets their way, and the result is a mess.
What happens on open-source project mailing lists is different. Everyone is primarily interested in writing good code, since there really are no monetary or marketing interests involved. The developers working on the project generally self-select for agreeing with the general design principles in the first place. Developers who have a conflict of interest may simply avoid voting on some feature. Most design work is done by single individuals who can follow through with their ideas, and feedback from the mailing list is used as an aid. Actually, the majority of formal votes that I see like this are regarding whether someone should be given write access to the source code repository; but if a design-related vote is taken, it's because a developer specifically wants feedback from other smart, unbiased people in the project when evaluating design alternatives.
Seems like a reasonable system to me.
 Signature Chris Smith - Lead Software Developer / Technical Trainer MindIQ Corporation
Twisted - 22 Jun 2006 21:06 GMT > The problem with "design by committee" (in the way that the term is > normally used, which actually doesn't much apply to Microsoft as I > understand it from friends who've worked there) is that you bring in a > bunch of people with vested interests in certain design decisions and > begin a huge compromise process. For example, you want to write a next-gen OS, and invite all the big businesses to a table to suggest features. Users want to be able to do anything they want. The entertainment industry wants to have root-level control over what can be viewed, copied, etc. when, even over a system's administrator's wishes. The OS vendor itself wants to gratuitously make migrating to any other OS difficult, so proposes obfuscated APIs that don't function precisely as publicly documented, though internal documentation of their real contracts prevets this being a problem for their in-house application developers. Third-party application developers want clearly-specified, well-behaved APIs. Government agencies and law enforcement want snoopable backdoors and key escrow anywhere encryption is used. Users and encryption vendors don't...
The result of course is a huge mess, which will be glossed over by giving it a pretty-sounding name, such as some nice harmless herbivore like maybe a longhorn, or something suggesting a huge panorama of wonderful options, such as might be termed a "vista" ...
Hrm. I thought you said Microsoft didn't do design by committee? ;)
> What happens on open-source project mailing lists is different. > Everyone is primarily interested in writing good code, since there > really are no monetary or marketing interests involved. Fortunately.
Unfortunately, open source projects do sometimes have vested interests, though they are different vested interests. Most p2p apps try to enforce some kind of social engineering. Some make it hard to grab large numbers of search results at once, even though the sooner you have the files the sooner they're being shared *cough*Shareaza*cough*. Others nag you about licenses and copyright*cough*Limewire*cough*. A lot deliberately obfuscate the documentation (if there is any) and user interface to push an agenda of requiring users become technical and learn lots of stuff they shouldn't need to about the internals, and when they call with questions are told to read the source, and with bug reports to submit a patch -- here there's a clear and unsubtle push to make all the users become more developers and/or to not support anyone but developers. When it's a compiler this is questionable, since a developer of RPGs, say, may not have time to devote to learning how to write and fix a compiler as well as an RPG. When it's image manipulation software it's inexcusable since that's a genre everyday nontechie Joes should be able to use. (Not naming any compilers here -- gcc user support and documentation in particular doesn't seem to be at all bad -- but I will name a photo manipulation package ... GIMP ...)
> The developers working on the project generally self-select for agreeing with the > general design principles in the first place. True, and different philosophies can always fork. Games also get forked simply to create new, similar games that aren't direct competitors with the original because they aren't really substitutable, the way two variations of say a paint program would be. A paint program is a paint program is a paint program, but two different games are, well, different.
Developers will likely agree internally then, though they may disagree with what users want to do with a product...
> Seems like a reasonable system to me. So did the electoral college to somebody. Now we're stuck with an unwanted war president with world-record-low approval ratings, unjust oil wars ongoing, and so on, all motivating the next big terrorist attack, whenever that ends up happening.
Oliver Wong - 22 Jun 2006 21:33 GMT >> The problem with "design by committee" (in the way that the term is >> normally used, which actually doesn't much apply to Microsoft as I [quoted text clipped - 22 lines] > > Hrm. I thought you said Microsoft didn't do design by committee? ;) I don't think the government, third party application developers and the entertainment industry actually ever really participated in the design of Vista. They may have requested certain features, but Microsoft was free to ignore those requests.
Otherwise, it's like saying "the lever"/"the inclined plane"/"some other elegant machine" was designed by committee, because I requested for a feature to be present in that machine, and thus I participated in its design.
"Vista is a mess, therefore it must have been designed by committee" is, of course, fallacious reasoning.
- Oliver
Twisted - 22 Jun 2006 23:12 GMT > I don't think the government, third party application developers and the > entertainment industry actually ever really participated in the design of > Vista. They may have requested certain features, but Microsoft was free to > ignore those requests. Then why didn't they? It's not those organizations that will be buying copies of Vista -- well, they probably will, but most sales will go to other organizations and individuals.
That MS didn't ignore those requests implies that they basically did have some special grant to give input into the design process. And that makes it design by committee.
Oliver Wong - 26 Jun 2006 15:08 GMT >> I don't think the government, third party application developers and the >> entertainment industry actually ever really participated in the design of [quoted text clipped - 9 lines] > have some special grant to give input into the design process. And that > makes it design by committee. Specifically, which request(s) are you referring to?
- Oliver
Twisted - 27 Jun 2006 05:37 GMT > Specifically, which request(s) are you referring to? The ones to put TC features in Winblows so Big Entertainment can control your use of lawfully purchased DVDs, in contravention of first sale doctrine? And others like those? MS didn't include such evilness out of the goodness of its heart. :P
Oliver Wong - 28 Jun 2006 15:25 GMT >> Specifically, which request(s) are you referring to? > > The ones to put TC features in Winblows so Big Entertainment can > control your use of lawfully purchased DVDs, in contravention of first > sale doctrine? And others like those? MS didn't include such evilness > out of the goodness of its heart. :P I suspect Microsoft put Trusted Computing into Vista willingly, and not as a "compromise" to bow down to "Big Entertainment". Why would Microsoft want to NOT put TC in? The only reason I can think of is to gain the favour of the the anti-TC advocates, which is probably not Microsofts target demographic anyway.
The fact that this was not a compromise on Microsoft's part means that this was probably not the result of design by committee.
- Oliver
Twisted - 03 Jul 2006 19:19 GMT > I suspect Microsoft put Trusted Computing into Vista willingly It probably opens them wide to all kinds of lawsuits, liability, and antitrust actions. Root level power over most of the PCs in the world, with the kill switch located in Redmond? Too much concentrated power to be tolerated for long by any country. Build that f.cker and threaten to actually use it, and it might not just be lawsuits and DoJ investigations -- how about armed f.cking invasion? (And this when they've deliberately used recent security updates to XP to "piggyback" unremovably spyware that can and sometimes does deactivate XP. There's only been a trickle of cases so far, but when Vista ships, they'll quit testing it and nuke all remaining functioning copies of XP to force everyone to upgrade. And then ... one ring to bind them all, my friend. That's going to be a direct threat to the sovereignty of any nation that hasn't migrated mission-critical stuff to open source, and the usual response to such a threat is military force. Of course, it would mean invading the nuclear-armed USA. Do you really think Bill was ready to start World War III without some convincing? As for the lawsuits, I don't think their EULA will let them weasel out of responsibility for problems caused by TC in Vista. Having been found to wield monopoly power by the courts, anything with such obvious anticompetitive uses will be under a lot of scrutiny, and one-sided contracts of adhesion people are leveraged into by a monopoly misusing copyright law* are just begging to be found null and void.)
*Using copyright to control conditions of sale and distribution so as to ram a contract down someone's throat that then grants the vendor much greater powers and privileges than they would have under just copyright law, such as blocking fair uses like backing up, reverse engineering, or doing what you like (short of distributing copies or "publicly performing" the thing) after purchase, clearly falls under the doctrine of copyright abuse. Of course, that doctrine is looking kind of quaint, much like the Sherman Act. And first sale and fair use seem to be heading that way next. :P In any event, the Copyright Act was never intended to permit the copyright holder to manufacture all kinds of new exclusive rights out of whole cloth or forbid fair use; software EULAs are a legal travesty more generally. Save the GPL and its ilk, of course, which are genuine license agreements that *permit* you to do some of the things copyright by default *reserves*, such as distribute copies, under certain conditions (such as that you include or at least provide a pointer to the source); as opposed to *further restricting* you.
Oliver Wong - 03 Jul 2006 20:41 GMT >> I suspect Microsoft put Trusted Computing into Vista willingly > > It probably opens them wide to all kinds of lawsuits, liability, and > antitrust actions. It seems we're straying pretty far off topic. If you know of an appropriate newsgroup and want to continue this discussion, let me know where. Otherwise, I'm satisfied to leave things as they are.
- Oliver
Oliver Wong - 22 Jun 2006 15:23 GMT >> I like the idea that a List<java.awt.Point> can be equal to a >> List<byte[]> ;-) > > I think it's more that a LinkedList<Foo> may be equal to an > ArrayList<Foo>. I expect sets are even more flexible, comparing equal > no matter what order the objects are in too. :) Consider the definition of equality for lists:
<quote> Both lists have the same size, and all corresponding pairs of elements in the two lists are equal. (Two elements e1 and e2 are equal if (e1==null ? e2==null : e1.equals(e2)).) In other words, two lists are defined to be equal if they contain the same elements in the same order. </quote>
So a List<Point> and List<byte[]> will be equal if they only contain nulls, or if they are both empty.
- Oliver
dmx_dawg@hotmail.com - 20 Jul 2006 20:06 GMT Hi all.
I was in a bit of a 'rant' mode when I wrote that post, however I believe the content stands (even if the tone was sometimes a bit sarcastic). However, I'm very very pleasantly surprised to see the great, well thought-out responses.
Chris: I do note those who are simply 'sagely warning' about the possible implications of the keyword, however there are those that, as you mention, 'mechanically' abide by a 'never ever use instanceof' mantra. For example:
>From http://www.hibernate.org/280.html
>>>> "instanceof is the hallmark of bad design" Now I assume they were referring to the keyword's use in the particular example shown as being bad design (and not in all cases), but this is the type of things that helps start these bad practice phobias where people forget about the context of the use and focus only on the use itself.
A few points:
As for the isAssignable method, I agree it can be used. But it seems to essentially do the same thing as instaceof and hence, as far as popular 'best-practice' goes, it has all the same faults of instaceof. eg: "Your design should be using polymorphism and have no need for isAssignable".
As for polymorphism vs instanceof, I've always agreed with anyone who has felt that:
1) if it can be done in a way that doesn't actually take away from application ease-of-maintenance
2) if it can be done in a way that doesn't add too much undue complexity
3) if it makes sense from the logical abstraction of your system
...then polymorphism is the way to go. Luckily in my experience (although often requiring a little iteration and refactoring): polymorphism is possible, instanceof is not required, the design ends up cleaner and everyone is happy. Its funny you mentioned the 'dynamic' aspect of the examples I presented, as the application that triggered my email (in which instanceof is used--sparingly) has a plugin architecture where classes are frequently dynamically loaded.
We've also been able to reduce the use of instanceof by relying more on plugin descriptors for information rather than determining such things at runtime (the use of descriptors was actually always the plan). But there are still cases where instanceof makes the most sense (or perhaps isAssignable--I will read up on it more to see if it offers advantages to our application over instanceof).
Anywho, thanks all for the informative posts!
Cheers!
-mike
> > I just decided to write a message regarding the myth that the use of > > the instanceof keyword is categorically bad. Not all java programmers [quoted text clipped - 115 lines] > Chris Smith - Lead Software Developer / Technical Trainer > MindIQ Corporation
Free MagazinesGet these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...
|
|
|