Reputation: 25
I usually do a null check in Dataweave, as below,
{ payload.variableA when payload != null otherwise null }
But one of my Collegue has suggested me to use default {} to reduce the null checks, like below,
%var x = payload default {}
{
payload.variableA
}
As it improves readability, especially in complex transformations.
But is it really a good practice to do this way? Will it cause any issues, like creating unnecessary empty objects?
Upvotes: 0
Views: 5323
Reputation: 1910
First, payload.variableA
should return null when payload is null. You don't need to do a check on that. Attempting to access a key on a null object returns null rather than throwing something like a null-pointer exception you might be used to.
You can think of default
as the null-coalesce operator for dataweave. You can set it to an empty object, a default value, etc etc.
https://docs.mulesoft.com/mule-runtime/4.3/dataweave-cookbook-defaults
The default operator behaves the same in DW1 and DW2.
Upvotes: 2