When composing longer strings based on multiple tests in Nextflow workflows, using the ternary operator or string concatenation can lead to long, hard-to-read lines of code. An alternative approach is to use a list to store the parts and then join them to create the final string. This method improves readability and maintainability.
e.g.
ext.args = {"-ax ${meta.readtype.equals("hifi") ? "map-hifi" : meta.readtype.equals("clr") ? "map-pb" : meta.readtype.equals("ont") ? "map-ont" : meta.readtype.equals("illumina") ? "sr" : ""} --cs=short ${reference.size() > 2.5e9 ? (" -I" + Math.ceil(reference.size()/1e9)+"G") : ""}" }
could become
ext.args = { [
meta.read_type.equals("hifi") ? "-ax map-hifi" : "",
meta.read_type.equals("clr") ? "-ax map-pb" : "",
meta.read_type.equals("ont") ? "-ax map-ont" :"",
meta.read_type.equals("illumina") ? "-ax sr" : "",
"--cs=short",
reference.size() > 2.5e9 ? (" -I" + Math.ceil(reference.size()/1e9)+"G") : "",
].minus("").join(" ") }
Key improvements:
- Each condition is on a new line, which improves readability.
- The
.minus("")
removes all empty strings (an alternative is.findAll()
which removes anything that evaluates to Groovy false -[ [], 0, "", '', false ]
). - Then
join(" ")
which combines the remaining parts with spaces.
This improves maintainability, as adding and removing conditions becomes easier.
( Written with the aid of Seqera AI )