To bind or not to bind

I’d like to poll the forum users on what they think is the better style:

    someTestScript party assetKey = do
      queryContractKey @Asset party assetKey >>=
         assertSome "there should be a Asset"
    someTestScript party assetKey = do
       aOpt <- queryContractKey @Asset party assetKey
       assertSome "there should be an Asset" aOpt
1 Like

I think that for a test script, I’d prefer option 2, as the assertion is the most important part, and I want to read it first. Having the explicit variable and the same level of indentation means I can read the test from bottom to top.

I don’t find myself using >>= very often. When I do, it’s typically for inline conversions or other things that I maybe want to draw less attention to, not important behavior. For example, I might use it to quickly filter out an empty string.

1 Like

It also depends on the context you’re using that code in. I like to stick to do for anything targeted at people relatively new to Daml because you won’t get very far without do (all examples use it, doing complex stuff with >>= is super messy) whereas you can get quite far without understanding >>= so avoiding that strictly reduces the number of concepts someone has to understand to make sense of the code.

In code where I know everyone is proficient in Daml, I occasionally use >>= for small things but anything larger still ends up using do notation.

2 Likes

I like using do because it makes the ordered/imperative nature of Update/Script execution explicit.

2 Likes

The people have spoken. I do prefer 2 too.

3 Likes

First note a little detail: for no 1, I don’t think that you need the do statement at all.

I think like others have said, do is nicer when you have multiple stacked binds; otherwise you have to indent each successive bind and your program falls off the screen.

I think the other situation where it has a definite advantage is when you’re writing purely side-effecting code i.e.

f : x -> ()
g : x -> ()

do
  f x --could also be written _ <- f
  g x

So this gives the impression of writing a program as in an imperative language. Of course, if you find yourself writing a lot of code like this it’s probably not great functional design! But there are several cases where I think this is justified, e.g. create, archive, or assert, like in your example.

2 Likes