CliMA / ClimaAnalysis.jl

An analysis library for ClimaDiagnostics (and, more generally, NetCDF files)
Apache License 2.0
9 stars 3 forks source link

Add a copying function to reduce boilerplate code #168

Open ph-kev opened 1 week ago

ph-kev commented 1 week ago

Currently, there is a lot of function that manipulate one thing of the OutputVar (like dims or data) and remake the OutputVar with that one thing changed. Because we cannot mutate the OutputVar (since otherwise the interpolant will not change), there is boilerplate code that which involves doing copy or deepcopy of the object to remake the object. Similarly, a lot of the tests involving constructing OutputVar with a single change.

To reduce the amount of boilerplate code, a copy function can be made that takes in var::OutputVar and the keyword arguments attributes, dims, dim_attributes, and data. If no keyword arguments are supplied, then the function return a deepcopy of the OutputVar. If a keyword argument is supplied, then it makes a copy of that object, but with whatever is supplied for the keyword. As such, instead of writing

...
ret_attribs = deepcopy(var.attributes)
ret_attribs["start_date"] = string(start_date)
ret_dims = deepcopy(var.dims)
ret_dims["time"] = time_arr
ret_dim_attributes = deepcopy(var.dim_attributes)
ret_data = copy(var.data)
return OutputVar(ret_attribs, ret_dims, ret_dim_attributes, ret_data)

you can write instead

...
ret_attribs = deepcopy(var.attributes)
ret_attribs["start_date"] = string(start_date)
ret_dims = deepcopy(var.dims)
ret_dims["time"] = time_arr
return copy_var(var; attributes = ret_attribs, dims = ret_dims)
ph-kev commented 1 week ago

A good name for the function could be rebuild or remake.