#1008 just an idea, related to protection and setters and getters

jessevdam Fri 5 Mar 2010

fantom has nice support for making "custom" setters and getters of which protection can also be changed.

So you can do something like

Int id := 0
{
  public get { echo("get id"); return *id }
  internal set { echo("set id"); *id = it }
}

Which is nice, but when you have list it would be nice you do can the same thing. Which will look like

Int[] ids := [,]
{
  public get|Int index| { echo("get id[$index]"); return ids.get(index) }
  internal add|Int val| { echo("add id"); ids.add(val) } 
  //..others functions
}

In this case only function already present in List may be used.

Doing this in current situation would result in

private Int[] ids := [,]
public Int getId(Int index)  
{
  echo("get id[$index]")
  return ids.get(index)
}
internal Void addId(Int index)
{ 
  echo("add id")
  ids.add(val) 
}

Another related idea would be the allowance of not predefined functions in the type

Int id := 0 
{
  public get { echo("get id"); return *id }
  internal set { echo("set id"); *id = it }
  protected Bool isNull() { return id == 0 } 
}

Int[] ids := [,]
{
  public get|Int index| { echo("get id[$index]"); return ids.get(index) }
  internal add|Int val| { echo("add id"); ids.add(val) }
  public Bool isOk { return ids[0] == 0 && ids[1] == 1 }
}

This is something which begins to look like more a definition of a anonymous class.

These are just 2 ideas. I like the first one. The second one I am not sure about that one. I thinks it is nice to discuss about.

brian Fri 5 Mar 2010

Interesting idea, we've actually kicked a few things around regarding collections.

The design pattern which I would suggest is this:

  • Make readonly or immutable List available
  • Expose add/remove methods appropiate for your class

It is a little bit of boiler plate, but lets you tightly control mutability of your list. But as long as you expose a read-only copy of your list all the crunchy goodness of List for each, map, find, etc is available. The List.ro method is designed to efficiently to support this exact design pattern.

The fwt::Widget class is a perfect example of this design pattern.

Login or Signup to reply.