1
\$\begingroup\$

Following advice to "Make good use of toString() for all Domain classes", I made what I thought was the most useful toString for my class. I found that certain operations happen before there are values for the components of the toString. I wonder if there is a cleaner way to check for nulls or even if I need to approach things differently. As I'm writing, it occurs to me that depending on other objects in a toString is probably a bad idea.

class AssessmentStep {
    String hours
    Date assStepDate
    Assessment ass
    Step step
    Integer assStepProgress
    static hasMany =[stepNotes:StepNote]

    @Override
    String toString(){
        String stepString = "null"
        String appString = ""
        if (step != null && step.stepName != null){
            stepString = step.stepName
        }
        if (ass !=null && ass.app != null && ass.app.appName != null){
            appString = ass.app.appName
        }

        return appString + " " + stepString
    }
\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

You could do:

String toString(){
    "${ass?.app?.appName ?: ''} ${step?.stepName ?: 'null'}"
}
\$\endgroup\$
1
\$\begingroup\$

You could also do the following...

[ass?.app?.appName, step?.stepName].minus(null).join(" ")

This creates a List containing the two values, removes any null values from the List, and then builds a string separating the values with a space character (i.e. the join).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.