Thread Tools Display Modes
Prev Previous Post   Next Post Next
05/19/14, 03:06 AM   #1
zgrssd
AddOn Author - Click to view addons
Join Date: May 2014
Posts: 280
Post The getset (gs) pattern

Ever since I started learning the WPF GUI System for .NET I have become a big friend of having get and set functions instead of directly exposed fields. In .NET get&set have been combined into the (almost entirely synrax sugar) construct of properties wich make setting them up a breeze.
They allow stuff like Validation and Change Notification to be in one place (wich in turn really simplifies GUI programming). The only thing you have to keep in mind are to never write the backing field directly (especially in the code that contains the property/get & set).

Latest when you work with LibAddonMenu you need a getter and setter too. So my first ones looked like this:
Code:
--Version 1, conventional get and set
local function getSomeValue()
    return SomeValue
end

local function setSomeValue(value)
    SomeValue = value
end
The I realised that I might be able to fold both abilites into a single function in lua, a getsetter or "gs":
Code:
--Version 2
local function gsSomeValue(value)
    if (value ~= nil) then
        SomeValue = value
    else
        return SomeValue
    end
end
As paramters are filled with up with nil if nothing is specified "local value = SomeValue()" would get me the value while "SomeValue(value)" would set it.
This has one disadvantage though: nil values are impossible to set anymore (wich may be a good or bad thing, depending on case).

After some thinking I realised that with Input Validation a immediate check of the real value would be needer after every set. So I put the return outside of the if to avoid having to make an extra function call:
Code:
--Version 3
local function gsSomeValue(value)
    if (value ~= nil) then
        SomeValue = value
    end
    return SomeValue
end
Wich can be used like
Code:
local value = --some String input that has to be parsed in the setter
value = gsSomeValue(value)
Version 2 and 3 work well with LibAddonMenu (you just drop the same reference into both get and set field). But I have not checked it with all Elements that need the pair (if some of them try to set nil it would break down).

Last edited by zgrssd : 05/19/14 at 03:09 AM.
  Reply With Quote
 

ESOUI » Developer Discussions » General Authoring Discussion » The getset (gs) pattern


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off