Tuesday, February 20, 2024

Some comments on :help E1377 (subclassing and constructors)

:help E1377 has this paragraph:

Unlike other languages, the constructor of the base class does not
need to be invoked. In fact, it cannot be invoked. If some
initialization from the base class also needs to be done in a child
class, put it in an object method and call that method from every
constructor().

That seems accurate, as in the following script `Bar` has its own
(implicitly defined) constructor, and the parent's constructor is not
invoked (no message is printed):

vim9script

class Foo
var _y = 0

def new(this._y, z: string)
this.Init(z)
enddef

def Init(z: string)
echomsg $'y={this._y}, z={z}'
enddef
endclass

class Bar extends Foo
endclass

var bar = Bar.new(1) # Sets _y to 1, doesn't print anything

Now, I have a couple of remarks:

It seems a bit counterintuitive that `Bar` cannot be initialized like
`Foo`, but with either `Bar.new()` or `Bar.new(n)`.

It may be the case that `Init()` does something necessary for the
initialization of the object. But `Bar` does not call `Init()`, so `bar`
may be potentially broken.

Ok, all that is as documented and can be remedied, of course:

class Bar extends Foo
def new(this._y, z: string)
this.Init(z)
enddef
endclass

var bar = Bar.new(1, 'a') # OK

But:

- I have basically redefined the same constructor of the superclass;
- I must know the private members of `Foo` to do that;
- I must be aware that any constructor must call `Init()` for the
correct initialization of the object. Again, I must know an
implementation detail of the superclass.

Note that `Foo` may be a library object imported by arbitrary users in
arbitrary scripts.

Wouldn't it make more sense for `Bar` to have the parent's constructor
as a default?

Thanks,
Life.

--
--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

---
You received this message because you are subscribed to the Google Groups "vim_use" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vim_use+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/vim_use/ur2trf%24hf%241%40ciao.gmane.io.

No comments: