R and OOP anti-patterns

Thomas Lumley just dropped a blog post, Blank cheque inheritance and statistical objects, which begins as follows.

One of the problems with object-oriented programming for statistical methods is that inheritance is backwards. Everything is fine for data structures, and Bioconductor has many examples of broad (often abstract) base classes for biological information or annotation that are specialised by inheritance to more detailed and useful classes. Statistical methods go the other way.

In base R, glm for generalised linear models is a generalisation of lm for linear models, but the glm class inherits from the lm class, …

This isn’t a problem with inheritance, it’s a problem with how R uses it.

Fundamentals of OOP and inheritance

The fundamental rule for inheritance in object oriented programming (OOP) is that a class X should inherit from class Y only if every X is a Y. That means you should be able to use an X wherever the code calls for an Y. For instance, a Poodle class might inherit from the Dog class, because every poodle is a dog. Any function you can apply to dogs, you can apply to poodles. Every function that is defined to return a poodle will also return a dog. Behavior as arguments and returns is governed by the concepts of covariance and contravariance in programming language theory. Inheritance must respect these relations for a coherent OOP design.

A classic blunder is to define a class for real numbers and one for complex numbers and have the complex numbers inherit from the real numbers. Every real number is a complex number, but not every complex number is a real number. So doing this will break standard OOP implementations. The reason beginners in OOP make this mistake is that it’s natural to think of the implementation of a complex number as taking a real number and adding an imaginary component. If you want to start with real numbers, a better way to define a complex number would be using composition to include two real components. That is, it contains two real numbers rather than inheriting from real numbers to get its real component. This is exactly how std::complex is defined in C++, with a constructor that takes the real and complex components as two objects of type T, where T might be double for double-precision complex numbers or it might be an autodiff type like stan::math::var.

The God object anti-pattern

I’m also not fond of how lm returns a god object. God objects are a widely cited anti-pattern in OOP, largely because they’re so frequently seen in the wild. The inclination that leads to this is to have something like a “blackboard” into which all kinds of state can be written so the user can get it all in one place. A common example is including all the input in a function’s output. No need to do that because the user already had all of that information because they couldn’t have called the function otherwise. God objects’ are usually a terrible idea as it’s nearly impossible to ensure consistency of such an object without defeating its purpose, because its purpose is to behave like a global variable repository. R doesn’t even try—you can take an lm fit object and change various aspects of it and leave it in an inconsistent state without warning, e.g.,

> fit <- lm(dist ~ speed, data = cars)

> fit$coefficients
(Intercept)       speed 
 -17.579095    3.932409 

> fit$coefficients = c(1, 2, 3, 4)

> fit$coefficients
[1] 1 2 3 4

The Stan interfaces in Python and R also return god objects. I lost the design argument to the other developers, who argued, “That’s the way it’s done in R and Python.”

R’s argument chaining vs. OOP method chaining

Speaking of OOP, chaining with pipes in R follows the object-oriented pattern of method chaining, but instead of using object returns that are the class defining the next method in the chain, it just passes along the return to use as the first argument in the next chained function. It’s no longer object oriented. This doesn’t break any OO patterns, per se. It might be awkward if you need to pack enough into a return to go onto the next function. In OOP, developers often break long method chains into groups of coherent calls with named returns when the returns are not all instances of the same class. The reason to break up long chains is, ironically given how they’re motivated in R, to help with readability and self-documentation. Code readability is the single best thing you can do to make code maintainable, because code will be read much more often than it gets written. You can bridge the gap between what R does with chaining and the standard way to do method chaining in OOP by looking at how Python classes are defined with an explicit self argument (like the this pointer to the class instance in C++, but C++ doesn’t require it as an explicit argument on methods).

P.S. I tried commenting on Lumley’s blog but was defeated by Disqus. I thought it might be of general interest, so am including it here.

