public boolean equals(Object other) {
     try{ return equals((Thing)other) } catch { return false; }
}
Here the semantics are entirely wrong. Imagine we have apples and oranges. Do we want a false when comparing apples to oranges, a runtime exception or a compile error. I vote compile error. Object oriented programming votes so as well. It doesn't have anything to do with purity. --- Generics give a big help here and can enable the compiler to do much more to the help of OOP than without (think .net 2 and .net 3; collections and generic collections).

As for the second example, when your very query is made up of a type, we can't argue that dealing with types as regular data is allowed.
However in this case it was about statistics, which should come at the very end without code being built on top of it. I am sure the problem is however ill-posed as it is mixing the type as data (shouldn't gui components be described in some data representation instead). It is at least that this knowledge is necessary when you take those kinds of shortcuts.

Serialization and communication in networks raises a hard point against me. The case is that indeed we need to be branching on a some variant of instanceof since all we have is a data representation of the type. The thing is annoying however, and people do strive to encapsulate that away with protocols like RPC and so on. So the conclusion is: although there may be no way away from branching on a serialization of a data type (the data representing a class), you should encapsulate that so that other code does not have to do an instance of. --- Once the object is out from the wire, we're back to OO Land where instanceof use is shunned.
To further elaborate yet again on the last example I've provided, it would relatively similar to the following:
class Program
{
static void Main(string[] args)
{
Foo foo = new Foo();
foo.Add(1);
foo.Add("xterm");
foo.Add(2);

Console.WriteLine(foo.GetCount<Int32>());

Console.ReadLine();
}
}

class Foo
{
Dictionary<Type, int> counter = new Dictionary<Type, int>();

public void Add(Object o)
{
if(counter.ContainsKey(o.GetType()))
counter[o.GetType()]++;
else
counter[o.GetType()] = 1;
}

public int GetCount<T>()
{
return counter[typeof(T)];
}
}
I wanted to provide this alternative so that people understand that i have not said in anyway that there's no solution to instanceof. It's a matter of how much effort you want to put into it or how pure you want to be.
rahmu wroteAyman's signature is bogging me. Determining the class of your object can sometimes be very useful. For example when catching exceptions, you could implement certain behaviors for particular types of exceptions.

What do you think? What are the good practices in that case?
Shouldnt all the behavior related to an object be contained in the object itself?
@arithma: you do realize that some languages like PHP or Ruby do not support generics. Saying that generics (or any other language specific feature) is an alternative to instanceof() is only a partial answer.

Yes I do believe that there is a way around them, and using instanceof() is not the best practice of all time. However I agree with xterm that practicality should prevail over purity.

However my question is what is the real cost of breaking a perfect OOP design and using instanceof?
rolf wrote
rahmu wroteAyman's signature is bogging me. Determining the class of your object can sometimes be very useful. For example when catching exceptions, you could implement certain behaviors for particular types of exceptions.

What do you think? What are the good practices in that case?
Shouldnt all the behavior related to an object be contained in the object itself?
Or it's parent. Then again, what if the behavior that you're intending to work falls on Type X and not on type Y which are both children of type P ? You'd have to subclass X and add the behavior there.
rahmu wroteHowever my question is what is the real cost of breaking a perfect OOP design and using instanceof?
Time versus Effort. If you have the time, you should adhere to the paradigm.
@rahmu: Except in the very few convoluted examples which I already mentioned (like sorting an array's elements by their type or as xterm put it in his example (counting members and grouping by type), etc..)) the use of instanceof can be easily replaced by proper inheritance.
The thing is the effort to follow proper inheritance is blown out of proportion.

What do you lose when you don't implement proper inheritance?
Imagine you have used instanceof to specify behavior for 4 different objects in four different contexts. Each time you have to add a context (context is usually a function call somewhere), you will have to copy the branching statements. When a new object type is added, and has to be dealt with in all these contexts as well.

The question is: what happens when you need to provide this functionality as a library? How can you branch on yet to be defined types (pending defining by the consumer of the application)?

That is the primary concern why proper design shuns using branching on run-time type info in the general case (with the few exceptions that blur the line between data and data-type).
When I program, I often do something like that:
<?php
// In this example I'll use PHP
// $andSomthingElse is an OPTIONAL parameter, which expects a non-empty array when used
function doSomething($withSomething, $andSomethingElse = false) {
    // do common stuff here
    if($andSomethingElse !== false and count($andSomethingElse) > 0) {
        // do the stuff that we do when $andSomethingElse is given here
    }
    // return something
}
?>
This is not OOP, but conceptually, it is not that different of using instanceOf(). In fact I might use is_array() instead of using !== false.

So, is that bad programming practice?
Not necessarily wrong, although in these cases prefer using isset()
rahmu wroteNot necessarily wrong, although in these cases prefer using isset()
You're right. I didn't know that <? $myVar = null ?> tested false with isset().
a month later
sorry for grave digging, just to make it clear for you, instanceof operator is primarily used to validate WildCasts , example you have a super "Appliance" ,and 2 sub classes of it "Tv" and "Radio"

Appliance Class:
/**
*
*@author Nader
*
**/
public abstract class Appliance {
public abstract void turnOn();
public abstract void turnOff();

}
Tv class:
/**
*
*@author Nader
*
**/
public class Tv extends Appliance {
private boolean on;
private float frequency;
@Override

public void turnOn()
{
on = true;
}
@Override
public void turnOff()
{
on = false;
}

public void changeFrequency(float freq)
{
frequency = freq;
}
}
Radio class:
/**
*
*@author Nader
*
**/
public class Radio extends Appliance {
private boolean on;
private int channel;
@Override

public void turnOn()
{
on = true;
}
@Override
public void turnOff()
{
on = false;
}

public void changeChannel(int chan)
{
channel = chan;
}
}
ShowUse , a class to show the proper and main usage of the instanceof operator :
import java.util.ArrayList;

/**
*
*@author Nader
*
**/
public class ShowUse {

public static void main (String[] argV)
{
//declare a list of the general type (Appliance)
ArrayList<Appliance> appliances = new ArrayList<Appliance>();

//adds 20 Tvs or Radios objects, randomly to the list , according to random numbers, either 1 or 0.
for(int = 0 ; i < 20 ; i++)
     appliances.add((int)Math.random()*10==0?new Radio():new Tv());  

//The real use of instanceof for casting validation
for(Appliance app : appliances)
{
   System.out.println("this appliance is a " + ((app instanceof Tv)?"Tv":"Radio"));
   if(app instanceof Tv)
{
Tv tv = (Tv)app;
tv.changeChannel(20);// call a function only found in the Tv class , after making sure that its type is a tv, other wise if it was a radio itll throw //runtime exception
}else{
Radio rad = (Radio)app;
rad.changeFrequency(99.1); //////////////////////////////////////////////////////////////////////////////////////////////////

         }
     }
 }
}
Hope that helps ^^.
That example doesn't highlight the proper use of instanceof, in fact such a solution is frowned upon in OO
xterm wroteThat example doesn't highlight the proper use of instanceof, in fact such a solution is frowned upon in OO
i deny , it does for sure,however, generally the usage of it is not very recommended , its much better when you distinguish them by setting ID's for them for example , and distinguishing them with that , but still that is an ideal use of the instanceof dirty op ;)
Syntactically it's correct, practically it works. Theoretically it's incorrect, proper OO dictates that a much better solution would be to apply further constraints to achieve such functionality in a better hierarchical structure with additional Behavior.

Edit: Reply came before your edit.
xterm wroteSyntactically it's correct, practically it works. Theoretically it's incorrect, proper OO dictates that a much better solution would be to apply further constraints to achieve such functionality in a better hierarchical structure with additional Behavior.
yes, theoretically its incorrect, like its always better to use information supported by the class itself, but i'm just kinda explaining some point of using that operator.

The case is similar with Threads, you an use the Thread.stop() method, but it's being deprecated, because it might cause some synch problems and theoretically incorrect, therefore it always recommended to base what's in the run() method on conditions, where certain stuff won't execute if for example a certain boolean , integer or whatever's value changes.
What xterm is trying to tell you is that you need an extra function within the interface of appliance that you derive to do nothing in radio and changes the channel in tv. If it needs arguments, you're probably mixing things and deriving them where they don't belong.
arithma wroteWhat xterm is trying to tell you is that you need an extra function within the interface of appliance that you derive to do nothing in radio and changes the channel in tv. If it needs arguments, you're probably mixing things and deriving them where they don't belong.
i totally don't get you , besides that Appliance isn't an interface, it is an abstract class...
Since when has programming become a dogma? Let everyone program the way he wants to!
Moderation warning: Let's keep focused on the subject at hand, the use of instanceof and why and when should it be avoided. No off-topic please.
Back on topic, I want to allude to the most brief argument against instanceof or any other type identification used in branching.
You have a compiled system that defines an interface that the client will be deriving additional classes from. If you branch on some of your library defined classes you will be stuck when you later want that behavior to be specified by the client for their own classes.
On the other hand, there does not seem to be any case where the instanceof is necessary: you can always remove instanceof from a language and do whatever you please with the same ease or simpler; unless of course you show a certain point of otherwise. The more major issue is that the use of instanceof as a shortcut may later impose a recompile for various assemblies when you need to add behavior for specific usually remote classes. What do you think?