From: DrPi <314@drpi.fr>
Subject: Re: How to check class type ?
Date: Thu, 22 Apr 2021 10:50:22 +0200 [thread overview]
Message-ID: <608138ce$0$32491$426a74cc@news.free.fr> (raw)
In-Reply-To: <s5po26$5fk$1@gioia.aioe.org>
Le 21/04/2021 à 19:40, Dmitry A. Kazakov a écrit :
> On 2021-04-21 19:08, DrPi wrote:
>> Hi,
>>
>> I have the following declarations (just for the example) :
>>
>> type Root is tagged null record;
>> type Root_Ptr is access all Root'Class;
>>
>> type Leaf1 is new Root with null record;
>> type Leaf1_Ptr is access all Leaf1'Class;
>>
>> type Leaf2 is new Root with null record;
>> type Leaf2_Ptr is access all Leaf2'Class;
>>
>>
>> To check if a variable is of type Leaf1_Ptr or Leaf2_Ptr, I do :
>
> That does not make sense, Leaf1_Ptr is not tagged.
>
>> if var'Tag = Leaf1'Tag then
>> ...
>> elsif var'Tag = Leaf2'Tag then
>> ...
>> end if;
>
>
> if Var in Leaf1'Class then
> ... -- Class rooted in Leaf1
> elsif Var in Leaf2'Class then
> ... -- Class rooted in Leaf2
>
>> It works. But is this correct ? Should the test be done differently to
>> suit Ada coding style ?
>
> It depends on the intent. Usually you should never check for the class
> except two cases:
>
> 1. Defensive programming of a downcast:
>
> if X in T'Class then
> declare
> Y : T'Class renames T'Class (X);
> begin
> ...
> end;
>
> Downcasts are by themselves problematic, to be avoided when possible.
>
> 2. Emulation of multiple dispatch.
>
> In most cases you leave all tag checks to dispatch.
>
> This may lead to so-called God-classes when primitive operations migrate
> to the root. E.g. if you had a primitive Foo on Leaf1, but not in Leaf2
> and the purpose of check would be if you could call to Foo, you might
> move Foo as abstract to Root and override it as raising exception in
> Leaf2. Then instead of checking for the tag, you would simply dispatch:
>
> Var.Foo; -- Will raise if not Leaf1
>
> This would be a God-class case.
>
Thanks for the explanations. As always, very instructive.
prev parent reply other threads:[~2021-04-22 8:50 UTC|newest]
Thread overview: 7+ messages / expand[flat|nested] mbox.gz Atom feed top
2021-04-21 17:08 How to check class type ? DrPi
2021-04-21 17:26 ` AdaMagica
2021-04-21 17:33 ` DrPi
2021-04-21 17:48 ` DrPi
2021-04-23 16:13 ` John McCabe
2021-04-21 17:40 ` Dmitry A. Kazakov
2021-04-22 8:50 ` DrPi [this message]
replies disabled
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox