Best way for "if null then default else value"

I was using the following pattern often in my code:

abc = something == null ? some_default : something

until I realised it can be more succinctly captured (especially when “something” is a more complex expression) as

abc = coalesce(something, some_default)

This is simple for anyone who knows coalesce() BUT I find the intent is not as obvious as the more verbose version.

So I’m wondering if there is a yet better way. Eg the most obvious would have been

abc = ifnotnull(something, else_value)

The defaults() function already available as experiment in HCL2 does not do the same: defaults() requires that something be an input variable with a type, whereas sometimes something is a local, and without an explicit type.

Is there a better way to communicate intent than using either the if/then/else or the coalesce()?

Hi @schollii,

I believe this term “coalesce” came from SQL, where most dialects have a function of the same name which has essentially the same effect. I imagine whether that name is intuitive or not will unfortunately depend on whether you are familiar with that function.

I don’t have any other ideas to suggest other than the explicit condition or the coalesce function. I don’t think we would consider adding yet another way to achieve the same effect, since the conditional expression is already very expressive for situations like this.

Thanks @apparentlymart good to know

@schollii Reading this: c# - Which works faster Null coalesce, Ternary or If Statement - Stack Overflow I think coalesce is better than if/else statement but the terraform code as such would need to be reviewed to see if it would apply or not