24

Is it good practice to use the override keyword when implementing abstract methods defined in traits?

trait Tooth {
  def ache(): Unit
}

class Molar extends Tooth {
  override def ache(): Unit = {}
}

In the above example, I understand that the override keyword is optional; but is it advisable? On which side of the terseness vs. safety trade-off should I fall?

0

4 Answers 4

27

override does one thing for you there: when removing Tooth.ache but not its implementations later on, you will get compiler errors. In particular, this forces implementations of Tooth (written by yourself or others) to be "close" to Tooth in a certain sense, namely that deprecated methods vanish (or are at least reconsidered).

This may or may not be desired.

2
  • 11
    OTOH, if somebody someday puts an implementation of ache inside Tooth, aiming to provide the eventual final solution, he/she will not even know that there will still be old implementations in the code.
    – user445107
    Mar 4, 2014 at 16:57
  • 3
    I agree with this. I have seen numerous examples of dead code because an abstract method was renamed. Jul 2, 2015 at 18:33
15

Personally, when I see

override def whatever()

the first thing I think is, "I wonder how this was supposed to behave before?"

Since this is an unhelpful thought if it was an abstract method, I find it both more terse and more safe to leave it off.

12

I usually don't use override when implementing an abstract method. It's not wrong, but redundant, and I prefer to keep my code as short as possible while maintaining clarity. But I realize it's not a clear-cut case.

0
8

I always use it, to indicate member that were declared on super classes, even if abstract.

2
  • 1
    I believe this is the best answer (by far), but it limits itself by being too brief. I would add that an override has a much distinct intention from a regular method (a new method only adds behavior; an override potentially changes it). And whenever different intention is needed, it is best to make it explicit.
    – rsenna
    May 23, 2013 at 18:08
  • 1
    OTOH, if somebody someday puts an implementation of ache inside Tooth, aiming to provide the eventual final solution, he/she will not even know that there will still be old implementations in the code.
    – user445107
    Mar 4, 2014 at 16:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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