BlueStyle
BlueStyle copied to clipboard
Soften guidelines for `return`
When using long-form functions always use the
returnkeyword
We may want adjust the the hard stance on using return with long-form functions. Some examples that adding in the return makes things worse:
function load!(tz_source::TZSource, file::AbstractString)
open(file, "r") do io
load!(tz_source, file, io)
end
end
# VS
function load!(tz_source::TZSource, file::AbstractString)
return open(file, "r") do io
load!(tz_source, file, io)
end
end
function isarchive(path)
@static if Sys.iswindows()
success(`$exe7z t $path -y`)
else
success(`tar tf $path`)
end
end
# VS
function isarchive(path)
return @static if Sys.iswindows()
success(`$exe7z t $path -y`)
else
success(`tar tf $path`)
end
end
function VariableTimeZone(name::AbstractString, args...)
new(name, args...)
end
# VS
function VariableTimeZone(name::AbstractString, args...)
return new(name, args...)
end
function extract(archive, directory, files=AbstractString[]; verbose::Bool=false)
...
run(cmd)
end
# VS
function extract(archive, directory, files=AbstractString[]; verbose::Bool=false)
...
return run(cmd) # Note: We don't actually want to return anything from this function
end
I would suggest we re-word to something like:
When using long-form functions prefer the use the
returnkeyword especially when control flow constructs are used. Avoid the use ofreturnwhen your function should not return anything.
I disagree, I like it how it is. When we don't want to return something I think we should add an empty return at the end.
I was just going to open a similar issue, and figured I'd look to see if there were other ones first.
For me it's mostly the last example that @omus posted. When a function doesn't actually return a value that we care about (such as a function that runs a command such as in this example), having an empty return nothing seems useless and serves no purpose imo. I get that we don't want implicit returns, but this seems overkill to me.
Copying my Slack comments here for posterity:
This is actually a pretty important case in particular. Julia will return the result of the last expression of a function. If the value of the last expression is of varying type depending on the arguments, you can have the compiler do a ton more work in inference than if you put return nothing. This is why e.g., the print functions in Julia end with return nothing.
Julia will return the result of the last expression of a function
My original examples are relying on this fact. If you want your function to return nothing it's definitely best to explicit.