Ayman'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?

EDIT: for archiving purposes, here's the signature I'm talking about:
"Anytime you find yourself writing code of the form "if the object is of type T1, then do something, but if it's of type T2, then do something else," slap yourself.
Many programmers claim that the use of this method can be a sign of poor OO design yet it can be really useful in some cases just as you noted as in exception handling.

An example can be something like this
class Thing {
public boolean equals(Thing other) {
return something;
}

public boolean equals(Object other) {
return other instanceof Thing
&& equals((Thing)other);
}
}
The use of instanceOf here is useful and advisable since it allows catching a ClassCastException.

The instanceOf() becomes dangerous and a sign of bad design when used in something like this:
if (ref instanceof Thing)
...
else if (ref instanceof Ding)
...
else if (ref instanceof Cosa)
...
else
throw new ResException(...);
In Java and when writing dynamic including on-the-fly classloaders, and mobile code it becomes more and more useful. For example, you developed a plugin architecture based on bytecode, and you want to make sure that the class provided actually implements the correct interface. In this case using instanceOf() instead of using the traditional runtime comparison is considered better.
What are the different types doing together in the first place?
Type inheritance means that objects should share behavior. If they don't, then they should not inherit from the same interface (or extend the same base).

Almost all switches based on type that continue processing on the said object could be solved by calling a virtual function (also called dynamic dispatch).

The only reason you'd really want to do an instance of (or get a value_type property back) is when you'd need to micro-optimize
(which good practice dictates that it must be profiled as the bottleneck;
will almost never happen in server-side web applications or on event driven windowed application).
Based on the type you can then factor out (in real time) the delegation to the function (in .NET environment, it is already a single VM instruction, but it could be slower than other instructions that directly reference the required function) that should be called using some kind of reflection (I think this is impossible in C++, but it could be the case in C# or Java or some other interpreted language - in which performance concerns are already mute).
@Ayman: Why are you comparing two Things in the first place. I think your examples only shows that instanceof is useful when you have already made higher level mistakes or the language itself is flawed (the case is, Java is indeed flawed when it comes to type systems, especially with the arrays and the conversion casts between them).

The correct behavior would have been in the case of a generic/template which automatically does the type comparison in the like of: equal(T &ref), where T is the generic/template parameter.

The combination of type branching and inheritance usually is a red flag that the programmer is trying to express generic contracts rather than sharing common behavior.
The statement: Every instance of a derived type from Thing should be comparable with other instances of the same derived type is translatable into a generic/template rather than inheritance+type-checking.

Hope it makes sense.
This has been an ongoing issue for ages. The problem is hardly related to bad OO design, it's more in tune with whether or not you should let the flow gracefully throw an exception or whether you should manually control it.

It's quite common in event handling scenarios.

P.S.: Yes, OOP Purists would bitch alot about the use of instanceof.
@xterm: You are underplaying the importance of the issue by the usual unscientific approach that plagues software engineering that is: "it works either way" and "everything has its pros and cons", however I believe that is akin to resulting in bad arbitrary architectures.
In an object oriented context, this question is the epitome of all questions. It is the analogue of using a for loop using an integer i in a functional programming language.

The question is put in the strongest form as such:
Is there a programming problem that would require the use of run-time type information to branch onto different behaviors (which includes raising exceptions)?
My answer for that is that if any language does require you using those techniques, then it is by design flawed as to its sticking to the object oriented paradigm.

Proper handling of these problems would move the type checking from run time to compile time. We all know what feeling it gives us the programmers when an error comes out at a random machine running our program complaining of an unhandled type mismatch exception. It's much better to have the program fail at compile time.
It's quite common in event handling scenarios.
There is no reason that a single event handler should receive multiple types of events and branch on that instead of having different strongly typed event handlers. It's bad design to wire different event signals to the same slot if they require different behavior.

I am afraid this is not a purist problem as you have put it, instead is a matter of good architecture.
arithma wrote@xterm: You are underplaying the importance of the issue by the usual unscientific approach that plagues software engineering that is: "it works either way" and "everything has its pros and cons", however I believe that is akin to resulting in bad arbitrary architectures.
"It works either way" is acceptable in the 21st century with the current state of hardware where the millisecond you would be saving by choosing the most "Optimal" way does not matter. The use of instanceof extends beyond the pushing the design into a bad architecture.
In an object oriented context, this question is the epitome of all questions. It is the analogue of using a for loop using an integer i in a functional programming language.
So it's a matter of being Pure within the paradigm you're programming in.
The question is put in the strongest form as such:
Is there a programming problem that would require the use of run-time type information to branch onto different behaviors (which includes raising exceptions)?
Again, it's a matter of how much effort is going to be put in order to accomodate the behavior you would be using "instanceof" for, in the object oriented context. If i'm going to have to implement my version of the object's blueprint for every single class that is available JUST to adhere to the OO paradigm, then i'm directly increasing the effort that i'm putting in to solve my problem, as well as the size of my application, just so i can make a few happy. Though notice the contradiction i'm creating based on my previous point concerning the 21st century. See the dilemma ?

The issue here is, not to overuse it.
My answer for that is that if any language does require you using those techniques, then it is by design flawed as to its sticking to the object oriented paradigm.
Based on the nature of instanceof, there's no language that has instanceof, or a similar construct, that cannot solve the problems using plain old OO tricks. But on a side note, languages aren't flawed, programmers are.
Proper handling of these problems would move the type checking from run time to compile time. We all know what feeling it gives us the programmers when an error comes out at a random machine running our program complaining of an unhandled type mismatch exception. It's much better to have the program fail at compile time.
It is definitly much better to move the errors at compile time, but at the cost of the increased effort you're putting in to deal with the problem in an object oriented manner.
There is no reason that a single event handler should receive multiple types of events and branch on that instead of having different strongly typed event handlers. It's bad design to wire different event signals to the same slot if they require different behavior.
And yet, instanceof is overused in this matter.
I am afraid this is not a purist problem as you have put it, instead is a matter of good architecture.
How is enforcing a good architecture at the cost of increasing effort not a Purist thinking?


The real question that you guys should ask is:

What is cheaper in terms of performance? condition or exception handling?


P.S: I wrote this post at 7.30am before having coffee, i'll revisit it later if it needs changing.
to further elaborate, concerning the case that Ayman provided, what would be the most optimal way of doing what he mentioned? Would this be more performant?
public boolean equals(Object other) {
try{ return equals((Thing)other) } catch { return false; }
}
Technically speaking, even the above is incorrect since you can avoid this problem by simply using generics, but since we're just taking it as an example...

Moreso, in terms of what problems might need instanceof as solution you can consider for example that you're building a forms wizard where you're highlighting the number of occurences of a certain control, at which point your statistical search requires you to define what type of control you're searching for. The "proper" way as you would put it would be to have PRE-defined factory that is containing the controls and you would build a parent that highlights the common behavior including the occurence of every type of control that is available. Then again, would that be simpler than just doing?
long count(Type t){
long mycounter = 0;
foreach(var c in formControls)
if(c is t){ mycounter++ }
return mycounter;
}
Or maybe even by using some language features:
long count(Type t){
return formControls.find { c => c is t }.count();
}
Let's be perfectly reasonable here, if you're using instanceof (or any similar construct) and you're going to have to change quite alot to get rid of it, then just use it.

Effort vs Time
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