Writing Your Own Mappers

Hydrant comes with a lot of mappers, but there will always be scenarios that Hydrant cannot anticipate. Mappers are the ultimate method to extending the features while still reusing as much as possible with Hydrant.

Before reading this, be sure to read the Mapper protocol and error handling, specifically creating errors.

Thought Process

When writing a mapper, look to do the least amount of work possible. Allow the composition of other mappers to achieve the bigger goal you’re trying to solve:

Even when implementing, feel free to use the existing mappers for implementation details, HYDMapReflectively and HYDMapObject both compose other mappers to achieve their work.

Type-checking (via -[isKindOfClass:]) is a bit more sensitive. You should do type checking to avoid crashing, but strict type checks to specific concrete classes should be considered carefully, because HYDMapTypes can cover those use cases.

Raising Exceptions

While mappers should not raise exceptions for -[objectFromSourceObject:error], it is perfectly acceptable to raise exceptions on mapper construction or creating a reverse mapper for easier debuggability by the consumer of your mapper.

Crafting your Implementation

When creating a new mapper, you should treat the two arguments you receive very carefully:

  • sourceObject can be any value, so be sure that your mapper does not crash or throw exceptions when receiving nil, [NSNull null], and unexpected object types.
  • error is an object pointer that may or may not be specified. Unlike some SDKs, you should nil out the error pointer if there are no errors.

If your mapper returns a fatal error, it is recommended to return nil. Using nil is not enough to indicate errors if parsing a source object to return nil is intended behavior. Don’t return [NSNull null] directly.

Closing Thoughts

Is the mapper you wrote generic? Contribute it back to Hydrant! Make sure it conforms to Hydrant’s design and is tested.

Read the Docs v: latest
Versions
latest
stable
v2.0.0
v1.1.0
v1.0.1
v1.0.0
Downloads
pdf
htmlzip
epub
On Read the Docs
Project Home
Builds

Free document hosting provided by Read the Docs.