#951 Introducing parameters to overridden methods

msl Mon 1 Feb 2010

Quick one - wondering whether anyone else has considered the following...

It'd be nice if I could override a method and introduce new parameters on the overridden method. For example:

class MyStr {
  override Str toStr(ToStrFmt fmt := DefaultToStrFmt()) {
    return fmt.genToStr(this)
  }
}

Obviously the new parameters would need default values so that statements calling the non-overriden version still have the correct signatures:

myStr := MyStr()
echo(myStr.toStr)

But if I know (either statically or via fits, is, isnot, et al) that I'm dealing with a method that takes the additional argument I can use it:

myStr := MyStr()
fmt := LongToStrFmt()
echo(myStr.toStr(fmt))

katox Mon 1 Feb 2010

Why would you prefer this model instead of adding a new method? You could do the same by overriding the original method so it delegates to the new one with a default parameter supplied - this wouldn't complicate reflective and dynamic code.

msl Mon 1 Feb 2010

Haven't really thought it through very much, so happy to be shot down in flames as required :)

Taking that approach (with the example above):

class MyStr {
  override Str toStr() {
    return fmtToStr()
  }
  Str fmtToStr(ToStrFmt fmt := DefaultToStrFmt())
  {
    return fmt.genToStr(this)
  }
}

My client code then needs to know to call the new method (but it "knows" that anyway since it's using the argument version):

myStr := MyStr()
fmt := LongToStrFmt()
echo(myStr.fmtToStr(fmt))

I guess the down side is that you now have two methods which by default do much the same thing:

myStr.toStr == myStr.fmtToStr // true

Which strikes me as a little redundant... Point taken though!

brian Mon 1 Feb 2010

Yes it would be nice (there are lots of cases where I've wanted that). But it would seriously complicate reflection. Not to say it couldn't be done, but don't think that is anything to tackle short term.

Login or Signup to reply.