Skip to content

Should defining a constructor really be "Advanced use only?" #245

Closed

Description

@kaneplusplus

This looks like a great project and I've been following it for a little while.

I did notice a few issues around constructors. First, the documentation claims that defining a constructor is for advanced use only. Should this be the case? Usually a constructor provides pre-processing steps to go from arguments to properties/attributes. This is not advanced usage in most other languages. Second, the documentation isn't sufficient to create a constructor in a class. I did try looking through the tests for an example but noted that the test in test-constructor.R file creates a class but fails when one tries to instantiate an instance.

> foo <- new_class("foo",
    properties = list(x = class_numeric),
    constructor = function() new_object(x = 1)
  )
> foo()
Error in .parent %||% class_construct(class@parent) :
  argument ".parent" is missing, with no default

Activity

  1. hadley commented on Jul 29, 2022

    @hadley
    Member

    It's advanced use only since you have to figure out how to build the constructor yourself 😛 (I'll definitely document that better). Maybe expert use only would be better phrasing? I don't think we expect many people to supply the constructor themselves. In the case where you wanted different arguments to properties, I'd think you'd create a wrapper function. Do you have an example of what you're thinking?

  2. kaneplusplus commented on Aug 1, 2022

    @kaneplusplus
    Author

    :-) Fair enough.

    I agree that creating a wrapper function is an alternative. For example, the range object in the documentation could take the range of a vector of points and you could create create_range() function as:

    create_range <- function(vals) {
      range(min(vals), max(vals))
    }
    

    The issue is then create_range() is not encapsulated by the range class. This isn't wrong but I might like to be able to create with range(vals) in addition to range(start, end).

    BTW, this is a great project.

  3. hadley commented on Aug 1, 2022

    @hadley
    Member

    Ah yeah, that makes sense. I'll tweak the docs to reflect this.

  4. added a commit that references this issue on Apr 15, 2023
    4783abc
  5. added a commit that references this issue on May 8, 2023
    6c0460c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions