开发者

Using the override keyword on implementations of abstract methods

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 开发者_JAVA百科optional; but is it advisable? On which side of the terseness vs. safety trade-off should I fall?


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.


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