blob: 135b3093bba2ea0128783d1f3ae3746f0500022b [file] [log] [blame]
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +00001*vim9class.txt* For Vim version 9.0. Last change: 2023 Jan 09
Bram Moolenaarc1c365c2022-12-04 20:13:24 +00002
3
4 VIM REFERENCE MANUAL by Bram Moolenaar
5
6
7NOTE - This is under development, anything can still change! - NOTE
8
9
10Vim9 classes, objects, interfaces, types and enums.
11
121. Overview |Vim9-class-overview|
132. A simple class |Vim9-simple-class|
143. Using an abstract class |Vim9-abstract-class|
154. Using an interface |Vim9-using-interface|
165. More class details |Vim9-class|
176. Type definition |Vim9-type|
187. Enum |Vim9-enum|
19
209. Rationale
2110. To be done later
22
23==============================================================================
24
251. Overview *Vim9-class-overview*
26
27The fancy term is "object-oriented programming". You can find lots of study
28material about this subject. Here we document what |Vim9| script provides,
29assuming you know the basics already. Added are helpful hints about how
30to use this functionality effectively.
31
32The basic item is an object:
33- An object stores state. It contains one or more variables that can each
34 have a value.
35- An object usually provides functions that manipulate its state. These
36 functions are invoked "on the object", which is what sets it apart from the
37 traditional separation of data and code that manipulates the data.
38- An object has a well defined interface, with typed member variables and
39 member functions.
40- Objects are created by a class and all objects have the same interface.
41 This never changes, it is not dynamic.
42
43An object can only be created by a class. A class provides:
44- A new() method, the constructor, which returns an object for the class.
45 This method is invoked on the class name: MyClass.new().
46- State shared by all objects of the class: class variables and constants.
47- A hierarchy of classes, with super-classes and sub-classes, inheritance.
48
49An interface is used to specify properties of an object:
50- An object can declare several interfaces that it implements.
51- Different objects implementing the same interface can be used the same way.
52
53The class hierarchy allows for single inheritance. Otherwise interfaces are
54to be used where needed.
55
56
57Class modeling ~
58
59You can model classes any way you like. Keep in mind what you are building,
60don't try to model the real world. This can be confusing, especially because
61teachers use real-world objects to explain class relations and you might think
62your model should therefore reflect the real world. It doesn't! The model
63should match your purpose.
64
65You will soon find that composition is often better than inheritance. Don't
66waste time trying to find the optimal class model. Or waste time discussing
67whether a square is a rectangle or that a rectangle is a square. It doesn't
68matter.
69
70
71==============================================================================
72
732. A simple class *Vim9-simple-class*
74
75Let's start with a simple example: a class that stores a text position: >
76
77 class TextPosition
78 this.lnum: number
79 this.col: number
80
81 def new(lnum: number, col: number)
82 this.lnum = lnum
83 this.col = col
84 enddef
85
86 def SetLnum(lnum: number)
87 this.lnum = lnum
88 enddef
89
90 def SetCol(col: number)
91 this.col = col
92 enddef
93
94 def SetPosition(lnum: number, col: number)
95 this.lnum = lnum
96 this.col = col
97 enddef
98 endclass
Bram Moolenaar7db29e42022-12-11 15:53:04 +000099< *object* *Object*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000100You can create an object from this class with the new() method: >
101
102 var pos = TextPosition.new(1, 1)
103
104The object members "lnum" and "col" can be accessed directly: >
105
106 echo $'The text position is ({pos.lnum}, {pos.col})'
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000107< *E1317* *E1327*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000108If you have been using other object-oriented languages you will notice that
109in Vim the object members are consistently referred to with the "this."
110prefix. This is different from languages like Java and TypeScript. This
111naming convention makes the object members easy to spot. Also, when a
112variable does not have the "this." prefix you know it is not an object member.
113
114
115Member write access ~
116
117Now try to change an object member directly: >
118
119 pos.lnum = 9
Bram Moolenaarf1dcd142022-12-31 15:30:45 +0000120< *E1335*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000121This will give you an error! That is because by default object members can be
122read but not set. That's why the class provides a method for it: >
123
124 pos.SetLnum(9)
125
126Allowing to read but not set an object member is the most common and safest
127way. Most often there is no problem using a value, while setting a value may
128have side effects that need to be taken care of. In this case, the SetLnum()
129method could check if the line number is valid and either give an error or use
130the closest valid value.
Bram Moolenaarf1dcd142022-12-31 15:30:45 +0000131 *:public* *E1331*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000132If you don't care about side effects and want to allow the object member to be
133changed at any time, you can make it public: >
134
135 public this.lnum: number
136 public this.col number
137
138Now you don't need the SetLnum(), SetCol() and SetPosition() methods, setting
139"pos.lnum" directly above will no longer give an error.
Bram Moolenaarf1dcd142022-12-31 15:30:45 +0000140 *E1334*
141If you try to set an object member that doesn't exist you get an error: >
142 pos.other = 9
143< E1334: Object member not found: other ~
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000144
145
146Private members ~
Bram Moolenaarf1dcd142022-12-31 15:30:45 +0000147 *E1332* *E1333*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000148On the other hand, if you do not want the object members to be read directly,
149you can make them private. This is done by prefixing an underscore to the
150name: >
151
152 this._lnum: number
153 this._col number
154
155Now you need to provide methods to get the value of the private members.
156These are commonly call getters. We recommend using a name that starts with
157"Get": >
158
159 def GetLnum(): number
160 return this._lnum
161 enddef
162
163 def GetCol() number
164 return this._col
165 enddef
166
167This example isn't very useful, the members might as well have been public.
168It does become useful if you check the value. For example, restrict the line
169number to the total number of lines: >
170
171 def GetLnum(): number
172 if this._lnum > this._lineCount
173 return this._lineCount
174 endif
175 return this._lnum
176 enddef
177
178
179Simplifying the new() method ~
180
181Many constructors take values for the object members. Thus you very often see
182this pattern: >
183
184 this.lnum: number
185 this.col: number
186
187 def new(lnum: number, col: number)
188 this.lnum = lnum
189 this.col = col
190 enddef
191
192Not only is this text you need to write, it also has the type of each member
193twice. Since this is so common a shorter way to write new() is provided: >
194
195 def new(this.lnum, this.col)
196 enddef
197
198The semantics are easy to understand: Providing the object member name,
199including "this.", as the argument to new() means the value provided in the
200new() call is assigned to that object member. This mechanism is coming from
201the Dart language.
202
203The sequence of constructing a new object is:
2041. Memory is allocated and cleared. All values are zero/false/empty.
2052. For each declared member that has an initializer, the expression is
206 evaluated and assigned to the member. This happens in the sequence the
207 members are declared in the class.
2083. Arguments in the new() method in the "this.name" form are assigned.
2094. The body of the new() method is executed.
210
211TODO: for a sub-class the constructor of the parent class will be invoked
212somewhere.
213
214
215==============================================================================
216
2173. Using an abstract class *Vim9-abstract-class*
218
219An abstract class forms the base for at least one sub-class. In the class
220model one often finds that a few classes have the same properties that can be
221shared, but a class with those properties does not have enough state to create
222an object from. A sub-class must extend the abstract class and add the
223missing state and/or methods before it can be used to create objects for.
224
225An abstract class does not have a new() method.
226
227For example, a Shape class could store a color and thickness. You cannot
228create a Shape object, it is missing the information about what kind of shape
229it is. The Shape class functions as the base for a Square and a Triangle
230class, for which objects can be created. Example: >
231
232 abstract class Shape
233 this.color = Color.Black
234 this.thickness = 10
235 endclass
236
237 class Square extends Shape
238 this.size: number
239
240 def new(this.size)
241 enddef
242 endclass
243
244 class Triangle extends Shape
245 this.base: number
246 this.height: number
247
248 def new(this.base, this.height)
249 enddef
250 endclass
251<
Bram Moolenaarf1dcd142022-12-31 15:30:45 +0000252 *class-member* *:static* *E1337* *E1338*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000253Class members are declared with "static". They are used by the name without a
254prefix: >
255
256 class OtherThing
257 this.size: number
258 static totalSize: number
259
260 def new(this.size)
261 totalSize += this.size
262 enddef
263 endclass
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000264< *E1340* *E1341*
265Since the name is used as-is, shadowing the name by a function argument name
266or variable name is not allowed.
267
268Just like object members the access can be made private by using an underscore
269as the first character in the name, and it can be made public by prefixing
270"public": >
271 class OtherThing
272 static total: number # anybody can read, only class can write
273 static _sum: number # only class can read and write
274 public static result: number # anybody can read and write
275 endclass
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000276<
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000277 *class-function*
278Class functions are also declared with "static". They have no access to
279object members, they cannot use the "this" keyword. >
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000280
281 class OtherThing
282 this.size: number
283 static totalSize: number
284
285 " Clear the total size and return the value it had before.
286 static def ClearTotalSize(): number
287 var prev = totalSize
288 totalSize = 0
289 return prev
290 enddef
291 endclass
292
293
294==============================================================================
295
2964. Using an interface *Vim9-using-interface*
297
298The example above with Shape, Square and Triangle can be made more useful if
299we add a method to compute the surface of the object. For that we create the
300interface called HasSurface, which specifies one method Surface() that returns
301a number. This example extends the one above: >
302
303 abstract class Shape
304 this.color = Color.Black
305 this.thickness = 10
306 endclass
307
308 interface HasSurface
309 def Surface(): number
310 endinterface
311
312 class Square extends Shape implements HasSurface
313 this.size: number
314
315 def new(this.size)
316 enddef
317
318 def Surface(): number
319 return this.size * this.size
320 enddef
321 endclass
322
323 class Triangle extends Shape implements HasSurface
324 this.base: number
325 this.height: number
326
327 def new(this.base, this.height)
328 enddef
329
330 def Surface(): number
331 return this.base * this.height / 2
332 enddef
333 endclass
334
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000335If a class declares to implement an interface, all the items specified in the
336interface must appear in the class, with the same types. *E1348* *E1349*
337
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000338The interface name can be used as a type: >
339
340 var shapes: list<HasSurface> = [
341 Square.new(12),
342 Triangle.new(8, 15),
343 ]
344 for shape in shapes
345 echo $'the surface is {shape.Surface()}'
346 endfor
347
348
349==============================================================================
350
Bram Moolenaar7db29e42022-12-11 15:53:04 +00003515. More class details *Vim9-class* *Class* *class*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000352
353Defining a class ~
354 *:class* *:endclass* *:abstract*
355A class is defined between `:class` and `:endclass`. The whole class is
356defined in one script file. It is not possible to add to a class later.
357
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000358A class can only be defined in a |Vim9| script file. *E1316*
Bram Moolenaar00b28d62022-12-08 15:32:33 +0000359A class cannot be defined inside a function.
360
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000361It is possible to define more than one class in a script file. Although it
362usually is better to export only one main class. It can be useful to define
363types, enums and helper classes though.
364
365The `:abstract` keyword may be prefixed and `:export` may be used. That gives
366these variants: >
367
368 class ClassName
369 endclass
370
371 export class ClassName
372 endclass
373
374 abstract class ClassName
375 endclass
376
377 export abstract class ClassName
378 endclass
379<
380 *E1314*
381The class name should be CamelCased. It must start with an uppercase letter.
382That avoids clashing with builtin types.
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000383 *E1315*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000384After the class name these optional items can be used. Each can appear only
385once. They can appear in any order, although this order is recommended: >
386 extends ClassName
387 implements InterfaceName, OtherInterface
388 specifies SomeInterface
389< *extends*
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000390A class can extend one other class. *E1352* *E1353* *E1354*
391 *implements* *E1346* *E1347*
392A class can implement one or more interfaces. The "implements" keyword can
393only appear once *E1350* . Multiple interfaces can be specified, separated by
394commas. Each interface name can appear only once. *E1351*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000395 *specifies*
Bram Moolenaar00b28d62022-12-08 15:32:33 +0000396A class can declare its interface, the object members and methods, with a
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000397named interface. This avoids the need for separately specifying the
Bram Moolenaar00b28d62022-12-08 15:32:33 +0000398interface, which is often done in many languages, especially Java.
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000399
400
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000401Items in a class ~
402 *E1318* *E1325* *E1326*
403Inside a class, in betweeen `:class` and `:endclass`, these items can appear:
404- An object member declaration: >
405 this._memberName: memberType
406 this.memberName: memberType
407 public this.memberName: memberType
408- A constructor method: >
409 def new(arguments)
410 def newName(arguments)
411- An object method: >
412 def SomeMethod(arguments)
Bram Moolenaarf1dcd142022-12-31 15:30:45 +0000413< *E1329*
414For the object member the type must be specified. The best way is to do this
415explicitly with ": {type}". For simple types you can also use an initializer,
416such as "= 123", and Vim will see that the type is a number. Avoid doing this
417for more complex types and when the type will be incomplete. For example: >
418 this.nameList = []
419This specifies a list, but the item type is unknown. Better use: >
420 this.nameList: list<string>
421The initialization isn't needed, the list is empty by default.
422 *E1330*
423Some types cannot be used, such as "void", "null" and "v:none".
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000424
425
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000426Defining an interface ~
427 *:interface* *:endinterface*
428An interface is defined between `:interface` and `:endinterface`. It may be
429prefixed with `:export`: >
430
431 interface InterfaceName
432 endinterface
433
434 export interface InterfaceName
435 endinterface
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000436< *E1344*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000437An interface can declare object members, just like in a class but without any
438initializer.
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000439 *E1345*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000440An interface can declare methods with `:def`, including the arguments and
441return type, but without the body and without `:enddef`. Example: >
442
443 interface HasSurface
444 this.size: number
445 def Surface(): number
446 endinterface
447
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000448An interface name must start with an uppercase letter. *E1343*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000449The "Has" prefix can be used to make it easier to guess this is an interface
450name, with a hint about what it provides.
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000451An interface can only be defined in a |Vim9| script file. *E1342*
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000452
453
454Default constructor ~
455
456In case you define a class without a new() method, one will be automatically
457defined. This default constructor will have arguments for all the object
458members, in the order they were specified. Thus if your class looks like: >
459
460 class AutoNew
461 this.name: string
462 this.age: number
463 this.gender: Gender
464 endclass
465
466Then The default constructor will be: >
467
Bram Moolenaar65b0d162022-12-13 18:43:22 +0000468 def new(this.name = v:none, this.age = v:none, this.gender = v:none)
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000469 enddef
470
Bram Moolenaar65b0d162022-12-13 18:43:22 +0000471The "= v:none" default values make the arguments optional. Thus you can also
472call `new()` without any arguments. No assignment will happen and the default
473value for the object members will be used. This is a more useful example,
474with default values: >
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000475
476 class TextPosition
477 this.lnum: number = 1
478 this.col: number = 1
479 endclass
480
481If you want the constructor to have mandatory arguments, you need to write it
482yourself. For example, if for the AutoNew class above you insist on getting
483the name, you can define the constructor like this: >
484
Bram Moolenaar65b0d162022-12-13 18:43:22 +0000485 def new(this.name, this.age = v:none, this.gender = v:none)
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000486 enddef
Bram Moolenaar65b0d162022-12-13 18:43:22 +0000487< *E1328*
488Note that you cannot use another default value than "v:none" here. If you
489want to initialize the object members, do it where they are declared. This
490way you only need to look in one place for the default values.
Bram Moolenaar7db29e42022-12-11 15:53:04 +0000491
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000492All object members will be used in the default constructor, also private
493access ones.
494
495If the class extends another one, the object members of that class will come
496first.
497
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000498
499Multiple constructors ~
500
501Normally a class has just one new() constructor. In case you find that the
502constructor is often called with the same arguments you may want to simplify
503your code by putting those arguments into a second constructor method. For
504example, if you tend to use the color black a lot: >
505
506 def new(this.garment, this.color, this.size)
507 enddef
508 ...
509 var pants = new(Garment.pants, Color.black, "XL")
510 var shirt = new(Garment.shirt, Color.black, "XL")
511 var shoes = new(Garment.shoes, Color.black, "45")
512
513Instead of repeating the color every time you can add a constructor that
514includes it: >
515
516 def newBlack(this.garment, this.size)
517 this.color = Color.black
518 enddef
519 ...
520 var pants = newBlack(Garment.pants, "XL")
521 var shirt = newBlack(Garment.shirt, "XL")
522 var shoes = newBlack(Garment.shoes, "9.5")
523
524Note that the method name must start with "new". If there is no method called
525"new()" then the default constructor is added, even though there are other
526constructor methods.
527
528
529==============================================================================
530
5316. Type definition *Vim9-type* *:type*
532
533A type definition is giving a name to a type specification. For Example: >
534
535 :type ListOfStrings list<string>
536
537TODO: more explanation
538
539
540==============================================================================
541
5427. Enum *Vim9-enum* *:enum* *:endenum*
543
544An enum is a type that can have one of a list of values. Example: >
545
546 :enum Color
547 White
548 Red
549 Green
550 Blue
551 Black
552 :endenum
553
554TODO: more explanation
555
556
557==============================================================================
558
5599. Rationale
560
561Most of the choices for |Vim9| classes come from popular and recently
562developed languages, such as Java, TypeScript and Dart. The syntax has been
563made to fit with the way Vim script works, such as using `endclass` instead of
564using curly braces around the whole class.
565
566Some common constructs of object-oriented languages were chosen very long ago
567when this kind of programming was still new, and later found to be
568sub-optimal. By this time those constructs were widely used and changing them
569was not an option. In Vim we do have the freedom to make different choices,
570since classes are completely new. We can make the syntax simpler and more
571consistent than what "old" languages use. Without diverting too much, it
572should still mostly look like what you know from existing languages.
573
574Some recently developed languages add all kinds of fancy features that we
575don't need for Vim. But some have nice ideas that we do want to use.
576Thus we end up with a base of what is common in popular languages, dropping
577what looks like a bad idea, and adding some nice features that are easy to
578understand.
579
580The main rules we use to make decisions:
581- Keep it simple.
582- No surprises, mostly do what other languages are doing.
583- Avoid mistakes from the past.
584- Avoid the need for the script writer to consult the help to understand how
585 things work, most things should be obvious.
586- Keep it consistent.
587- Aim at an average size plugin, not at a huge project.
588
589
590Using new() for the constructor ~
591
592Many languages use the class name for the constructor method. A disadvantage
593is that quite often this is a long name. And when changing the class name all
594constructor methods need to be renamed. Not a big deal, but still a
595disadvantage.
596
597Other languages, such as TypeScript, use a specific name, such as
598"constructor()". That seems better. However, using "new" or "new()" to
599create a new object has no obvious relation with "constructor()".
600
601For |Vim9| script using the same method name for all constructors seemed like
602the right choice, and by calling it new() the relation between the caller and
603the method being called is obvious.
604
605
606No overloading of the constructor ~
607
608In Vim script, both legacy and |Vim9| script, there is no overloading of
609functions. That means it is not possible to use the same function name with
610different types of arguments. Therefore there also is only one new()
611constructor.
612
613With |Vim9| script it would be possible to support overloading, since
614arguments are typed. However, this gets complicated very quickly. Looking at
615a new() call one has to inspect the types of the arguments to know which of
616several new() methods is actually being called. And that can require
617inspecting quite a bit of code. For example, if one of the arguments is the
618return value of a method, you need to find that method to see what type it is
619returning.
620
621Instead, every constructor has to have a different name, starting with "new".
622That way multiple constructors with different arguments are possible, while it
623is very easy to see which constructor is being used. And the type of
624arguments can be properly checked.
625
626
627No overloading of methods ~
628
629Same reasoning as for the constructor: It is often not obvious what type
630arguments have, which would make it difficult to figure out what method is
631actually being called. Better just give the methods a different name, then
632type checking will make sure it works as you intended. This rules out
633polymorphism, which we don't really need anyway.
634
635
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000636Single inheritance and interfaces ~
637
638Some languages support multiple inheritance. Although that can be useful in
639some cases, it makes the rules of how a class works quite complicated.
640Instead, using interfaces to declare what is supported is much simpler. The
641very popular Java language does it this way, and it should be good enough for
642Vim. The "keep it simple" rule applies here.
643
644Explicitly declaring that a class supports an interface makes it easy to see
645what a class is intended for. It also makes it possible to do proper type
646checking. When an interface is changed any class that declares to implement
647it will be checked if that change was also changed. The mechanism to assume a
648class implements an interface just because the methods happen to match is
649brittle and leads to obscure problems, let's not do that.
650
651
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000652Using "this.member" everywhere ~
653
654The object members in various programming languages can often be accessed in
655different ways, depending on the location. Sometimes "this." has to be
656prepended to avoid ambiguity. They are usually declared without "this.".
657That is quite inconsistent and sometimes confusing.
658
659A very common issue is that in the constructor the arguments use the same name
660as the object member. Then for these members "this." needs to be prefixed in
661the body, while for other members this is not needed and often omitted. This
662leads to a mix of members with and without "this.", which is inconsistent.
663
664For |Vim9| classes the "this." prefix is always used. Also for declaring the
665members. Simple and consistent. When looking at the code inside a class it's
666also directly clear which variable references are object members and which
667aren't.
668
669
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000670Using class members ~
671
672Using "static member" to declare a class member is very common, nothing new
673here. In |Vim9| script these can be accessed directly by their name. Very
674much like how a script-local variable can be used in a function. Since object
675members are always accessed with "this." prepended, it's also quickly clear
676what kind of member it is.
677
678TypeScript prepends the class name before the class member, also inside the
679class. This has two problems: The class name can be rather long, taking up
680quite a bit of space, and when the class is renamed all these places need to
681be changed too.
682
683
Bram Moolenaar1b5f03e2023-01-09 20:12:45 +0000684Declaring object and class members ~
685
686The main choice is whether to use "var" as with variable declarations.
687TypeScript does not use it: >
688 class Point {
689 x: number;
690 y = 0;
691 }
692
693Following that Vim object members could be declared like this: >
694 class Point
695 this.x: number
696 this.y = 0
697 endclass
698
699Some users pointed out that this looks more like an assignment than a
700declaration. Adding "var" changes that: >
701 class Point
702 var this.x: number
703 var this.y = 0
704 endclass
705
706We also need to be able to declare class members using the "static" keyword.
707There we can also choose to leave out "var": >
708 class Point
709 var this.x: number
710 static count = 0
711 endclass
712
713Or do use it, before "static": >
714 class Point
715 var this.x: number
716 var static count = 0
717 endclass
718
719Or after "static": >
720 class Point
721 var this.x: number
722 static var count = 0
723 endclass
724
725This is more in line with "static def Func()".
726
727There is no clear preference whether to use "var" or not. The two main
728reasons to leave it out are:
7291. TypeScript, Java and other popular languages do not use it.
7302. Less clutter.
731
732
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000733Using "ClassName.new()" to construct an object ~
734
735Many languages use the "new" operator to create an object, which is actually
736kind of strange, since the constructor is defined as a method with arguments,
737not a command. TypeScript also has the "new" keyword, but the method is
738called "constructor()", it is hard to see the relation between the two.
739
740In |Vim9| script the constructor method is called new(), and it is invoked as
741new(), simple and straightforward. Other languages use "new ClassName()",
742while there is no ClassName() method, it's a method by another name in the
743class called ClassName. Quite confusing.
744
745
746Default read access to object members ~
747
748Some users will remark that the access rules for object members are
749asymmetric. Well, that is intentional. Changing a value is a very different
750action than reading a value. The read operation has no side effects, it can
751be done any number of times without affecting the object. Changing the value
752can have many side effects, and even have a ripple effect, affecting other
753objects.
754
755When adding object members one usually doesn't think much about this, just get
756the type right. And normally the values are set in the new() method.
757Therefore defaulting to read access only "just works" in most cases. And when
758directly writing you get an error, which makes you wonder if you actually want
759to allow that. This helps writing code with fewer mistakes.
760
761
Bram Moolenaar00b28d62022-12-08 15:32:33 +0000762Making object members private with an underscore ~
Bram Moolenaarc1c365c2022-12-04 20:13:24 +0000763
764When an object member is private, it can only be read and changed inside the
765class (and in sub-classes), then it cannot be used outside of the class.
766Prepending an underscore is a simple way to make that visible. Various
767programming languages have this as a recommendation.
768
769In case you change your mind and want to make the object member accessible
770outside of the class, you will have to remove the underscore everywhere.
771Since the name only appears in the class (and sub-classes) they will be easy
772to find and change.
773
774The other way around is much harder: you can easily prepend an underscore to
775the object member inside the class to make it private, but any usage elsewhere
776you will have to track down and change. You may have to make it a "set"
777method call. This reflects the real world problem that taking away access
778requires work to be done for all places where that access exists.
779
780An alternative would have been using the "private" keyword, just like "public"
781changes the access in the other direction. Well, that's just to reduce the
782number of keywords.
783
784
785No protected object members ~
786
787Some languages provide several ways to control access to object members. The
788most known is "protected", and the meaning varies from language to language.
789Others are "shared", "private" and even "friend".
790
791These rules make life more difficult. That can be justified in projects where
792many people work on the same, complex code where it is easy to make mistakes.
793Especially when refactoring or other changes to the class model.
794
795The Vim scripts are expected to be used in a plugin, with just one person or a
796small team working on it. Complex rules then only make it more complicated,
797the extra safety provide by the rules isn't really needed. Let's just keep it
798simple and not specify access details.
799
800
801==============================================================================
802
80310. To be done later
804
805Can a newSomething() constructor invoke another constructor? If yes, what are
806the restrictions?
807
808Thoughts:
809- Generics for a class: `class <Tkey, Tentry>`
810- Generics for a function: `def <Tkey> GetLast(key: Tkey)`
811- Mixins: not sure if that is useful, leave out for simplicity.
812
813Some things that look like good additions:
814- For testing: Mock mechanism
815
816An important class to be provided is "Promise". Since Vim is single
817threaded, connecting asynchronous operations is a natural way of allowing
818plugins to do their work without blocking the user. It's a uniform way to
819invoke callbacks and handle timeouts and errors.
820
821
822 vim:tw=78:ts=8:noet:ft=help:norl: