Do you ever use reflection instead of OO?

A

Aaron Fude

Hi,

I know I'm taking a chance posting a question like this on a java
newsgroiup...

There a lot of well known advantages to OO, but I have recently
started using the java reflection to take care of many simpler
situations. It gives up some of the advantages of OO, but saves a few
imports, the need for external libraries in some contexts and offers a
few other advantages.

For example, suppose I'm writing a library for producing HTML pages,
and my Table class has an Object obj in one of its cells. Then to
render it to HTML it could use the following pseudo code:

if (hasMethod(obj, "toHTML"))
print(callMethod(obj), "toHTML"));
else
print(obj.toString());


The OO alternative would be to create an interface "HTMLable", but the
above approach saves the user from having to implement that on every
type of object that he might want to stick into a table. As another
alternative, the Table code could use, if (instanceof HTMLable), but I
feel that that is neither here nor there.

How do feel about my "OO crime" for simple situations?

Thanks,

Aaron
 
S

Stefan Ram

Aaron Fude said:
if (hasMethod(obj, "toHTML"))
print(callMethod(obj), "toHTML"));
else
print(obj.toString());
The OO alternative would be to create an interface "HTMLable", but the

Object oriented languages (like Smalltalk or Lisp) do not
necessarily have the concept of »interface« at all. They lack
Java's static type system and, therefore, they do not need
interfaces. So, your idea of »OO« seems to be restricted to
Java's interpretation of »OO«. In Java, reflection is used to
add some of the dynamics to Java that object-oriented
languages have right from the start.

When an object does not have a »toHTML« operation, you can not
use »toString« instead because it might evaluate to a string
like "<" that might result in an HTML document that is not
well-formed. There is no way to get an HTML representation
from an object that is not aware of HTML.

Your code is not object-oriented, but this is not because it
does not use an interface or because it uses reflection. It is
not object-oriented because it uses a type-branch instead of
polymorphism. To implement polymorphism in Java, sometimes an
interface is used. So this has to do with interfaces only
indirectly.
 
M

Mark Space

Aaron said:
The OO alternative would be to create an interface "HTMLable", but the
above approach saves the user from having to implement that on every
type of object that he might want to stick into a table. As another

Well, no.

It's easy in Java to pass interfaces without actually implementing that
interface on any object.

public class TestHtml {
public void main( String ... args ) {
Set s = new HashSet();
s.addAll(Arrays.asList(
"one two three four five six seven".split(" ")));

Htmlizer( new HtmlTableIface() {
public String toHtml() {
return "<code>"+s.toString+"</code>";
}
} );

}

void Htmlizer ( HtmlTableIface h ) {
System.out.println( h.toHtml() )
}
}

interface HtmlTableIface {
String toHtml();
}


I didn't compile that, but you get the idea. To pass an object to a
method that takes an interface, just wrap the object in an anonymous
class. This isn't always the best, but it works for "simple situations."

In general, you want to ensure intent. Require interfaces because it's
better to push some of the work off to the caller. In your example, you
could simplify your reflection just to this:

print( obj.toString );

And then just provide an appropriate toString method for all objects.

public class MyHtmlTableEntry {
public String toString() {
return "<code>"+...+"</code>";
}
}
 
M

Mark Space

Lew said:
If you are writing a web app, another good way is to use JSP and EL:

<td>object:</td><td>${usefulThing}</td>

Since "to HTML" is a very widespread need, there exist a number of
standard ways to do it.

Good point. When I first read Aaron's post, I thought he was talking
about HTML display in a Swing JTable. I see he's probably talking about
actually emitting HTML to a data stream. Not my favorite way of doing
things, but I guess it might be needed sometimes.
 
A

Arne Vajhøj

Aaron said:
I know I'm taking a chance posting a question like this on a java
newsgroiup...

There a lot of well known advantages to OO, but I have recently
started using the java reflection to take care of many simpler
situations. It gives up some of the advantages of OO, but saves a few
imports, the need for external libraries in some contexts and offers a
few other advantages.

For example, suppose I'm writing a library for producing HTML pages,
and my Table class has an Object obj in one of its cells. Then to
render it to HTML it could use the following pseudo code:

if (hasMethod(obj, "toHTML"))
print(callMethod(obj), "toHTML"));
else
print(obj.toString());


The OO alternative would be to create an interface "HTMLable", but the
above approach saves the user from having to implement that on every
type of object that he might want to stick into a table. As another
alternative, the Table code could use, if (instanceof HTMLable), but I
feel that that is neither here nor there.

How do feel about my "OO crime" for simple situations?

I would go for HTMLable interface in this case.

Reflection is to be used for cases where interface is not possible.

Arne
 
D

Daniel Pitts

Lew said:
Generally, OP, reflection adds complexity to a solution, and reduces
safety.

I don't have enough context about your problem to presume to judge your
solution. Reflection exists as a tool because it is sometimes useful,
more useful than other available solutions. Like many powerful tools,
reflection is subject to abuse, arguably more at risk for worse
consequences than other tricks of the trade.

In the end, the best advice is to reflect responsibly, and don't blame
the knife if you find its edge too sharp.
I've written a bit about reflection.
<http://virtualinfinity.net/wordpres...angers-of-reflection-or-put-down-that-mirror/>

