Friday, December 13, 2013

Sapphire 0.7 : List Index Facility

The scalability and performance of some features can benefit from constant time lookup of list entries based on the value of a member property.

A list can have one or more indexes that are created on first request. Once created, an index is shared by all consumers of the list and updates itself automatically. The index can also notify listeners when it changes.

Index<T extends Element>
{
    ElementList<T> list()
    ValueProperty property()
    T element( String key )
    Set<T> elements( String key )
    attach( Listener listener )
    detach( Listener listener )
}

ElementList<T extends Element>
{
    Index<T> index( ValueProperty property )
    Index<T> index( String property )
}

A quick lookup is easy to write.

Task task = repository.getTasks().index( "Id" ).element( "1234" );

Multiple elements that share the same key value can be retrieved as a group.

List<Task> tasks = repository.getTasks().index( "Component" ).elements( "SDK" );

Listening for changes to the index as opposed to the whole list can help reduce the number of times an expensive operation is performed.

Index<Task> index = repository.getTasks().index( "Component" );
List<Task> tasks = index.elements( "SDK" );

Listener listener = new Listener()
{
    @Override
    public void handle( Event event )
    {
        // Do something when the index has changed.
    }
}

index.attach( listener );

...

index.detach( listener );

No comments: