0

I am designing a class and some methods are designed to be overriden in subclasses. Which of these ways is better or what are pros and cons?

Way 1:

class Foo(foo: (Int) => Unit = _=>{})

Way 2:

class Bar {
  def bar(int: Int) = {}
}

I understand that foo is a function value and bar is a method (so foo cannot define default values for parameters) and Bar could be a trait (unlike Foo), but is there more?

Beryllium
  • 12,808
  • 10
  • 56
  • 86
Krever
  • 1,371
  • 1
  • 13
  • 32
  • Read this to help you decide whether to use functions or methods : http://stackoverflow.com/q/4839537/3248346 –  Feb 27 '15 at 19:00
  • If you are looking to build class-hierarchy... then the second should be more preferable. – sarveshseri Feb 27 '15 at 19:08

1 Answers1

0

In the first case, every instance of Foo could have a different function passed in. In the second case, each function requires a different subclass.

Which is better? It depends on what you need. If the second, subclass style works for your application, it's probably better, because the code will probably be more understandable. But if you really need to decouple the function from the implementation of this class hierarchy - give the client code total flexibility - then use the first.

The second style also may be slightly faster in some contexts, but rarely enough to matter.

Ed Staub
  • 15,480
  • 3
  • 61
  • 91