Typcasting from a variable?

For questions and postings not covered by the other forums
timmeh
Posts: 18
Joined: Fri Apr 13, 2012 3:12 pm

Typcasting from a variable?

Postby timmeh » Thu Jun 14, 2012 2:51 pm

This is really basic but I'm unsure on how to do it.

Can I typecast with a variable if I dont know what class the object is going to be?
e.g.

Code: Select all

someMethod(obj : Object; member : Class) begin //set the class of obj to be member obj.Member
or is there some setClass() method for objects?
Would really appreciate knowing how to do this!

murray
Posts: 144
Joined: Fri Aug 14, 2009 6:58 pm
Location: New Plymouth, New Zealand

Re: Typcasting from a variable?

Postby murray » Thu Jun 14, 2012 3:38 pm

Usually you will have some idea what class it will be from your design (e.g. it may be one of several subclasses from a common superclass). You can obtain the class of an object by calling the class() method. It is good practice to be as strict as possible with your parameters, as this will help with OO design and with Jade's compile and runtime checking. For example, in your case the parameter could be a superclass type that has the required methods so that typecasting is not necessary. Typecasting to an incompatible class will cause Jade to raise an exception. Also, the lefthand side of any assignment statement must be type compatible with the object it is receiving.
Murray (N.Z.)

torrie
Posts: 92
Joined: Fri Aug 14, 2009 11:24 am

Re: Typcasting from a variable?

Postby torrie » Thu Jun 14, 2012 3:46 pm

You can type cast a variable, for example:

Code: Select all

someMethod(obj : Object) vars aCustomer : Customer; begin aCustomer := obj.Customer;
If the object is a customer, the code above will work, if not then an exception is thrown at runtime as Murray has pointed out.

You can check whether the object is a customer first e.g.

Code: Select all

someMethod(obj : Object) vars aCustomer : Customer; begin if obj.isKindOf( Customer ) then aCustomer := obj.Customer; else // We do not have a customer. endif;
If you're type casting, then you should consider whether you are better to refactor the code and moving the logic onto a method on the Customer class etc.

However there are some times where it's unavoidable. For example, the display row method on the Table class has the following signature

Code: Select all

displayRow( table: Table input; theSheet: Integer; obj: Object; theRow: Integer; bcontinue: Boolean io): String;
Most people will type case the obj variable in the code. In this case you can however update the signature to match the collection being used, e.g.

Code: Select all

displayRow( table: Table input; theSheet: Integer; customerToDisplay: Customer; theRow: Integer; bcontinue: Boolean io): String;
which then avoids the type casting.


Return to “General Discussion”

Who is online

Users browsing this forum: No registered users and 23 guests