Skip to main content

Objects

This file will contain all the rules that needs to be followed related to objects and their contracts.

Responsibility of State

Every object is responsible for its own state.

Every object must guarantee that it cannot enter an illegal state. Any exceptions must be clearly documented.

Shipment s = // code
s.setShipper(null) // bug

The above example is not allowed, since a shipment can never exist without a Shipper.

Temporary Invalid state

It is not allowed to 'temporarily' have an object with invalid state.

Shipment s = // code
s.setField(invalid); // bug
if (s.isInvalid()) {
throw ...;
}

This is not allowed, since Shipment is not guaranteeing its own state.

There exists code that will do this with Hibernate entities, for example handling updates by creating 2 Shipments, one with the original state and one with the new state. This is very brittle and not allowed.

Assumptions

It is not allowed to assume properties of objects. Either these properties must be verified, or the source object must guarantee them.

For example, if a function does not explicitely guarantee a non-null return type, it is not allowed to assume it is not null.

Modelmapper and reflection

When using org.modelmapper.ModelMapper fields are populated using reflection, bypassing all normal validation. Objects created in this manner cannot guarantee their own state. It is not possible to make hard guartees on objects instantiated in this manner.

It is not allowed to use this construct in new code, and old code that uses it should be refactored.

ModelMapper and related constructs are allowed to be used to map to external data structures and the like, such as JSON, since these objects do not make claims on their own state.