Abstract cross-cutting concerns away from template choices

Let’s say I have many templates that have a changeTime field like

template A
  with
    creator : Party
    changeTime : Time
  where
    signatory creator
    choice Foo : ContractId A
      controller creator
      do
         -- Update some other fields as well, skipped for brevity
          currentTime <- getTIme
          create this with
             changeTime = currentTime

template B
  with
    creator : Party
    changeTime : Time
  where
    signatory creator
    choice Bar : ContractId B
      controller creator
      do
          -- Update some other fields as well, skipped for brevity
          currentTime <- getTIme
          create this with
             changeTime = currentTime

I’d like to know if there is a way to abstract the currentTime <- getTime; create this with changeTime = currentTime away from the choice implementations, but making sure all templates having a changeTime field will automatically ‘inherit’ (for lack of a better term) the behaviour of getting its changeTime field updated when Foo or Bar is exercised.

I am thinking interfaces might help but I am not exactly sure.

1 Like

I would just factor this out into a function. You don’t get the automatic inheritance that you’re asking for but I think being explicit here is preferable. You could in theory try to build some interface based solution but interfaces are a fairly heavy weight solution to achieve decoupling. They’re not that great for just reducing boilerplate so I wouldn’t use them here:

template A
  with
    creator : Party
    changeTime : Time
  where
    signatory creator
    choice Foo : ContractId A
      controller creator
      do updateTime this

template B
  with
    creator : Party
    changeTime : Time
  where
    signatory creator
    choice Bar : ContractId B
      controller creator
      do updateTime this

updateTime : (HasField "changeTime" t Time, HasCreate t) => t -> Update (ContractId t)
updateTime t = do
  currentTime <- getTime
  create  t with
    changeTime = currentTime
1 Like

Thank you @cocreature!