Thursday, February 19, 2009

Using "protected" as a namespace

I'm a big fan of certain aspects of Object-Oriented software development, one being information hiding. Not in a way that makes it hard to extend classes, but in order to keep the public API as small and neat as possible. That means favouring protected over private, but often I want a read-only or write-only property in the public API, while still supporting binding (or any other processing on set). This can be a problem at compile time when you'd like to be able to use both internally, however. Take the following code snippet of real code:

//----------------------------------
// selectedUser
//----------------------------------

private var _selectedUser : User;

[Bindable("selectedUserChanged")]
public function get selectedUser() : User
{
    return _selectedUser;
}

protected function set selectedUser(value : User) : void
{
    if (_selectedUser == value)
        return;

    _selectedUser = value;
    dispatchEvent(new Event("selectedUserChanged"));
}

//----------------------------------
// Selection callback
//----------------------------------

public function selected(item : Object) : void
{
    if (item == null || displayUsers.contains(item))
        selectedUser = User(item);
}

MXMLC will give us "Error 1000: Ambiguous reference to selectedUser" when we try to compile this code. Namespaces to the rescue! Did you know you can use public, package, protected and private just as you would a normal namespace in most cases? The solution to this particular problem then becomes:

public function selected(item : Object) : void
{
    if (item == null || displayUsers.contains(item))
        protected::selectedUser = User(item);
}

You may note that instead of a protected accessor, I could have cooked up a protected setSelectedUser() function. Which is true, but using the namespace prefix allows me to retain the assignment operator, which I find clearer.

0 comments:

This is

  • Tales of Flex
  • From Brisbane, Australia
  • Opinions on Flex development
  • Tips and FAQs
  • Shameless self-promotion

I am

  • Twitterer
  • Flexcoder
  • Maroon
  • Designer
  • Java lover
  • That loud-mouthed Aussie yob
  • Blogger
  • Problem solver
  • Contributor
  • Cricket Fan
  • Lousy photographer
  • Great cook

I read



Subscribe via RSS to receive updates!