luukvdmeer / sfnetworks

Tidy Geospatial Networks in R
https://luukvdmeer.github.io/sfnetworks/
Other
334 stars 20 forks source link

Support typed library #255

Open latot opened 10 months ago

latot commented 10 months ago

Hi all, maybe all ppl with some experience on R, would know is not easy to debug or work with a language where there is no checks on types, or where we can do some weird things like NA + 1 = NA.

There is several challenge aspects in order write good code, and this to be used correctly, like, no one send some trash to the param of a function.

Some time ago, I found the library "typed", which give us the chance to check when a var changes it is still a valid one, or when passing a param to a function.

The "typed" lib, give us the chance to create or own assertions, I think would be great have them for sfnetworks, I have created this one:

typed_sfnetworks <- typed::as_assertion_factory(function(value, null_ok = FALSE) {
    if (null_ok && is.null(value)) return(NULL)
    if (!sfnetworks::is.sfnetwork(value)){
        e <- sprintf(
        "%s\n%s",
        "type mismatch",
        waldo::compare(
            typeof(value),
            "sfnetworks",
            x_arg = "typeof(value)",
            y_arg = "expected"))
        stop(e, call. = FALSE)
    }

    value
})

To use is very simple:

library(typed)
typed_sfnetworks() ? x

#For vars
#This will throw an error
x <- sf::st_read("network.gpkg")
#This will works
x <- sf::st_read("network.gpkg") %.>%
       sfnetworks::as_sfnetwork(., directed = FALSE)

#For params
f <- ? function(network = ? typed_sfnetworks()) {
  network %.>% sfnetworks::active(., "nodes") %.>% sf::st_as_sf(.)
}

I think would be great have a sfnetworks::typed_sfnetwork or similar inside the package, to use this checks on libs who uses sfnetworks.

Thx!