[Gambas-user] MyObject.Property vs MyObject.Variable

Bruce Bruen bbruen at ...2308...
Mon Jun 20 10:37:17 CEST 2011


On 20/06/11 15:20, Demosthenes Koptsis wrote:
> Hi list,
>
> i study the objects these days and i saw that we can declare PUBLIC VARS
> in a class and also PROPERTIES.
>
> So we can have code like
>
> PUBLIC X AS Integer
> cThing.X
>
> or
>
> PROPERTY X AS Integer
> cThing.X
>
> - I understand that a property is shown at Properties List in IDE and a
> Vars not.
> - Properties need READ/WRITE functions, Vars not.
>
> Are any other differences about them in programming?
>
>
>    
Hi,

Very quickly off the top of my head.

1) Properties are overrideable. So you can "fake" protected attributes, 
as in

CLASS base
PROPERTY VeryDangerous as Float
...

CLASS child
INHERITS base
PROPERTY VeryDangerous as Float

PRIVATE FUNCTION VeryDangerous_Read() as Float
     RETURN 0
END

PRIVATE SUB VeryDangerous(Value as Float)
     Error.Raise("BANG! Don't Ever try to set this property again")
END


2) With properties you can add validation

PROPERTY Age as Integer

PRIVATE FUNCTION Age_Write(Value as Integer)
     IF 0<=Value<=100
        $myAge=Value
      ELSE
         Error.Raise("Attempt to set idiotic value for Age")
     ENDIF
END

3) Properties can implement business rules on related attributes

PROPERTY Income as Integer

PRIVATE FUNCTION Income_Write(Value as Integer)
     $myIncome=Value
     SELECT CASE $myIncome
         CASE <20000
             $myCreditRating=0
         CASE <50000
             $myCreditRating=1
         CASE <100000
             $myCreditRating=2
         CASE ELSE
             $myCreditRating=3
     END SELECT
END

(try doing that with a public var!)

4) Generic Public Vars Create Bugs!
     CLASS x
         PUBLIC Obscure as Variant

     CLASS y
         myX.Obscure="Hello Sailor"
....

....
         MyIncome=200 * MyX.Obscure

(contrived, but you'll get my drift.)

5) Properties can be Read Only!

(and therefore can represent derived attributes.)

PRIVATE FUNCTION WeeklyPay_Read() as Float
     RETURN $myWage * $myHoursWorked
END

6) Someone check this!  Public vars are values, properties are references

ted





More information about the User mailing list