Skip to content

Instantly share code, notes, and snippets.

@sam
Created July 2, 2014 19:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sam/58a29428e5fafb927eae to your computer and use it in GitHub Desktop.
Save sam/58a29428e5fafb927eae to your computer and use it in GitHub Desktop.
To Override or Not To Override (that is the question)
// To Override or Not To Override (that is the question):
trait Foo {
def close: Unit
def bar(baz: String): Int
def zed(y: Int): Int = y * 2
}
class No {
// Override is unnecessary since the method is abstract.
// You’ll get a compiler error for not implementing it properly
// here either way.
def close = ()
// Same deal here, except if the abstract signature changes, then
// you’ll still get the same error as above.
def bar(baz: String) = baz.length
// If you want to override the default implementation then you have to
// use the override modifier here no matter what. Leaving it off makes
// it overloaded instead, so you don’t have a choice.
override def zed(y: Int) = y * 10
}
class Yes {
// Doesn’t do anything for you right now, and if the trait later implements
// this method, your now useless override will silently pass. The non-
// overridden variation has the advantage of throwing an error when the
// abstract method changes to a default method. No override: +1
override def close = ()
// Same deal as above. If the trait later implements the method,
// this will silently swallow what would otherwise have been a helpful
// error. If the trait changes the signature you’d get an error either way.
// No override: +1
override def bar(baz: String) = baz.length
// Remember that this override wasn’t optional anyways.
// So wether the method signature changed, or the implementation, etc
// doesn’t really matter.
override def zed(y: Int): Int = y * 2
}
// So the winner: Do not unnecessarily override abstract methods. It never produces *more* feedback,
// and can actually cause unnecessary code to remain silently hidden instead of prompting review with
// a helpful compiler error.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment