You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@struts.apache.org by Carl Smith <cc...@yahoo.com> on 2005/08/10 16:47:33 UTC

Why interface

In Java/J2EE community, it seems that a lot of experienced developers tend to use a lot of interfaces, however, a lot of junior developers ignore using interface. I am not sure why interfaces seem to be favorite to some experienced developers. Can some one explain this?Can you give examples where an interface is preferred?

Thanks.

 



__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 

Re: Why interface

Posted by Dakota Jack <da...@gmail.com>.
You missed the point, Adam.  No one is so daft as to be saying that
having an interface makes the implementations of that interface less
than specific implementations.  The point is that you can switch them
out.

On 8/11/05, Adam Hardy <ah...@cyberspaceroad.com> wrote:
> Dave Newton on 10/08/05 16:25, wrote:
> >
> > (4) Dependency Injection/Configurability.
> >
> > Classes that implement interfaces can be instantiated at runtime
> > allowing for config-file-level application modification. This can
> > translate into HUGE wins over the life of an application.
> >
> > As a recent thread on DTOs pointed out having multiple implementations
> > of CRUD actions can be REALLY handy: I have an existing application that
> > uses Torque for persistence. I refactored out a lot of the typical CRUD
> > stuff into an interface, implemented a default Torque CRUD base class,
> > whung up a configuration file, and can now perform the most general CRUD
> > actions on my DB by giving a tablename String.
> >
> > When I migrate this to Hibernate "all" I'll need to do is implement a
> > generic Hibernate CRUD base class (and perhaps some specializers for
> > particular tables/OMs), change the class names in my config file, and my
> > application will work as before without having to change any of my Actions.
> 
> Hold on a mo', you've lost me there. Haven't had my coffee yet -
> 
> if you have a whole package of DAOs (doing the CRUD stuff), all
> inheriting the Torque base class which implements your DAO interface,
> and you change over to Hibernate, then surely you must write a whole new
> package of DAOs for Hibernate, not just the base class?
> 
> Obviously though the business tier is coded to the interface so is
> unaffected.
> 
> Correct me if I'm wrong,
> 
> Adam
> 
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
> For additional commands, e-mail: user-help@struts.apache.org
> 
> 


-- 
"You can lead a horse to water but you cannot make it float on its back."
~Dakota Jack~

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


Re: Why interface

Posted by Dave Newton <ne...@pingsite.com>.
This got long-ish as I'm partially thinking out loud about this 
work-in-progress. Sorry. The whole thing got blown out of proportion 
late last week and I shouldn't be doing this with Struts at all, I 
think. More of a Dave's Java Playground project, this.

Adam Hardy wrote:

> if you have a whole package of DAOs (doing the CRUD stuff), all 
> inheriting the Torque base class which implements your DAO interface, 
> and you change over to Hibernate, then surely you must write a whole 
> new package of DAOs for Hibernate, not just the base class?

The DAO stuff is written by Hibernate (I might not be using the right 
acronym, I suppose), and I haven't fully refactored my classes yet, but 
in a nutshell:

public interface ICrudDelegate {
    // CRUD operations
    public Object getById(final String omClass_, final String id_);
    public void deleteById(final String omClass_, final String id_);
    public List getList(final String omClass_);
    public void saveOm(final Object om_);
    public void updateOm(final Object om_);
    // CRUD method retrievers
    public Method getUpdateMethod(final String omClass_);
    // [... plus others like that ...]
}

So I have a DefaultTorqueCrudDelegateImpl class that does all the Right 
Things for Torque. I also have a DefaultHibernateCrudDelegateImpl class 
that does all the Right Things for Hibernate (although I suspect I have 
a fair chunk of refactoring yet to do).

Actual it's more complicated than this, as I have a single Action that 
does all the CRUD based on Ruby on Rails-style URLs : 
/${prefix}/${table_name}/${command}[/${id}] and have a IHandleCommands 
interface:

public interface IHandleCommands {
    public boolean isCommandHandled(final String cmd_);
    public Object handleCommand(final String cmd_, final Map cmdParams_)
                  throws UnsupportedOperationException, 
CommandHandlerException;
    public Class[] getHandlerSignature();
    public Object[] getHandlerParams(final Map cmdParams_);
}

and currently a single implementation, StrutsCommandHandler. My single 
CRUD action packages up relevant arguments (mapping, form, request, 
response, my crud config (see below), etc) into the Map and hands it off 
to the StrutsCommandHandler, which instantiates and uses the delegates 
as described above.

So a chunk of my config file might look like this:

<crud-mappings>
  <crud prefix="Admin">
    <form tableName="Event"
          omDelegate="com.pingsite.delegates.DefaultTorqueCrudDelegateImpl"
          omClass="com.pingsite.om.Event"
          />
    <form tableName="AnnouncementType"
          
crudHandler="com.pingsite.crud.handlers.AnnouncementTypeCrudHandler"
          omDelegate="com.pingsite.delegates.DefaultTorqueCrudDelegateImpl"
          formClass="com.pingsite.struts.forms.AnnouncementTypeForm"
          omClass="com.pingsite.om.AnnouncementType"
          />
    <form tableName="ProductCategory"
          crudHandler="com.pingsite.crud.handlers.StrutsCommandHandler"
          omDelegate="com.pingsite.delegates.DefaultTorqueCrudDelegateImpl"
          formClass="com.pingsite.struts.forms.ProductCategoryForm"
          omClass="com.pingsite.om.ProductCategory"
  </crud>

  <crud prefix="User">
    <form tableName="AnnouncementType"
          formClass="com.pingsite.struts.forms.UserAnnouncementTypeForm"
          omClass="com.pingsite.om.UserAnnouncementType"/>
  </crud>
 
</crud-mappings>

There are also the typical hooks you'd expect; things before the form is 
displayed (so I can pre-populate dropdowns, etc.), things after the form 
is submitted (like tweaking my form's checkboxes into integers for my 
MySQL Torque stuff), blah blah blah. Except for the generation of JSP 
chunks (currently barely handled by a Ruby script) it's a configuration 
file change to add a table into the CRUD processing system, which is neat.

Totally out of control, though, and I'm not entirely sure I've really 
accomplished anything except get better at design and reflection. It's 
been a VERY interesting exercise, though!

Dave



---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


Re: Why interface

Posted by Adam Hardy <ah...@cyberspaceroad.com>.
Dave Newton on 10/08/05 16:25, wrote:
> 
> (4) Dependency Injection/Configurability.
> 
> Classes that implement interfaces can be instantiated at runtime 
> allowing for config-file-level application modification. This can 
> translate into HUGE wins over the life of an application.
> 
> As a recent thread on DTOs pointed out having multiple implementations 
> of CRUD actions can be REALLY handy: I have an existing application that 
> uses Torque for persistence. I refactored out a lot of the typical CRUD 
> stuff into an interface, implemented a default Torque CRUD base class, 
> whung up a configuration file, and can now perform the most general CRUD 
> actions on my DB by giving a tablename String.
> 
> When I migrate this to Hibernate "all" I'll need to do is implement a 
> generic Hibernate CRUD base class (and perhaps some specializers for 
> particular tables/OMs), change the class names in my config file, and my 
> application will work as before without having to change any of my Actions.

Hold on a mo', you've lost me there. Haven't had my coffee yet -

if you have a whole package of DAOs (doing the CRUD stuff), all 
inheriting the Torque base class which implements your DAO interface, 
and you change over to Hibernate, then surely you must write a whole new 
package of DAOs for Hibernate, not just the base class?

Obviously though the business tier is coded to the interface so is 
unaffected.

Correct me if I'm wrong,

Adam

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


Re: Why interface

Posted by Dave Newton <ne...@pingsite.com>.
Frank W. Zammetti wrote:

>I think it usually comes down to three reasons...
>  
>
I'd add a fourth, although really it's just a result of the reasons you 
mention. But I think it's important enough to warrant attention :)

(4) Dependency Injection/Configurability.

Classes that implement interfaces can be instantiated at runtime 
allowing for config-file-level application modification. This can 
translate into HUGE wins over the life of an application.

As a recent thread on DTOs pointed out having multiple implementations 
of CRUD actions can be REALLY handy: I have an existing application that 
uses Torque for persistence. I refactored out a lot of the typical CRUD 
stuff into an interface, implemented a default Torque CRUD base class, 
whung up a configuration file, and can now perform the most general CRUD 
actions on my DB by giving a tablename String.

When I migrate this to Hibernate "all" I'll need to do is implement a 
generic Hibernate CRUD base class (and perhaps some specializers for 
particular tables/OMs), change the class names in my config file, and my 
application will work as before without having to change any of my Actions.

Business logic will also be unaffected by the persistence mechanism change.

Jython utilities and GUI apps will also run unmodified: I use the new 
Hibernate implementation, use the same config file, and everything is ducky.

I get giddy just thinking about it.

Dave



---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


Re: Why interface

Posted by "Frank W. Zammetti" <fz...@omnytex.com>.
I think it usually comes down to three reasons...

(1) A class can only extend a single class, whereas it can implement
multiple interfaces (Interfaces are Java's version of multiple inheritance
in C).  So, as soon as you get to the point where extending a single class
just isn't sufficient, it's no longer really a choice... well, I suppose
you could push all the functionality up the inheritance tree, but that
gets ugly in a hurry.

Since you can only extend a single class, you want to do so carefully,
kind of like if your in a desert, you don't want to drink your last glass
of water lightly :)  So, if you keep implementing interfaces instead, you
keep that one inheritance path open to you.

It's really *not* the same as multiple inheritance because you aren't
inheriting functionality, but it in a sense leads to the same thing
because you of course have to implement all the methods of the interface,
and presumably you do so in a meaningful way, so in the end you get the
same basic effect.

(2) It allows for polymorphism.  If a given class implements a given
interface, you can treat the class as an instance of the interface.  So,
if you have a Dog class and a Dolphin class and a Lizard class and they
all implement the IHasBabies interface which has a single giveBirth()
method, obviously the method by which each of the classes "gives birth" is
quite different, but all you need to do in your code is:

((IHasBabies)animal).giveBirth();

...and animal can then be an instance of a Dog, Dolphin or Lizard and the
above code doesn't have to change at all.  Note that if there was true
multiple inheritance you'd be able to do the same thing.

You may be asking "well, why not just have Dog, Dolphin and Lizard extent
a HasBabies class"?  Again, it comes back to the multiple inheritance
problem... what if you want to have a class Eats and a class Sleeps and a
class Runs, etc., to encapsulate the common functionality?  You either
have to put all that stuff into the one class that Dog, Dolphin and Lizard
extends, which is ugly, or you get into a situation where there is no
guarantee about the interface each class has... maybe Dog has sleepLong()
and Lizard has sleepShort().  Implementing an interface that describes
sleeping, then one that describes eating, etc., guarantees that each of
the implementing classes exposes the same generic functionality, even if
the specific details are different for each.

(3) Following on the heels of the last paragraph, implementing an
interface is a clean way of saying "ok, this class is guaranteed to have
the following members".  It's a matter of extensibility... imagine when
you have to add another type of animal to the above example... maybe you
want to add an AlienFaceHugger class, which has yet another method of
giving birth (eeewwww!)... if it implements that IHasBabies interface,
then you know it is guaranteed to have that giveBirth() method, even if
you don't know what goes on inside it, and most importantly, this will be
enforced at compile-time.

So, it isn't so much a choice to use interfaces vs. not using them...
there are certain things that you won't be able to do without them in
Java.  Or, at least there are things that you won't be able to do WELL in
Java.

-- 
Frank W. Zammetti
Founder and Chief Software Architect
Omnytex Technologies
http://www.omnytex.com

