Under The Hood2
T decode(BitBuffer buffer, Resolver resolver, Builder builder)throws DecodingException;int getSize(Resolver resolver);Expression<Integer, Resolver> getSize();CodecDescriptor getCodecDescriptor();Class<?>[] getTypes();Class<?> getType();}
The
decode(BitBuffer, Resolver, Builder)
is obviously the operation that will decode datafrom the
BitBuffer
into an instance of
T
.The
Resolver
allows the
Codec
to resolve references used in Preon annotations.The Codec interface is the interface implemented by objects that are able to decode data from aBitBuffer and to encode data into a BitBuffer
1
. In addition to that, the Codec needs to be able tomake some sort of prediction on the number of bits occupied by the encoded data. And last but notleast, the Codec needs to be able to return a CodecDescriptor, used for rendering documents with adescription of the Codec.When I just said that Codecs are capable of decoding data from a BitBuffer, you could have actuallyread 'decoding an object from a BitBuffer'. Codecs are associated to a single type, and are expectedto return only a single instances of that type from the BitBuffer.In many cases, your objects will hold references to many other objects. Does that mean that a singleCodec needs to be able to recursively traverse the object graph and understand how to decode eachof the individual members of the objects that it encounters?The answer to that question is both yes and no. "Yes", since whenever you invoke decode on theCodec, it needs to be able to reproduce all objects that are referenced by the object that is goingto be returned. "No", since the Codec does not have to understand all of that itself. It can simplydelegate to other Codecs, one for every type of attribute it encounters.If you are decoding an object, you
could
actually use the Codec interface directly. If you create aninstance using the
Codecs
class, they just magically know what to do. We just learned that Codecsconstructed like this, will most likely delegate their work to other Codecs, which in turn will mostlikely delegate their work to other Codecs, and so on and so forth. This way, the Codec both
hides
achain of responsibility, but is also able to act as a
link
inside a chain of responsibility.
2CodecFactory
The previous section ended with stating that a single Codec most likely delegates to other Codecs,which in turn delegate to other Codecs, etc. Obviously, each Codec has to be constructed before itcan be used. All of these instances are created as a result of the create() method on Codecs. But howdoes the Codecs class know which ones to create?As you might have already have guessed by its name, it is of course the CodecFactory. TheCodecFactory a single operation, that is expected to be able to return Codec from the context passedin, or return
null
.
1
The latter is currently not supported yet, but it's not unlikely that it's going to be implemented in the future.
Add a Comment