Breaking notation convention - a potential anti-pattern?

algunion
Mon, 17 Jul 2023 17:34:33 +0000
General Usage

I have a scenario where I think it might be warranted to depart from the end with an exclamation mark convention for function names that modify at least one of their arguments.

However, I wouldn’t want to get into an anti-pattern here - so I am really curious about your take on this.

I think the best approach is to show a MWE here:

struct MyStruct
    arr::Vector{Int} # updatable thing
    updatable::Bool
end

function myfun(x::MyStruct)
    # some sophisticated logic using x
    y = 1 # resulted from the logic
    success = true # can also be false - depending on the logic
    success && x.updatable && push!(x.arr, y)
    return x
end

x = MyStruct([1, 2, 3], true)
myfun(x)
@info x

In this scenario, myfun has the potential to modify its argument - and will always fail to modify it when the updatable is set to false. And will almost always modify it when the updatable is set to true (with a few exceptions - depending on the internal logic of the function).

I am aware that I could isolate my logic and have myfun and myfun! versions that can call myfun_logic that returns (result=an Int, success=true/false) and perform the update only inside myfun! - but in this case I could very well just drop the updatable field and decide which function to call each time. So let’s stick with the MWE - where the user does not need to select between the two functions at each call location.

So, should I switch to myfun! in this scenario? Or, is myfun a legitimate option?

17 posts - 7 participants