I wanted to ask few questions regarding this approach, also as AHK good practises.
1. Should I check variable type & other conditions in setters?
Here's a sample method:
Code: Select all
setWidth(width)
{
if !(width is "integer" && width > 0) ; checks if passed argument is an integer and is bigger than 0
throw Exception("Argument is not integer or the value is smaller than 1.") ; if it's not - throw an exception
this.width := width ; assign the value to object's property
return true ; return... something. See next question.
}
2. What should I return in the setter?
Look at the sample above - what should I return?:
a) true, because the method succeed. Probably not, because if it wouldn't - exception is thrown anyway.
b) width (the argument)
c) this.width (the propery, after assigning new value)
d) this.getWidth() (use getter method)
e) this (class instance itself)
I think getter makes most sens, just in case there's extra logic in it.
3. Should I use setters in constructor?
Code: Select all
__New(width)
{
this.setWidth(width)
}
4. Maybe instead of this all, I should use __Get and __Set? Pros and cons, why yes or not.
Looks like saving afford on making methods that can be omitted anyway, thus automatically answer two previous questions. The thing is, I would probabably need to if/else each propery within this method.
5. What should I do if the argument doesn't meet requirements? (Sticking to doing this in setter)
Sticking to the first code snippet - is throwing an exception there valid in first place? What is the best practise? Specifically, I want to use some kind of general purpose messages, like "Invalid argument type: excepted 'integer', received 'string'", without having to have them inline everywhere or a global variable.
As far I can tell, Exception() is basically a function, that returns associated array with predefined keys to fill the throw error.
I was thinking about creating a custom class for exceptions and call it by either throw new MyClass("stuff") or throw MyClass.__New("stuff"). Why custom class? I could use class static for the messasing mentioned above.
Thanks for your input.