The absolute value function is an instance of the norm function in one dimension. I've seen instances of libraries where the absolute value function is overloaded to also take the norm of higher dimensional vectors. Would it be better practice to define a new function, say "norm," or is there some reason why overloading a standardized absolute value function might have benefits.

  • If I should clarify anything about my question, what should I clarify? Jun 9 '20 at 21:53
  • 1
    If you are designing a library of mathematical functions, you are free to define your functions to do whatever you want to do. However, you don't say who you are designing your library for, what uses they would put the library to, what its programming language is, etc. Jun 9 '20 at 22:15
  • @BobDalgleish I was trying to be general about programming languages - this question should apply to any language where overloading is possible. And I think as much as possible I'd like it to apply to any use case. However, I edited my question to hopefully ask a more specific question. Jun 9 '20 at 23:36

You shouldn't overload just because you can, excessive overloading sometimes breaks the principle of least astonishment. More often than not you just shouldn't do that as it makes harder to detect when a scalar is used instead of a vector (or the opposite) by mistake (edit: this applies mainly to regular development, if you are developing a math library then users are supposed to read the documentation so they will be well aware of the overloading).

The absolute value can be considered a particular case of norm, so it would be ok to overload the norm function to return the absolute value for scalar inputs if that makes the code significantly cleaner and the change is understood by the rest of your team. Not all norms are absolute values so other developers wouldn't know what to expect when a abs function is called on a vector, e.g. they may think it applies the abs function to each component.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.