My conclusion is that reflection should be used in well tested framework
code, not application/business code.
 
A

Aaron Fude

Hi,

Thanks to all who replied and the responses are all very interesting.
I think I need to explain my question a little better. I guess I am
not asking about OO and the dangers of abusing reflection are obious
to me. Also, toHTML is just an example, I am not actually doing
anything html related. But sticking with that example, suppose I go
with polymorphism. There are several _small_ disadvantages to using
polymorphism, but they add up.

1a. HTMLable may be one of very many things that the libary does, yet
the caller which may be an applet, needs to drag that .jar around with
it.
1b. The calling application becomes married to the library containing
HTMLable.
2. Wrapping leads to bulky code. What would Mark's suggestion do to
code
table.add(new Date()).add(new Person()).add("Male").add(new
Address(...)).add(3.0);
where Address has a toHTML.
3. Having to import org.address.webstuff.create.html.* is also "bulky"
especially in jsp contexts.

For these three reasons (I thought I had more) I leaning towards
reflection where it is not dangerous. (Again, I'm not doing any html.)

PS: It's nice to get a reference to Lisp. My first and favorite
language remains Scheme.
 
S

Stefan Ram

Aaron Fude said:
1a. HTMLable may be one of very many things that the libary
does, yet the caller which may be an applet, needs to drag that
.jar around with it.

Then so it be. This is designed this way in Java.

If you want to go by automobile, you need to drag a motor,
tires, and tank with you, and possibly three empty seats.
If you start to rebuilt the car so that you can go without
them, the result usually will be worse, and you will not
reached your destination in time.
PS: It's nice to get a reference to Lisp. My first and favorite
language remains Scheme.

Alan Kay coined the term »object-oriented« in 1967.
In 2003, he wrote about it:

»OOP to me means only messaging, local retention and
protection and hiding of state-process, and extreme
late-binding of all things. It can be done in Smalltalk
and in LISP. There are possibly other systems in which
this is possible, but I'm not aware of them.«

http://www.purl.org/stefan_ram/pub/doc_kay_oop_en
 
T

Tom Anderson

Alan Kay coined the term »object-oriented« in 1967.
In 2003, he wrote about it:

»OOP to me means only messaging, local retention and
protection and hiding of state-process, and extreme
late-binding of all things. It can be done in Smalltalk
and in LISP. There are possibly other systems in which
this is possible, but I'm not aware of them.«

I guess nobody had shown poor old Alan Python at that point.

tom
 
T

Tom Anderson

Thanks to all who replied and the responses are all very interesting. I
think I need to explain my question a little better. I guess I am not
asking about OO and the dangers of abusing reflection are obious to me.
Also, toHTML is just an example, I am not actually doing anything html
related. But sticking with that example, suppose I go with polymorphism.
There are several _small_ disadvantages to using polymorphism, but they
add up.

1a. HTMLable may be one of very many things that the libary does, yet
the caller which may be an applet, needs to drag that .jar around with
it.
1b. The calling application becomes married to the library containing
HTMLable.
2. Wrapping leads to bulky code. What would Mark's suggestion do to
code
table.add(new Date()).add(new Person()).add("Male").add(new
Address(...)).add(3.0);
where Address has a toHTML.
3. Having to import org.address.webstuff.create.html.* is also "bulky"
especially in jsp contexts.

For these three reasons (I thought I had more) I leaning towards
reflection where it is not dangerous. (Again, I'm not doing any html.)

Speaking as someone who left java for python quite some time ago, this
makes a lot of gut-level sense to me. But still, the java way is
polymorphism, static typic, etc.

Plus, i think your points fail a bit:

1a. If you're implementing an interface, and what looks like a callback
interface in particular, from a package, you're presumably depending on
that package anyway, right? If you don't need WebStuff's
convert-objects-to-HTML code, why are you using its HTMLizable interface?
Why not write your own?

1b. Not sure i understand this point. Again, if you're not using the
package, don't use its interface. If you are using the package, you're
married to it anyway. This is true even in an untyped language. Unless
there is a plug-compatible alternative librrary, but then you can switch
easily in a typed language too.

2. Is Person a HTMLizable? If so, everything works. If not, you probably
don't ever get the address as HTML - but you don't your way either. Unless
you're tree-walking through objects' fields? That sounds like a bad idea.

3. I don't find imports a problem in the slightest [1]. There are always
other harder problems to deal with [2]. And don't write JSPs!

I guess a point is that in an untyped language, it's easier to have
informal interfaces, what Smalltalk might call protocols. So, even though
nobody formally specifies an HTMLizable interface, if the idea of having a
toHTML method catches on, you can use it on random third-party objects and
get sensible behaviour. I think this is a minor point - generally, when
you're depending on somebody else's class to do something, it's because
they're following the same specification as you, and that means someone
has written a specification, and could have made the relevant interfaces
available as a very lightweight package (like the servlet API JAR).

tom

[1] Particularly when using Eclipse.

[2] Particularly when using Eclipse.
 
A

Aaron Fude

2. Is Person a HTMLizable? If so, everything works. If not, you probably
don't ever get the address as HTML - but you don't your way either. Unless
you're tree-walking through objects' fields? That sounds like a bad idea.

You are saying that everything works, but how can you add(2.0) if
Double is not HTMLizable?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top