mulesoft-labs / data-weave-rfc

RFC for the data weave language
13 stars 5 forks source link

Null Asserter #21

Open machaval opened 3 years ago

machaval commented 3 years ago

Null Asserter

Current Problem

If we have a variable that is Something | Null but we have already validate that is not null or we just know is never null.

var myVar: String | Null = payload.foo
---
if(myVar != null) myVar ++ " test" else ""

This script fails beacuse

  1. We don't have flow re-typing, something that we may fix but is impossible that it works 100% of the times
  2. There is no way to assert that myVar is not null

We currently have a way to assert that a property should exist

{}.a

Fails because the property doesn't exists different to

{}.a

That returns null but also different that

{a: null}.a!

That also returns null.

Having seen this we can not use ! to assert that an expression doesn't return null as this only asserts that a property does exists.

Proposal

We can introduce !! this asserts that the expression is not null.

{a: null}.a!! //Fails
{}.a //Returns null
{}.a!! // Fails

var myVar: String | Null = payload.foo
---
if(myVar != null) myVar!! /*My var is not null anymore*/ ++ " test" else ""
menduz commented 3 years ago

Can it be a function?

there is a chance here to not introduce new syntax and make the scripts easier to understand using familiar concepts: contract assertions. https://rosettacode.org/wiki/Assertions_in_design_by_contract

// core.dwl
fun require<T>(value: T | Null): T =
  if (value == null)
    fail('Value assertion failed')
  else
    value as T
var myVar: String | Null = ???

fun acceptString(value: String) = ???
---
acceptString(require(myVar))
machaval commented 3 years ago

Yes @menduz this is a really valid point, but my concern with that is how verbose this end up being. I have mixed feelings about this. But you are 100% right that this can be modeled with the language in a very simple way

manikmagar commented 3 years ago

I agree with @menduz here, having functions are more readable than something like !!. Compare that to Objects.requireNonNull() function in java.

Being verbose could be better than being confusing or difficult to understand. I can foresee people forgetting about !! or referring to docs again to remind what that means in counter-productive way.