Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining and implementing interfaces in R

Tags:

oop

r

interface

I'm interested in defining and inheriting from interfaces in R. By interface, I mean OOP interfaces. I know R supports class extension. This link http://adv-r.had.co.nz/OO-essentials.html gives an example of extending a reference class in R. It defines a NoOverdraftAccount reference class that extends an Account reference class.

Instead of extending the Account reference class, I'd like to be able to define an account interface, IAccount. I would like I'd like NoOverDraftAccount to implement IAccount, such that:

  • NoOverDraftAccount must implement all methods in IAccount.
  • NoOverDraftAccount cannot declare any new public methods not already declared in IAccount.
  • NoOverDraftAccountcan declare private methods and properties.

What's the best way to achieve this?

The closest I've come to an answer was from the question Multiple inheritance for R6 classes. But, the question wasn't focused on interfaces.

Thanks for your time.

like image 367
Joshua Daly Avatar asked Jul 12 '18 06:07

Joshua Daly


1 Answers

I don't think "declarations" make much sense in an interpreted language like R. As there's no compile step there's no way to test if something actually conforms to a declared interface without running a function on the class, something like does_class_follow(class,interface), at some point.

So I think you have to start from scratch - you need to define an interface specification class and write the does_class_follow function.

My first thought was that a class would have to know what interface(s) it conformed to so that the test could introspect this, but perhaps that's wrong and you should have a file of interface definitions and pseudo-declarations that tested everything.

For example, have some file interfaces.R that looks like:

 IAccount = Interface(
     public = list("deposit","withdraw")
 )

 Implements(Account, IAccount)
 Implements(Account, NoOverDraftAccount)

Then when the package is loaded those Implements functions would run and test the classes against that specification of what an Account interface is. Whether its better to test at load time or to put these sort of things in the ./test/ folder and test them at test time using test_that or another test system is a question...

As you may be aware you'll have to implement this separately for all the OO systems in R that you want to use - S3, S4, R5, ReferenceClasses, R6, proto, R.oo and all the other ones I've forgotten...

like image 52
Spacedman Avatar answered Oct 04 '22 02:10

Spacedman