Skip to content

docs: replace stateful ggproto example with stateless one#6854

Open
CuiweiG wants to merge 1 commit intotidyverse:mainfrom
CuiweiG:docs/issue-6582-ggproto-example
Open

docs: replace stateful ggproto example with stateless one#6854
CuiweiG wants to merge 1 commit intotidyverse:mainfrom
CuiweiG:docs/issue-6582-ggproto-example

Conversation

@CuiweiG
Copy link
Copy Markdown

@CuiweiG CuiweiG commented Apr 22, 2026

Closes #6582.

The current ?ggproto example demonstrates a stateful class (Adder$x) that, per the issue, "advertises a property of ggproto classes that should be used sparingly and ideally not at all if you're developing extensions."

The replacement builds a stateless Math class with two static methods plus a Mather child overriding one method via ggproto_parent(). Construction, method dispatch, and parent-method invocation are all still covered; no self$* field access appears anywhere. The child method carries self in its signature solely to thread identity into ggproto_parent(Math, self).

The "Working with ggproto classes" section gains a short paragraph stating that most ggplot2 layer classes (Geoms, Stats, Scales) are stateless, and encouraging extension authors to follow that convention.

Local verification: all example code paths run under devtools::load_all() with the expected values.

The prior @examples for ggproto() used stateful classes (Adder$x),
a pattern discouraged for extensions since most ggplot2 layer classes
are stateless. The new Math/Mather example covers construction, method
dispatch and ggproto_parent() without `self$*` access, and the
Working-with-classes section adds a paragraph on the stateless norm.

Closes tidyverse#6582.
@teunbrand
Copy link
Copy Markdown
Collaborator

Thanks for preparing a PR!
I think the proposed change is not exactly what we want users to learn about ggproto classes. It may have very well be my insufficient explanation in #6582 that had set this on the wrong track.
To explain a bit more; it is fine to read from a ggproto object's fields, but to write to that field is discouraged.
In the old example, self$x <- self$x + n is the problematic piece.

@CuiweiG
Copy link
Copy Markdown
Author

CuiweiG commented Apr 22, 2026

Thanks for the clarification — the write-vs-read distinction wasn't clear to me from the issue alone. Will revise the example to keep the field-based inheritance pattern but drop the mutation. Back to you shortly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Example in ?ggproto counterproducive

2 participants