SafeR - examples

Printer-friendly versionPrinter-friendly version
How to use the SafeR framework

 

To ensure a given text is not null or empty we can write...

NotEmptyText text = NotEmptyText.of(textInput);

...or...

NotEmptyText.assertFor(textInput);

Let's look at another example: a given collection must not contain any null values. To ensure this, we write...

NoNulls<Foobar> foobars = NoNulls.of(unsafeFoobars);

...or...

NoNulls.assertFor(unsafeFoobars);

As simple as that we can ensure a collection meets a contract of our choice. But in this example we have to pay more attention, because SafeR will create a copy of the collection passed to the of operation to ensure its referent is not referenced anywhere else and thus the collection cannot be changed after it has been passed to the of operation. This is fine for most cases. In case the collection is too large and therefore the performance is too poor at this point, a boolean flag can be passed to the of operation to skip the copy action:

NoNulls<Foobar> foobars = NoNulls.of(unsafeFoobars, true);

Please note: skipping the copy action requires that the caller of the of operation ensures that the collection passed to the of operation is not referenced anywhere else!

Sometimes we just want to query whether or not a given object meets a certain contract, e.g. to check if the unsafeFoobars contain a null value we can write...

if (NoNulls.isTrueFor(unsafeFoobars)) { ... }

...or...

NoNulls.ifTrueFor(unsafeFoobars, f -> { ... });

...or...

NoNulls.ifFalseFor(unsafeFoobars, f -> { ... });

...where we pass as second parameter a Consumer to process the foobars.

 

How do we use the safe references we created?

If we create a safe reference to pass it to a subsequent operation, sooner or later we have to access the referent contained in the safe reference. We can unwrap the referent like so...

Foobar safeFoobar = foobar.get();

...or so...

Foobar safeFoobar = foobar.getObject();

...or so...

Foobar safeFoobar = foobar.getReferent();

...or so...

Foobar safeFoobar = foobar.getValue();

...or so...

Foobar safeFoobar = foobar.ref();

...or so...

Foobar safeFoobar = foobar.safe();

...or so...

Foobar safeFoobar = foobar.value();

...and all of these accessors do the same, they return the referent. These sibling operations exist solely to support various coding styles. So it is up to you which accessor you use. It is recommended to define a coding standard for each project, where that coding standard tells the developers precisely where to use which accessor. For instance a project might use always the value accessor for simple values and the ref accessor for complex objects. Or a project might use always the safe accessor to highlight that a safe referent is returned. If such a coding standard is applied consistently, it improves the readability of the code.

 

Pages