Accessing Succinctly

Tagged:  •  

There are times when you have code that looks like this:


Object subclass: MyNewClass [
    | foo bar baz traz bif |

    foo     [ ^ foo ]
    bar     [ ^ bar ]
    baz     [ ^ baz ]
    traz    [ ^ traz ]
    bif     [ ^ bif ]

    foo: aFoo   [ foo := aFoo ]
    traz: aTraz [ traz := aTraz ]
    baz: aBaz   [ baz := aBaz ]

    myMethod [
        "Do something with all of those instance variables"
    ]
]

This may not fully express the problem, but the "code smell" is that you
end up having to write some sort of accessor methods for each instance
variable that you need to use outside of the class. I have made vi
macros for doing this, but it still lines of code that have to be
maintained.

What would be nice if we could just write something nice and short.
Like this:


Object subclass: MyNewClass [
    <readers: 'bar bif'>
    <accessors: 'foo traz baz'>

    myMethod [
        "Do something with all of those instance variables"
    ]
]

With the following extension to ClassDescription you can. It is
slightly inspired by Ruby's accessor definition. And it makes things so
much more readable when you're writing code in a text editor. I
generally just keep this bit of code in a file to fileIn:.


"Extensions for making writing classes with accessors a bit less verbose"

ClassDescription extend [

    accessors: aString [
        self readers: aString.
        self writers: aString.
    ]

    readers: aString [
        aString substrings do: [:ivar |
            (self allInstVarNames includes: ivar asSymbol)
                ifFalse: [ self addInstVarName: ivar ].
            self createGetMethod: ivar.
        ]
    ]

    writers: aString [
        aString substrings do: [:ivar |
            (self allInstVarNames includes: ivar asSymbol)
                ifFalse: [ self addInstVarName: ivar ].
            self createSetMethod: ivar.
        ]
    ]

]

I don't like very much the automatic declaration of instance variables, but the idea is cute.

You can put the code in ~/.st/pre.st and it will be loaded whenever you create an image.

Syndicate content

User login