On Fri, Nov 18, 2011 at 11:11 AM, Christian Schwarz
<[email protected]> wrote:
> In Mina 2 we can add attributes to a session and get them as well.
> Because IoSession#getAttribute(Object
> key) returns Object we always have to remember what attribute type is
> associated with the key and cast the result to the expected type.
>
> Mina 2 example:
> final static Object KEY = new AttributeKey(SourceClass.class,"myKey");
> ...
> session.set(KEY,"myAttribute");
> String attributeValue= (String)session.get(KEY);
>
>
> Instead of using plain Object-keys, the key type should contain information
> about its attributes. The aim is to get type-safe access to attributes.
>
> Assume we have the following new AttributeKey-Class:
> /**
> * @parmeter T Type of the referenced Attribute
> */
> class AttributeKey<T> {
> public TypesafeAttributeKey(Class<T> attributeType, String attributeKey){
> ...
> }
> }
>
> The IoSession should have Attribute related accessors like these:
>
> void setAttribute(AttributeKey<T> key, T value);
> T getAttribute(AttributeKey<T> key);
>
>
> So in Mina 3 the example could look like this:
>
> final static AttributeKey<String> KEY = new
> AttributeKey<String>(String.class,"myKey");
> ...
> session.set(KEY,"myAttribute");
> String attributeValue=session.get(KEY);
>
> These 2 cases won't compile:
>
> session.set(KEY,new Date());
> Integer attributeValue=session.get(KEY);
>
> This pattern would simplify the use of Attributes, because the programmer
> don't have to care about the types and can concentrate on more improtant
> things. In my humble opinion the Objekt keys should be removed at all, i
> don't see the purpose for such unspecific keys.
>
In MINA 3 the attributes methods was modified for avoiding the cast :
/* Session context management */
/**
* Returns the value of the user-defined attribute for this session.
*
* @param name the attribute's name
* @return <tt>null</tt> if there is no attribute with the specified name
*/
<T> T getAttribute(String name);
/**
* Sets a user-defined attribute.
*
* @param name the attribute's name
* @param value the attribute's value
* @return The old attribute's value. <tt>null</tt> if there is no
previous value or if the value is null
*/
<T> T setAttribute(String name, T value);
you do String x = sesssion.getAttribute("mykey");
in place of : String x = (String)sesssion.getAttribute("mykey");
In what you propose in place of
session.setAttribute("mykey",theValue);
you need to do :
AttributeKey<MyType> key = new AttributeKey<MyType>(MyClass.class,"mykey");
session.setAttribute(key,theValue);
Sure it's improving the typing, but does it really simplify the code ?
Julien