Ad

In cases where there is a possibility of going outside the int range, it's good to prevent it from returning the wrong product. Doesn't have to be an exception, but should be documented so other developers can tell what cases they have to take into account when they use your function. I'm for exceptions because it forces developers to deal with scenarios rather than just ignore the warnings in the documentation or to just not read the documentation.

If you know that you will never have the possibility of going out of the int's range, then this is overkill.

As for test cases I'm a proponent that test cases should only test one scenario. I find multiple asserts are fine, if you need to check multiple things to verify the scenario. If you need/want to test ranges or multiple values in one scenario, then refactor them into parameters for the test cases so the testing framework can do it's job and your test cases will be as simple as possible. If possible.

Code
Diff
  • using System;
    
    public class Multiplication
    {
        // Multiply two integers
        // Throws error if the product is outside of the int range.
        // This would otherwise silently error and return the wrong product.
        public long Multiply(int a, int b) {
          long res = (long)a * (long)b;
          
          // make sure it's still a valid int
          if (res > Int32.MaxValue || res < Int32.MinValue)
            throw new InvalidOperationException("Product is outside range of int");
          
          return res;
        }
    }
    • using System;
    • public class Multiplication
    • {
    • public int Multip(int a, int b)
    • {
    • return a * b;
    • // Multiply two integers
    • // Throws error if the product is outside of the int range.
    • // This would otherwise silently error and return the wrong product.
    • public long Multiply(int a, int b) {
    • long res = (long)a * (long)b;
    • // make sure it's still a valid int
    • if (res > Int32.MaxValue || res < Int32.MinValue)
    • throw new InvalidOperationException("Product is outside range of int");
    • return res;
    • }
    • }