Skip to content

Instantly share code, notes, and snippets.

@kevroletin
Last active April 16, 2018 04:14
Show Gist options
  • Save kevroletin/49699eca01e5719da79ba038a1489066 to your computer and use it in GitHub Desktop.
Save kevroletin/49699eca01e5719da79ba038a1489066 to your computer and use it in GitHub Desktop.
My current thought about extensible abstractions

Problems

  1. Runtime configuration

    Example: web services which read database configuration from config.yaml.

    An application reads configurations and chooses between different subsystem implementations.

  2. Write your own implementation of a concept from 3rd party library

    Example: graphical toolkits.

    We want our users to be able to extend framework/library functionality without modifying framework/library code. For example, in graphical toolkits, it is possible (and even desirable) to implement your own widgets.

  3. Extend existing implementation

    Example: graphical toolkits.

    Extend existing implementation by configuring/overriding some aspects of its behavior.

  4. Dependency injection.

    Example: mocking for testing.

  5. Separation of concerns

OOP

  1. Runtime configuration

    Here we just declare an interface and take advantage of dynamic methods dispatch:

      interface Database {
          public <User> fetchAllUsers();
          public void   deleteUser(User);
      }
      
       class PostgresDatabase implements Database { ...
       
       class MysqlDatabase implements Database { ...
       
       ...
       
       if (config.database.url.contains("postgres")) {
           return new PostgresDatabase(config.database);
       }
       else if (config.database.url.contains("mysql")) {
           return new MysqlDatabase(config.database);
       } else {
           ...
    
  2. Write your own implementation of a concept from 3rd party library

    Aka "Implement this interface" frameworks.

    Basically the same idea as in the previous point. Framework declared common interface and users are able to extend this interface.

  3. Extend existing implementation

    Aka "Fill the gap by overriding this virtual method" approach.

    The cool thing here is that extension happens at compile time.

  4. Dependency injection

    The object receives all its dependencies in the constructor and works with them via interfaces. That way it is easy to mock dependencies for testing.

  5. Separation of concerns

    We usually implement different subsystems or different scenarios as objects. The rule of thumb is "the object should do a single thing and do it well". There are OOP patterns which help to organize interaction between objects in such a way that the rule of thumb works. Then we combine solution by calling object methods.

FP

First of all, OOP can be implemented in Haskell and there are several approaches which implement a different amount of concepts from OOP. I didn't read all of them because I want to concentrate on alternatives to OOP.

  1. Runtime configuration

    I know about the Handle pattern. Essentially it is an emulation of dynamic dispatch where you construct Vtables by hands. There is an extension of the Handle pattern where you combine global config and dependency injection with a registry of Handles into a single monad transformer:

  2. Write your own implementation of a concept from 3rd party library

    There we have two options:

    • emulate OOP and explicitly pass distionaries

    • use Typeclasses

      AFAIU even internally, type constraints are very similar to dynamic interfaces in OOP languages and require a compiler to pass Vtable for a typeclass:

      class Widget where
          draw :: WidgetDrawingMonad ()
      
      ...
      
      class Layout where             
          addWidget :: Widget w => w -> IO () -- This method will receive Vtable if no inlining happens
      
      ...
      
      instance Widget MyWidget where
          draw = myWidgetDraw
      
  3. Extend existing implementation

    • Pass callbacks.

        concreteImplementation = abstractImplementation (\x -> x + 1) (\y -> y * 5)
      
    • TODO: Can I somehow use parametric polymorphism here? I definitely can in c++, how I would do it in Haskell?

  4. Dependency injection

    TODO: study existing DI frameworks in Haskell. TODO: study mocking of a part in a Monad Transformer stack

  5. Separation of concerns

    1. Monad Transformers

      We prefer implementing several small "languages" for solving different problems and then combining them together. The main abstraction here is MonadTransformers library. Having different transformers like ReaderMonad and StateMonad is not a sufficient level of concerns isolation. So if you use Reader or State monad then it is possible to have really fine-grained separation of concerns by using type constraints like this:

          class HasDbConfig where
              getDbConfig :: DbConfg
      
          class HasNetworkConfig where
              getNetworkConfig :: NetworkConfig
      
          data AppConfig = AppConfig
              { dbConfig      :: DbConfig
              , networkConfig :: NetworkConfig
              } deriving (...)
      
          instance HasDbConfig AppConfig where ...  -- (1)
      
          instance HasNetworkConfig AppConfig where ... -- (1)
      
          type AppMonad = ReaderT AppConfig IO ()
      
          storeUserToDb :: ( ReaderMonad r m
                           , HasDbConfig r
                           , IOMonad m) 
                        => User -> m ()
          ...
      

      We can go even further and restrict the amount of effects available in storeUserToDb function like this:

        class DatabaseIOMonad where
            executeSql :: Text -> IO ()
      
        storeUserToDb :: ( ReaderMonad r m
                         , HasDbConfig r
                         , DatabaseIOMonad m) 
                      => User -> m ()
      

      That way we can implement multiple mini-languages for different activities that our application performs and then use it in our main AppMonad.

      (1) - You can automate is by TH and MakeClassyLenses from Lens library.

    2. Extensible effects. Free and Freer monads

      TODO

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