11 thoughts on “R and OOP anti-patterns”

  1. “That’s the way it’s done in R and Python.”

    I’m pretty sure anyone who expressed that opinion about software development in Python, at least as this regards that particular practice, would not be on my team for long. Of course, I tend to consider OOP itself to be an anti-pattern, so there’s that.

    • @nkh: Stan grew up as a volunteer, open-source project. I didn’t have a team that reported to me, so I didn’t have the discretion of firing anyone, much less hiring anyone. I could’ve exerted enough authority early on to block contributions, but I’m guessing people would’ve just left the project when they no longer felt they had any control.

      At the point the project started, it was a couple people reporting to Andrew. Andrew’s very hands-off management-wise, which works very well if you’re a self-directed academic taking a low-paying job in order to have your academic freedom. It gave me the freedom to work on a new programming language for 1.5 years without publishing anything, which is an absolutely bonkers plan in academia (though less risky from my perspective as I was planning to go back to industry). I was working primarily on the language and math library in C++ and didn’t have the cycles or R/Python knowledge to build the interfaces. There also has to be a degree of trust in a collaboration or it’s miserable for everyone. It’s also important here that my colleagues were right—that is how people build R and Python interfaces. And for all I know, the designs they came up with are better for most R and Python users. Personally, I tend to design things for myself and hope other people like them.

      We went through a cycle of industry-style management with repo managers and a technical director, and I have to say being technical director was the least fun part of the Stan project. We eventually created a governing body and Breck Baldwin shephered Apache-style technical governance, which is based on voting on things that are contentious. This has proved to be very good. I suggest reading Karl Fogel’s excellent, Producing Open-Source Software, which is itself free, open-access.

      • one correction – the voting procedure was put in place by the first developer-elected Stan Governing Body.

        the original version of governance, advocated by Breck, among others, was unworkable. from my stints in industry, it’s not particularly successful there, either, given that most projects fail to launch and even fewer are widely adopted. the Stan project has been blessed with developers who like to teach and train others – starting with Bob and Daniel Lee. that and pragmatism.

      • Thanks for the remarkably detailed answer to what, largely, an off the cuff comment. I’ve never participated in an open source project and it’s interesting to see how the organization works without the structures/incentives we have in an “industrial” setting.

        I don’t doubt that those are practices that are common in a subset of Python development. After all, I use matplotlib on a daily basis which is something of a poster child for the improper manipulation of one objects inner state by external objects. But I am serious when I say that no one who presented me a PR that looked like matplotlib would ever get that approved. Something like matplotlib seems to represent a common practice in open source scientific software of a certain vintage and the way it’s architected represents experience and expectation of a community that was accustomed to interacting with a different programming ecosystem, not best software development practice (which is, to be fair, a pretty vague term). In my context, catering to this sort of common practice at the expense of morr flexible, secure design is not a compromise that I would support. But I do know that ymmv.

  2. What can be done to address these issues? The method-chaining and god-object seem addressable, but the inheritance issue seems like it comes about as a result of how techniques are developed (start with the easy cases, move to the more general).

    • Julia solves this problem and many more IMHO. Julia doesn’t have inheritance, it has multiple dispatch. If you want to do something with an object you pass that object to a function and it will call the most specific method for that type. And it doesn’t matter what argument you place the object in. Unlike OOP where in essence the first object to a function determines the method call, you can specialize a function in Julia to do the right thing.

      For example

      sample(mymodel,NUTS(400,0.8),400)

      Is the syntax to sample from a Turing model using the NUTS algorithm with 400 sample warmup targeting 0.8 acceptance rate followed by 400 retained samples.

      Want to sample with a different algorithm? Instead of passing a NUTS object pass a MH() object. Want to sample a different kind of model? Pass a different kind of model in the first argument…

    • “Prefer composition over inheritance” is a good rule of thumb that is still not followed often enough. Make your poodle contain a DogBehavior object, make your complex number contain a RealNumber. I’ve seen cases where inheritance works great, such as GUI libraries, but overall inheritance is very easy to get wrong as soon as you go beyond interfaces.

  3. Similarly to Daniel Lakeland above, I find multiple dispatch a much nicer way to organize code than OOP. This video is a nice overview of how and why it works in Julia: https://www.youtube.com/watch?v=kc9HwsxE1OY

    Ironically, R has multiple dispatch but it is via S4 which is so clunky that it is rarely every seen by users, and does not get widely used by package devs either. So the only language in practical use for scientific programming that has multiple dispatch is Julia.

    • Whether you like S4 or not, all of Bioconductor is built on it, so I respectfully disagree with “does not get widely used by package devs”.

  4. Base R piping is not really chaining in the sense either of the Magritter pipe or of object oriented programming. It does not feed an output into an input, it feeds the results of a function into another function g(f(x)) for the user is f(x) |> g(x) but the compiler handles does this in the R way of handling nested math functions.

    I actually would not consider the S3 generics an actual object oriented system.

    • The point about S3 is important. While S3 is referred to as ‘one of the many object oriented frameworks in R’, its effect — particularly in old base R functions like lm() — is much closer to Julia’s multiple dispatch than to archetypal OOP systems (e.g. Ruby, Java). That makes the direction of inheritance less important. The quoted section of the OP complains that it’s incorrect for glm to inherit from lm, but the implied relationship is not “all glms are lms”, it’s “treat glms and lms the same way when the user attempts to show, print, plot, or predict with them”.

      I’m also not sure about the god object complaint, or at least about the better alternative. Julia’s GLM.LinearRegression() returns a similar structure (preprocessed data, coefficients, test results) with similar generic methods (show, print, plot). Python’s sklearn.linear_model.LinearRegression() is different, in that its workflow decomposes the preprocessing, fitting, testing, and plotting processes into discrete steps. From my experience, this feels much less like a choice between good and bad approaches, and more like a tradeoff between the benefits and costs of encapsulation / abstraction. Fitting and presenting results from a linear regression in R and Julia requires fewer lines of more declarative code.

Leave a Reply

Your email address will not be published. Required fields are marked *