On Wed, August 10, 2005 10:47 am, Carl Smith said:
>
> In Java/J2EE community, it seems that a lot of experienced developers tend
> to use a lot of interfaces, however, a lot of junior developers ignore
> using interface. I am not sure why interfaces seem to be favorite to some
> experienced developers. Can some one explain this?Can you give examples
> where an interface is preferred?
>
> Thanks.
>
>
>
>
>
> __________________________________________________
> Do You Yahoo!?
> Tired of spam?  Yahoo! Mail has the best spam protection around
> http://mail.yahoo.com


---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


Re: Why interface

Posted by Ulrich Elsner <ul...@gmail.com>.
On 8/10/05, Laurie Harper <la...@holoweb.net> wrote:
> Carl Smith wrote:
> > In Java/J2EE community, it seems that a lot of experienced developers tend to use a lot of interfaces, however, a lot of junior developers ignore using interface. I am not sure why interfaces seem to be favorite to some experienced developers. Can some one explain this?Can you give examples where an interface is preferred?
> 
> Much more importantly than 'because Java doesn't have multiple inheritance'
>   is what Dave's alluding to, that if you code to interfaces the
> implementation can be switched without impact. As a more general example,
> consider if you wrote all your code to use ArrayList and later found, after
> profiling, that you needed to switch to LinkedList for performance reasons.
>   You'd have to update all your code -- including all the clients of all
> the methods that accepted or returned an ArrayList.
> 
> Conversely, if you coded to the List interface, you would only need to
> change the implementation code. All the client code would be unaffected.
> That's Dave's point about being able to switch X for Y with minimal impact.

And to answer the original question to why experienced developers tend
to use interfaces more often than newbies: a seasoned programmer knows
that eventually their code needs to be updated, refactored or otherwise changed.
Hence in the long run, the extra effort it takes to design the
interface will pay off.
The newbie just assumes that he will get it right the first time.

Ulrich

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


Re: Why interface

Posted by Michael Jouravlev <jm...@gmail.com>.
On 8/10/05, Dave Newton <ne...@pingsite.com> wrote:
> Laurie Harper wrote:
> 
> > As a more general example, consider if you wrote all your code to use
> > ArrayList and later found, after profiling, that you needed to switch
> > to LinkedList for performance reasons.  You'd have to update all your
> > code -- including all the clients of all the methods that accepted or
> > returned an ArrayList.
> >
> > Conversely, if you coded to the List interface, you would only need to
> > change the implementation code. All the client code would be
> > unaffected. That's Dave's point about being able to switch X for Y
> > with minimal impact.
> 
> That was a much better example than mine :) I could have typed so much less!

Or even shorter: for polymorphic usage of similar but different classes ;-)

Problem with interfaces is they they are fixed. Once you define an
interface, you have to follow it. Say, you defined (er... I defined ;)
) an CRUD interface and forgot to define crudReset() method. Now even
if crudReset() method is defined in implementing class, it cannot be
polimorphically used for every class implementing CRUD interface.
Bummer.

Interfaces should be designed with much greated attention than regular
class hierarchies. If inteface is extended, then classes using it has
to switch to new interface explicitly.

Michael.

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


Re: Why interface

Posted by Dave Newton <ne...@pingsite.com>.
Laurie Harper wrote:

> As a more general example, consider if you wrote all your code to use 
> ArrayList and later found, after profiling, that you needed to switch 
> to LinkedList for performance reasons.  You'd have to update all your 
> code -- including all the clients of all the methods that accepted or 
> returned an ArrayList.
>
> Conversely, if you coded to the List interface, you would only need to 
> change the implementation code. All the client code would be 
> unaffected. That's Dave's point about being able to switch X for Y 
> with minimal impact.

That was a much better example than mine :) I could have typed so much less!

Dave



---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


Re: Why interface

Posted by Laurie Harper <la...@holoweb.net>.
Carl Smith wrote:
> In Java/J2EE community, it seems that a lot of experienced developers tend to use a lot of interfaces, however, a lot of junior developers ignore using interface. I am not sure why interfaces seem to be favorite to some experienced developers. Can some one explain this?Can you give examples where an interface is preferred?

