Anthony
Anthony

Reputation: 35938

How to pass a boolean to a method with a variable name

I have a method such as this

def uploadFile(String fileName, boolean performCleanup = false) {
   //upload file
   if (performCleanup == true) {
       //delete local file
   }
}

I call this method in two ways:

  1. uploadFile("/some/path/to/file.txt")
  2. uploadFile("/some/path/to/file.txt", true)

In the second case, for better readability, I would like to pass a variable name that would suggest what the significance of passing true is.

Something like, uploadFile("/some/path/to/file.txt", performCleanup: true")

Is this possible?

Upvotes: 2

Views: 5752

Answers (3)

Will
Will

Reputation: 14529

I'd like to suggest another way to use it in a DSL-ish way, by returning a map which can responds to performCleanup:

def uploadFile(String fileName) {
    //upload file
    println "uploading file"

    [performCleanup: { 
        //delete local file
        println "cleaning up" 
    }]
}

uploadFile 'file' performCleanup()

Output:

$ groovy Clean.groovy 
uploading file
cleaning up

By not calling performCleanup() after, it doesn't happen:

uploadFile 'file'

Output:

$ groovy Clean.groovy 
uploading file

Upvotes: 0

Gergely Toth
Gergely Toth

Reputation: 6977

By introducing and extra closure you can create a nicely readable micro DSL:

def performCleanup = {
  println "cleanup $it" //delete local file
}
def upload(fileName) {
  println "upload file $fileName" //upload file
  [then: { action ->
    action(fileName)
  }]
}

upload "path"
upload "path" then performCleanup

Upvotes: 3

Dónal
Dónal

Reputation: 187529

You can use a Map to simulate named args:

def uploadFile(Map args) {
   String fileName = args.fileName

   // will default to false if omitted
   boolean performCleanup = args.performCleanup

   //upload file
   if (performCleanup == true) {
       //delete local file
   }
}

You can then call the method using

uploadFile(fileName: "/some/path/to/file.txt")
uploadFile(fileName: "/some/path/to/file.txt", performCleanup: true)

This style has some pros and cons compared to the more typical style (wherein each value is passed as a separate argument):

  • Improved call site readability
  • Diminished declaration site readability
  • Flexibility, e.g. you can add/remove args to the method without updating each caller
  • Diminished compile-time safety, e.g. even if static compilation is enabled, you can't tell whether each caller is providing the required arguments

Upvotes: 2

Related Questions