TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Allow visibility on constructors

Open bpasero opened this issue 11 years ago • 42 comments

I think it is a pretty common pattern to have a static factory method to create a class and the constructor of this class being otherwise private so that you cannot instantiate the class unless you use the factory method.

bpasero avatar Mar 13 '15 09:03 bpasero

Since all "classes" are actually just functions and since there's no such thing as uncallable function, anywhere the class is visible you can also use the new operator on it.

You can however make the class non-public (e.g. in a module) and export an interface for the class. This abuses the fact that interfaces can extend classes but they're not directly instantiable nor extendable.

qc00 avatar Mar 13 '15 14:03 qc00

Well the same applies to private functions in classes, right? I don't see why we could not get a compile error for accessing a private constructor.

bpasero avatar Mar 13 '15 18:03 bpasero

@billccn I don't like to kill requests by "JS allows then you will not be able to hide". On thing is protect completely in TS & generated JS, other thing is to protect that to the point of generating JS. As you have explained the full protection is not possible, but having different visibility checked by compiler, should be possible. If you don't like visibility modifiers, then use default public everywhere, there are other that find that concept useful.

wgebczyk avatar Mar 14 '15 10:03 wgebczyk

Yeah, I guess if the private fields are implemented as a compiler check only, then it can probably be extended to constructors. However, the interface-based workaround already works though.

qc00 avatar Mar 14 '15 17:03 qc00

:+1: There are times when I want to force the programmer to use the factory methods for code readability. The interface-based workaround creates a lot of noise in the code.

I think the compiler check only is the way to go.

dsherret avatar Mar 26 '15 01:03 dsherret

Accepted, accepting PRs

RyanCavanaugh avatar May 19 '15 16:05 RyanCavanaugh

To clarify, could a class with a private constructor be extendable?

i.e. Would this throw an error?

class A {
    private constructor() {
    }
}

class B extends A { // Should there be an error at A saying: "Cannot extend private class 'A'"?
}

if so, would we then allow this:

class A {
    protected constructor(a?: any)
    private constructor() {

    }
}

class B extends A { // No error since 'A' has a non-private constructor
}

AbubakerB avatar Aug 05 '15 08:08 AbubakerB

From non-JS developer experience that's expected behaviour.

wgebczyk avatar Aug 05 '15 08:08 wgebczyk

In the first example, B should be an error because its implicit super call is illegal. So a class with a private constructor is effectively sealed/final.

In the second example, A's declaration should be an error because all overloads of a constructor, and its implementation, must have the same visibility (same rule we have for methods).

RyanCavanaugh avatar Aug 05 '15 17:08 RyanCavanaugh

See also #471. Is it really required to allow constructors to be private or will protected do?

benliddicott avatar Sep 08 '15 14:09 benliddicott

@benliddicott it's sometimes useful to force a singleton or to force the programmer to use one of the static methods to create an object, because sometimes it can be more readable.

See here.

dsherret avatar Sep 08 '15 21:09 dsherret

@dsherret protected meets all those needs.

But you cannot be sure that a downstream user will never have a legitimate need to inherit from your class. The only effect of private is to prevent your downstream users meeting a need you didn't anticipate.

benliddicott avatar Sep 09 '15 09:09 benliddicott

@benliddicott Sometimes the only thing you want is for a class to be unextendable. I refer you to Effective Java Item 15 Minimize Mutability, especially:

"2. Ensure that the class can’t be extended. This prevents careless or malicious subclasses from compromising the immutable behavior of the class by behaving as if the object’s state has changed. Preventing subclassing is generally accomplished by making the class final, but there is an alternative that we’ll discuss later.

Currently there's no final/sealed support in TypeScript, so a private constructor is the only way to achieve an immutable class from the type system's perspective. (Though, I do recommend people also freeze the object in the constructor.)

qc00 avatar Sep 09 '15 10:09 qc00

@billccn , that author's opinion is interesting. So is the idea that the library writer's opinion should override that of the library user. My own experience has been that library writers don't know when to use private, and over-use it, causing headaches for users, simply because they believe they know how their library will be used, when in fact they do not.

But rather than a static language like Java, a more apt comparison would be Perl, another dynamic language: http://www.perlmonks.org/?node_id=437623

One of the reasons why perl doesn't have access modifiers such as public, private, and protected, is because it's recognised that they often get in the way of getting the job done: what was envisioned by the original designer has nothing to do with what you want to do with it. In the same way, design for flexibility - although you may not see yourself needing it now, the next person to come along may see it being incredibly handy to solve that new problem, and will bless your genius for developing that flexibility ;-)

and:

Perl doesn't have an infatuation with enforced privacy. It would prefer that you stayed out of its living room because you weren't invited, not because it has a shotgun

http://www.perlmonks.org/?node_id=1096925

In fact JavaScript is the same, and - yes - TypeScript is the same, in almost every respect. In typescript you can access private members just fine - using the aptly named escape-hatch: obj["propertyName"].

If as a library writer you suspect it is unwise to call a method or inherit from an object, then tell the user it is unwise. But don't prevent them - they may know better than you after all.

benliddicott avatar Sep 09 '15 11:09 benliddicott

I don't understand the discussion about "protected being sufficient". If TS has the concept of visibilty and I can apply this concept to constructors, the answer is "it is not sufficient".

bpasero avatar Sep 09 '15 11:09 bpasero

If access modifiers are allowed on the constructor then I think it should have consistent behaviour with other modifiers and allow private.

Private members in general are for sure useful. They allow you to organize and refactor the implementation details of a class without worrying about causing side effects outside the class.

With private constructors I might want to force the developers on my team to program in a certain way. For example, I might want to force them to use the static method here because it's more readable and force them not to extend this class:

class Currency {
    private constructor(private value: number, private type: CurrencyType) {
    }

    static fromNumberAndType(value: number, type: CurrencyType) {
        return new Currency(value, type);
    }

    static fromString(str: string) {
        const value = ...,
              type  = ...;

        return new Currency(value, type);
    }

    // ... omitted ...
}

// error:
const badCurrency = new Currency(5.66, CurrencyType.USD);
// ok:
const goodCurrency1 = Currency.fromNumberAndType(5.66, CurrencyType.USD);
const goodCurrency2 = Currency.fromString("5.66 USD");

dsherret avatar Sep 09 '15 15:09 dsherret

With private constructors I might want to force the developers on my team to program in a certain way.

That's a management issue not a language design issue.

benliddicott avatar Sep 10 '15 08:09 benliddicott

@benliddicott The similar you can say about type descriptors on variables :) If you don't like the feature just use plain JS. OR Use TS and create some lint-like rules that prohibit usage of private on constructor.To paraphrase your last comment: "That's tooling issue not language design issue".

wgebczyk avatar Sep 10 '15 08:09 wgebczyk

@benliddicott if something is not possible to do then I won't have to send it back when it's wrong after doing a code review. That saves time.

Telling the compiler exactly how the code should be used correctly is an asset that gives the proper feedback to the developer using it as they are programming.

dsherret avatar Sep 10 '15 14:09 dsherret

@dsherret No it's an arbitrary constraint that empowers Architecture astronauts :-1:

jbondc avatar Sep 20 '15 15:09 jbondc