Mega Search
23.2 Million


Sign Up

Make a donation  
Using interfaces  
News Group: embarcadero.public.delphi.oodesign

Hi,

many of my business objects implement the interface ICommentOwner. I'm not sure, where I should type
cast:

Version 1:

  procedure ShowComments(AOwner: ICommentOwner);

usage

  ShowComments(MyItem as ICommentOwner);


Version 2:

  procedure ShowComments(AOwner: IInterface);

usage
  
  ShowComments(MyItem);


the implementation in version 2 would look like this


procedure ShowComments(AOwner: IInterface);
var
  co : ICommentOwner;
begin
  if not Supports(AOwner, ICommentOwner, co)
    then Exit;
  ...
end;


The problem is, that in any case I will get runtime errors only if I use my ShowComments() method
with an item, that does not implement ICommentOwner. And I would like to have compiler errors.

cu Christian

Vote for best question.
Score: 0  # Vote:  0
Date Posted: 8-Sep-2014, at 12:56 AM EST
From: Christian Kaufmann
 
Re: Using interfaces  
News Group: embarcadero.public.delphi.oodesign
Christian Kaufmann wrote:

> Hi,
> 
> many of my business objects implement the interface ICommentOwner.
> I'm not sure, where I should type cast:
> 
> Version 1:
> 
>   procedure ShowComments(AOwner: ICommentOwner);
> 
> usage
> 
>   ShowComments(MyItem as ICommentOwner);
> 
> 
> Version 2:
> 
>   procedure ShowComments(AOwner: IInterface);
> 
> usage
>   
>   ShowComments(MyItem);
> 
> 
> the implementation in version 2 would look like this
> 
> 
> procedure ShowComments(AOwner: IInterface);
> var
>   co : ICommentOwner;
> begin
>   if not Supports(AOwner, ICommentOwner, co)
>     then Exit;
>   ...
> end;
> 
> 
> The problem is, that in any case I will get runtime errors only if I
> use my ShowComments() method with an item, that does not implement
> ICommentOwner. And I would like to have compiler errors.
> 

If you use version 1 and pass an object reference to it, not an
interface reference, the compiler is smart enough to extract the
interface reference from the object reference, and it will complain if
the object does not implement the interface in question. The interface
needs to have a GUID for this to work.

Unfortunately this scheme is a bit problematic if the lifetime of your
objects is controlled by reference counting. In this case you
frequently don't have an object reference to pass, only interface
references. The compiler cannot reliably figure out whether a given
interface reference belongs to an object that also implements a
specific other interface.



-- 
Peter Below (TeamB)

Vote for best answer.
Score: 0  # Vote:  0
Date Posted: 8-Sep-2014, at 10:07 AM EST
From: Peter Below