Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Null Asserter #21

Open
machaval opened this issue Jan 30, 2021 · 3 comments
Open

Null Asserter #21

machaval opened this issue Jan 30, 2021 · 3 comments

Comments

@machaval
Copy link
Contributor

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
Copy link
Contributor

menduz commented Jan 30, 2021

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
Copy link
Contributor Author

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
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants