winglang / wing

A programming language for the cloud ☁️ A unified programming model, combining infrastructure and runtime code into one language ⚡
https://winglang.io
Other
5.04k stars 196 forks source link

Private class initializers #4377

Open Chriscbr opened 1 year ago

Chriscbr commented 1 year ago

Feature Spec

Starting in Wing 0.x, class initializers are now private by default, unless specified public using the pub keyword. Previous to this change, it was not possible to define private constructors in Wing.

Here's an example of how private constructors can be used to implement the singleton design pattern:

bring "constructs" as constructs;

class MySingleton {
  pub value: num;
  pub static getInstance(scope: constructs.Construct): MySingleton {
    return new MySingleton() in scope;
  }

  // like all methods, `init` is private by default
  new() {
    // ... perform some one-time calculation maybe
    this.value = 42;
  }
}

class MyService {
  pub new() {
    let s = new MySingleton(); // this should be an error (since `init` is private)
    let s2 = MySingleton.getInstance(this);
    assert(s2.value == 42);
  }
}

new MyService();

Use Cases

There are several common use cases for private constructors:

Implementation Notes

No response

Component

Compiler

Community Notes

eladb commented 1 year ago

Is this proposing that by default it won't be possible to initialize objects from a class?

If so, in the above example it shouldn't be possible to instantiate MyService because its init is private, no?

Chriscbr commented 1 year ago

@eladb Fixed

github-actions[bot] commented 11 months ago

Hi,

This issue hasn't seen activity in 60 days. Therefore, we are marking this issue as stale for now. It will be closed after 7 days. Feel free to re-open this issue when there's an update or relevant information to be added. Thanks!

github-actions[bot] commented 9 months ago

Hi,

This issue hasn't seen activity in 60 days. Therefore, we are marking this issue as stale for now. It will be closed after 7 days. Feel free to re-open this issue when there's an update or relevant information to be added. Thanks!

github-actions[bot] commented 5 months ago

Hi,

This issue hasn't seen activity in 90 days. Therefore, we are marking this issue as stale for now. It will be closed after 7 days. Feel free to re-open this issue when there's an update or relevant information to be added. Thanks!

github-actions[bot] commented 2 months ago

Hi,

This issue hasn't seen activity in 90 days. Therefore, we are marking this issue as stale for now. It will be closed after 7 days. Feel free to re-open this issue when there's an update or relevant information to be added. Thanks!