Detecting ambiguities

It is often difficult to find ambiguous methods until you happen to hit a specific use case at runtime. That's not good. I don't know about you, but software engineers like me don't like surprises in production!

Fortunately, Julia provides a function in the Test package for detecting ambiguities. We can try this out using a similar test. Consider the following code:

We have created a small module in the REPL that defines three foo methods. It's a classic example of ambiguous methods—if we pass two integer arguments, then it is unclear whether the second or the third foo method should be executed. Now, let's use the detect_ambiguities function and see if it can detect the problem:

The result is telling us that the foo(x::Integer, y) and foo(x, y::Integer) functions are ambiguous. As we've already learned how to fix that problem, we can do that and test again:

In fact, the detect_ambiguities function is even more useful when you have functions that extend functions from other modules. In this case, you can just call the detect_ambiguities function with the modules that you want to check all together. Here's how it works when you pass two modules:

In this hypothetical example, the Foo4 module imports the Foo2.foo function and extends it by adding a new method. The Foo2 module by itself would be ambiguous, but combining both modules resolves the ambiguity.

So when should we make use of this great detective function? A good way to do this is to add the detect_ambiguities test in the module's automated test suite so that it is executed in the continuous integration pipeline for every build.

Now that we know how to use this ambiguity detection tool, we can use multiple dispatch without fear! In the next section, we will go over another aspect of dispatch called dynamic dispatch.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.35.148