10 ms·
Maybe it's my background but recursion feels more natural, either you are at the base, or at a point with N-1 items below. This gives you two different invarian
by PartiallyTyped 4y ago
Maybe it's my background but recursion feels more natural, either you are at the base, or at a point with N-1 items below. This gives you two different invariants that you can use to simplify the code.
Small example, though not exactly comparable to looping.
I needed to create a human readable qualified path appended by a hash (to avoid conflicts). This qualified path was needed ahead of the construction of an object, and the logical name must have been used in both the hash and qualified path as it was global (Yes, it was an S3 bucket).
I wrote a function
uniqueQualifiedName: Construct x Optional(logicalId) x Properties -> string.
The recursive step is at the top, where the logicalId is transformed to a construct in the scope of the first argument, and the function is called again with NewConstruct x Nothing x Properties. This could easily be adjusted to work with a list of logicalIds instead.
The invariant in the recursive step is that once the call returns, the construct at the end of the chain will be exactly the construct I inserted, and I can pop it safely, and the scope object will be none the wiser.
The invariant in the base is simply that I don't need to worry about logicalId being anything.
You can see then how easy it is to adapt this to work with a list, whereas with a loop you'd have to write it from zero, and then roll back. Too messy imho.
- roenxi 4y agoI don't understand your problem or your solution, but that seems like a lot of things going on to construct a string. But it sounds like you could just bash the logicalIds together and append the hash of the bash of the mash. Might not need loops or recursion.
- PartiallyTyped 4y agoTo just bash them together I'd have to either use the private api which is not a good thing. Alternatively I can push a list of items N steps to each object and have each one of them both adding and removing the logical names.