Much more importantly than 'because Java doesn't have multiple inheritance' 
  is what Dave's alluding to, that if you code to interfaces the 
implementation can be switched without impact. As a more general example, 
consider if you wrote all your code to use ArrayList and later found, after 
profiling, that you needed to switch to LinkedList for performance reasons. 
  You'd have to update all your code -- including all the clients of all 
the methods that accepted or returned an ArrayList.

Conversely, if you coded to the List interface, you would only need to 
change the implementation code. All the client code would be unaffected. 
That's Dave's point about being able to switch X for Y with minimal impact.

In 'text book' terms, extending a base class expresses an IS-A relationship 
where implementing an interface expresses a HAS-A (behaviour) relationship. 
Inheritance is a very over-used language feature; often it's used to 
express a 'has some of the same behaviour as, even if it's semantically 
unrelated' relationship -- i.e. as an implementation convenience rather 
than an expression of model semantics. Use of interfaces can go a long way 
to providing cleaner object models.

Just my 2c...
-- 
Laurie, Open Source advocate, Java geek and novice blogger:
http://www.holoweb.net/laurie


---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


[OT ]Re: Why interface

Posted by DG...@EvergreenInvestments.com.
"Program to an interface, not an implementation." 

#1 principle from GoF.  Here's a recent interview with Erich Gamma: 
http://www.artima.com/lejava/articles/designprinciples.html

-Dennis




Carl Smith <cc...@yahoo.com> 
08/10/2005 10:47 AM
Please respond to
"Struts Users Mailing List" <us...@struts.apache.org>


To
Struts Users Mailing List <us...@struts.apache.org>
cc

Subject
Why interface







In Java/J2EE community, it seems that a lot of experienced developers tend 
to use a lot of interfaces, however, a lot of junior developers ignore 
using interface. I am not sure why interfaces seem to be favorite to some 
experienced developers. Can some one explain this?Can you give examples 
where an interface is preferred?

Thanks.

 



__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 

[OT] Re: Why interface

Posted by Jerry Tan <jt...@dtcc.com>.
At the end of the day, some would say there's really no functional
difference between the two.

But as for a preference for interfaces, well, partly it's due to the
limitation of single inheritance in Java.  Using interfaces provides the
functionality of acting as a derivative of multiple base classes, without
bumping into any of the difficulties or heartache in a language that does
allow true multiple base classes.

Another reason is that using interfaces allows a simpler extension point
that others can use in the future, without necessarily inheriting any of
the other miscellaneous members in a base class that would not actually be
used (which may not have been originally properly scoped in the base).

Defining an interface during a design phase also forces you to think long
and hard about what is the true *core* functionality of the object you're
trying to model, i.e., what are the minimal characteristics that such an
object satisfying this role would require, whether that role is what a
method returns or what it takes as a parameter.

So this process of stripping down some problem domain to its core "verbs",
so to speak, does help streamline the design process somewhat, i.e.,
forcing you to think purely in terms of functionality as these are exposed
through methods, rather than also having to think about how data members
may or may not fit in, or the interaction between these "verbs" and the
data it acts upon, which is something that would come up when you're
thinking of designing something through inheritance of base classes.

HTH, my 2 cents.




                                                                           
             Carl Smith                                                    
             <ccsmith20002001@                                             
             yahoo.com>                                                 To 
                                       Struts Users Mailing List           
             08/10/2005 10:47          <us...@struts.apache.org>            
             AM                                                         cc 
                                                                           
                                                                   Subject 
             Please respond to         Why interface                       
               "Struts Users                                               
               Mailing List"                                               
             <user@struts.apac                                             
                  he.org>                                                  
                                                                           
                                                                           





In Java/J2EE community, it seems that a lot of experienced developers tend
to use a lot of interfaces, however, a lot of junior developers ignore
using interface. I am not sure why interfaces seem to be favorite to some
experienced developers. Can some one explain this?Can you give examples
where an interface is preferred?

Thanks.





__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around
http://mail.yahoo.com


---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org