TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Support final classes (non-subclassable)

Open Zorgatone opened this issue 10 years ago • 184 comments

I was thinking it could be useful to have a way to specify that a class should not be subclassed, so that the compiler would warn the user on compilation if it sees another class extending the original one.

On Java a class marked with final cannot be extended, so with the same keyword on TypeScript it would look like this:

final class foo {
    constructor() {
    }
}

class bar extends foo { // Error: foo is final and cannot be extended
    constructor() {
        super();
    }
}

Zorgatone avatar Apr 26 '16 13:04 Zorgatone

A real case I would be using final is to prevent overriding a method with something which would never call the super method. Some public method of course. But the real solution I figured out would be the ability to force any sub method to call the super one. https://github.com/Microsoft/TypeScript/issues/21388

Xample avatar Nov 21 '18 19:11 Xample

As I'm not a language designer, I can't speak to the drawbacks of adding a keyword to the language. I will say that I am currently working on an abstract superclass that has a method I intend to be final, but to my dismay found that I couldn't make it so. For now I will go with the less-than-ideal approach of putting a comment, but team members implementing the class might not read said comment.

I think that above there are plenty of excellent examples of when/where final would be not only useful, but provide real value and real safety to the platform being built. It's no different for me. As I said, I don't know much about language design complexities but this is clearly a feature that people want/will use/I can't really see a way to abuse it or that it would generate bad code. I understand the concept of fearing scope creep but TS developers don't have to implement everything the community wants.

Just to add my bit to the debate, I would like to put my thumb on the yes-side of the scale because this issue is replete with good arguments supporting the addition of the feature, yet the arguments against that I see are:

  • It could lead to scope creep (this is manageable)
  • People will ask for other features (okay, but who cares, that's part of designing a language and this isn't legal precedent we're setting)
  • It could reduce efficiency (I imagine that since the TS team is full of bad-asses you'd probably find a way to make this manageable)
  • Opinionated "Don't use OOP concepts" comments

None of the above seem like credible threats to the TS ecosystem itself, nor the code that is produced out of it; they all seem political (except maybe the efficiency one, but I have huge confidence in you guys so I'm not really worried about it, plus a minor efficiency decrease would be worth not blowing up important component/library constructs by unwitting inheritance mistakes).

Hope this is constructive! Love TS and want to see it keep improving!

👍

--edit--

In response to @RyanCavanaugh:

So what problem is being solved?

The problem being solved I think is outlined by many, many comments above. I don't mean this as an insult but that question does make it sound, to me, like you aren't actually paying attention to the arguments presented, and that you have your mind set on "no". I don't mean disrespect with that, its just that, honestly, this thread is full of examples of problems that this would solve.

Somehow I missed this comment, which very well outlines a serious concern for adding the feature and that makes sense to me. Again, I don't know the complexity of adding it but efficiency concerns aside (since it's not up to developers to worry about TS efficiency, that's the job of the TS team), there don't seem to be any good arguments against final (in my humblest of opinions).

dudewad avatar Dec 14 '18 21:12 dudewad

Most of the recent discussion has been centered on final methods (less so on final classes). Final methods are certainly my primary interest. I just noticed that if you expand the "this comment" link in @RyanCavanaugh 's previous post that he considers the final method discussion off-topic. However @mhegazy suggested that this ticket is the right place (when closing #9264). So as a lowly end-user I'm baffled as to where I should be asking for/voting for final methods. Guidance would be appreciated.

cbutterfield avatar Dec 14 '18 23:12 cbutterfield

@cbutterfield The contradiction is something that I noticed as well but did not point out in my post for fear of ranting (I actually found THIS thread through #9264 and came here at @mhegazy's direction). @RyanCavanaugh @mhegazy Per the comment above, where is the correct place to discuss final methods, because that actually is the thing I'm most interested in.

dudewad avatar Dec 15 '18 00:12 dudewad

Looking back on my heavily downvoted comment (make sure to go add your 👎 if you haven't yet!) I'm happy to report that React is no longer setting a bad example by forcing a class-based API on its users! With the Hooks proposal, the React team has come to their senses and embraced a radically simpler functional approach. With that, the last reason for many developers to have to use classes at all has evaporated, and good riddance. I'll reiterate: everything you think you need classes for can be done better without them.

The future of JS and TS is classless, praise be!

pelotom avatar Dec 15 '18 01:12 pelotom

@cbutterfield I noticed that too, and if issue #9264 was closed to be discussed in this issue, I think the title should change to Suggestion: Final keyword for classes and methods, otherwise people looking for final methods (exclusively) might not add a reaction in the first post.

lucasbasquerotto avatar Dec 15 '18 10:12 lucasbasquerotto

Quoting @mhegazy: Java and/or C# uses the final class to optimize your class at runtime, knowing that it is not going to be specialized. this i would argue is the main value for final support. In TypeScript there is nothing we can offer to make your code run any better than it did without final.

I fundamentally disagree. I've developed in Java for many years in many teams and we have never used final classes or methods for runtime optimizations; in practice it is primarily a OOP design idiom. Sometimes I just don't want my class or method to be extended/overridden by external subclasses be it to protect and guarantee a function, or to limit a library's API noise to the essentials, or to protect API users from misunderstanding a complex API.

Yes those issues can be solved by adding comments or interfaces, but final is an elegant solution to reducing visible API to the necessary functions when all you want is a simple class with a clean extendable API.

bbottema avatar Jan 04 '19 09:01 bbottema

Even though this issue is nearly 3 years old, we really should have a final keyword as there's already an abstract keyword.

Keep in mind that we do not want to force people to use it and it's a feature as useful as the abstract keyword. But here's another usecase that will strongly show the benefit of a final keyword:



abstract class A {
  protected abstract myVar: string;

  protected abstract myFunction(): void;
}

class B extends A {
  protected readonly myVar: string = "toto";

  constructor() {
    super();
    this.myFunction();
  }

  protected myFunction() {
    console.log(this.myVar);
  }
}

class C extends B {
  constructor() {
    super();
  }

  protected myFunction() {
    console.log("tata");
  };

  public callFunction = () => {
    this.myFunction();
  }
}

const myB = new B(); // toto

const myC = new C(); // toto
myC.callFunction(); // tata

Result after compilation :

toto
toto
tata

So in this code, We have an abstract class A that have abstract methods and properties, we want the inherited class to define them, but we would like to not let any other classes to override those implementations. Best we could do would be to keep the protected keyword, but as you see, we can still redefine the attributes.

So what if we go further in the Typescript compilation process and use the readonly to protect our attributes (and pretend our methods are properties) ?

class B extends A {
  [...]

  protected readonly myFunction = () => {
    console.log(this.myVar);
  }
}

class C extends B {
  protected myVar: string = "I am not protected that much";
  [...]

  protected myFunction = () => { // using the readonly keyword doesn't prevent any modification
    console.log("tata"); // If you launch this code, tata will still be logged in the console.
  };
}

(Note that the code is compiled with tsc, no errors thrown when compiling or executing it) So now we have two problems :

  • We don't protect our B attributes, so we need a way to prevent any unexpected inheritance.
  • Now we know that we can override any readonly properties by extending its class, and YES, Typescript knows that it's the parent property we're changing as using private instead of protected in C class will throw an error as it's not the same access type/visibility.

At the moment, we could use decorators (sealed like the official Typescript documentation shows, or a final decorator ) but remember that it is only useful in runtime, and that we must prevent this in the compilation process instead.

I'll look if there's an issue about the "security breach" (if we can call that) when we want to override a protected readonly value and we actually can and we shouldn't. Otherwise I'll open an issue to debate on the verification of the readonly keyword among private, protected keyword with inheritance stuff.

tl ; dr : The final keyword would solve two problems (though the readonly verification would be a good start to prevent any unauthorized rewrite)

Mcfloy avatar Jan 21 '19 13:01 Mcfloy

Three years later... it's so ridiculous.

GuilhermeLessa avatar Jan 23 '19 12:01 GuilhermeLessa

In order to prove the need for this feature, I suggest to take a look what was done in other languages:

Java:
final class SomeClass { ... }
PHP:
final class SomeClass { ... }
C#:
sealed class SomeClass {...}
C++:
class SomeClass final { ... }
Delphi:
type SomeClass = class sealed() ... end;

So, we see that in all the most popular OOP languages this feature exists because it comes from the inheritance logic of OOP.

pcastornii avatar Jan 28 '19 12:01 pcastornii

Also I have to quote the Dev lead of TS saying

if we have final classes, then we'll "need" final methods or properties as well.

I'm not sure if it's ironic, but in JS the readonly keyword is used for properties (and methods if you cheat), so that's a pretty dumb point.

And maybe not letting one guy closing the issue when he have +40 downvotes meaning the community disagree strongly with him would be a good advice to avoid further dumb situations.

If you're not interested in reinforcing the main feature of Typescript, please say it loud so that tech news can relay that on Twitter, because otherwise, it's a just an hidden bad buzz. You're just ignoring your community, AND you have no process in making the community validating what we need or not.

Mcfloy avatar Jan 28 '19 17:01 Mcfloy

maybe not letting one guy closing the issue when he have +40 downvotes meaning the community disagree strongly with him would be a good advice to avoid further dumb situations

I'm not "one guy". When I make decisions here, it is the reflection of the entire TypeScript team's decision-making process. The design team has looked at this issue multiple times, and each time come to the same conclusion. You are welcome to disagree with that outcome, but the process is not up for debate.

you have no process in making the community validating what we need or not.

This is the process, right here: You calling my summarization of our reasoning "dumb" and me (and other people on the team) reading it. We're listening to the feedback.

RyanCavanaugh avatar Jan 28 '19 17:01 RyanCavanaugh

I know pointing to other implemented features as reasons for considering this one is a smell and not really an argument, but I find it ironic that a type aliasing mechanism was considered and added (it may well be awesome, but one could certainly live without it) but something like this is rejected.

In the end, I can live without such a feature, but the same could be said for about half the features TS has. So, then, what would be an appropriate reason to consider implementing this?

asimonf avatar Jan 28 '19 18:01 asimonf

GitHub unhelpfully hides a lot of comments here, so I'm reposting various responses (plus some additions) we've given in the past. Adding some thoughts in below as well.


Some points were considered when we reviewed this last time

  • CLASSES ARE A JAVASCRIPT FEATURE, NOT A TYPESCRIPT FEATURE. If you really feel like classes are completely useless without final, that is something to take up with the TC39 committee or bring to es-discuss. If no one is willing or able to convince TC39 that final is a must-have feature, then we can consider adding it to TypeScript.
  • If it's legal to invoke new on something, that has a one-to-one runtime correspondence with inheriting from it. The notion of something that can be new'd but not super'd just doesn't exist in JavaScript
  • We are trying our best to avoid turning TypeScript into an OOP keyword soup. There are many better composition mechanics than inheritance in JavaScript and we don't need to have every single keyword that C# and Java have.
  • You can trivially write a runtime check to detect inheritance from a "should-be-final" class, which you really should do anyway if you're "worried" about someone accidently inheriting from your class since not all your consumers might be using TypeScript.
  • You can write a lint rule to enforce a stylistic convention that certain classes aren't inherited from
  • The scenario that someone would "accidently" inherit from your should-be-sealed class is sort of an odd one. I'd also argue that someone's individual assessment of whether or not it's "possible" to inherit from a given class is probably rather suspect.
  • There are basically three reasons to seal a class: Security, performance, and intent. Two of those don't make sense in TypeScript, so we have to consider the complexity vs gain of something that's only doing 1/3rd the job it does in other runtimes.

haven't heard a convincing argument for why TS doesn't need it

Just a reminder that this is not how it works. All features start at -100. From that post

In some of those questions, the questions asks why we either “took out” or “left out” a specific feature. That wording implies that we started with an existing language (C++ and Java are the popular choices here), and then started removing features until we got to a point where we liked. And, though it may be hard for some to believe, that's not how the language got designed.

We have a finite complexity budget. Everything we do makes every next thing we do 0.1% slower. When you request a feature, you're requesting that every other feature become a little bit harder, a little bit slower, a little bit less possible. Nothing gets in the door here because Java has it or because C# has it or because it'd only be a few lines of code or you can add a commandline switch. Features need to pay for themselves and for their entire burden on the future.


What would change our mind here? People showing up with examples of code that didn't work the way it should have because the final keyword was missing.

The scenario here that the keyword attempts to address is one where someone mistakenly inherits from a class. How do you mistakenly inherit from a class? It's not an easy mistake to make. JavaScript classes are inherently fragile enough that any subclass must understand its base class's behavioral requirements, which does mean writing some form of documentation, and the first line of that documentation can simply be "Do not subclass this class". Or there can be a runtime check. Or the class constructor can be hidden behind a factory method. Or any other number of options.

In other words: the only correct process for inheriting from a class in JavaScript always starts with reading that class's documentation. There are too many constraints the base class might have to simply derive and start coding. If, at the very first step, you should already know not to try, what value is the static enforcement providing at step three?

Why must TypeScript have this keyword when the situation is already one in which you should have had encountered at least two separate roadblocks telling you not to be there to begin with?

I've been programming for approximately forever years now and I have not once tried to subclass something only to find out it was sealed and I shouldn't have tried. It's not because I'm a super genius! It's just an extremely uncommon mistake to make, and in JavaScript these situations are already ones where you need to be asking questions of the base class in the first place. So what problem is being solved?

If you're not interested in reinforcing the main feature of Typescript, please say it loud so that tech news can relay that on Twitter

We're very explicit about how we design the language; non-goal number one speaks exactly to this suggestion.


My personal reaction after reading the many comments here is that there's a strong biasing effect due to constructs that exist in other languages. If you just approach this from a blank slate perspective, there are dozens of behavioral you could imagine, of which TypeScript has only a small subset.

You could easily imagine some keyword that was applied to a method and enforced that derived methods called it via super. If C# and Java had this keyword, people would absolutely apply that keyword in places where it made sense. In fact, it'd arguably be much more commonly enforced than final, because it's impossible to apply a runtime check for, and is a much more subtle aspect of the base-derived contract than "derived classes may not exist". It'd be useful in a variety of ways that final wouldn't be. I would much rather have that keyword than this one (though I think neither meets the complexity vs value bar).

So, then, what would be an appropriate reason to consider implementing this?

When we look at feedback, strong considerations look like this:

  • I can't adequately express the behavior of this JavaScript library
  • My code compiled, but really shouldn't have because it had this (subtle) error
  • The intent of this code is not adequately communicated by the type system

final hits these, but so would a modifier that says "This function can't be called twice in a row" or "This class's construction doesn't really finish until the next async tick". Not everything imaginable should exist.

We've never seen feedback like "I spent hours debugging because I was trying to inherit from a class that wasn't actually subclassable" - someone saying that would rightly trigger a 'wat' because it's not really imaginable. Even if the modifier existed, it wouldn't really help the situation, because libraries don't document if classes are intended to be final - e.g. is fs.FSwatcher final ? It seems like even the node authors don't know. So final is sufficient if the authors know that it's final, but that's going to be documented regardless, and a lack of final doesn't really tell you anything because it's often simply not known either way.

RyanCavanaugh avatar Jan 28 '19 19:01 RyanCavanaugh

I read the entire block and understand the statement of the team on the choice of features, I'll just go back on certain points from my comments

I'm not "one guy". When I make decisions here, it is the reflection of the entire TypeScript team's decision-making process.

Sorry I was refering to mhegazy and the pretty massive feedback he got from the community that uses Typescript.

If you really feel like classes are completely useless without final, that is something to take up with the TC39 committee or bring to es-discuss. If no one is willing or able to convince TC39 that final is a must-have feature, then we can consider adding it to TypeScript.

I do not think final is the first step as there's already a proposal for the private keyword https://github.com/tc39/proposal-private-methods

I'm skeptical about the You should a comment to say *dont do this*, it's like saying on a form Hey don't write down specific characters, you coded for nearly forever years so you should know the n°1 rule of a dev: Never trust the user (and the dev that will use your code)

I'm not saying we must absolutely stop everything and put a billion dollars to implement the final keyword, because the usecases are too low to be that efficient, also consider that I gave few exemples where the limit are both from TS and JS and that if people choose TS, it's to prevent the errors in compile-time, not in run-time. If we want things to blow up at runtime, we can use JS and stop caring about TS, but that's not the point, because there's an ultimate usecase that shows how I use the final keyword : I want to lock a method, I don't want anyone to override it.

And as Javascript is limited by that, the community thought Typescript could go beyond that limit, that's why this issue has been on for 3 years, that's why people are still wondering why this feature is not here, and that's why we want the compiler to do the manual checking of a class and/or method.

You didn't wait JS to have private/public methods to implement them, though there are actually proposals to include them with the # keyword (less verbose than public/private), I know you wanted to create a perfect language because perfection is not when you can't add anything anymore, it's when you can't remove anything anymore.

If you can find a solution to prevent a method to be overwritten in the compile process (and not in runtime-process as the point wouldn't be valid), be my guest.

I tried to show the weakness of the situation (on methods/properties and not class), because any TS dev can rewrite any libraries they want, breaking anything they want, maybe that's the beauty of the thing, I guess.

Thanks for the reply by the way, no hate or bad behavior intended against the dev team or you.

Mcfloy avatar Jan 28 '19 19:01 Mcfloy

All valid points! But, please let’s split the discussion between

a) Support final classes b) Support final methods

While all your arguments target a) - none targets b.

Having final methods is crucial as was pointed out many times in the discussion. The only answer I heard so far was „don’t do OOP“ - but that’s nothing I (and many other) would go with.

Am 28.01.2019 um 20:32 schrieb Ryan Cavanaugh [email protected]:

GitHub unhelpfully hides a lot of comments here, so I'm reposting various responses (plus some additions) we've given in the past. Adding some thoughts in below as well.

Some points were considered when we reviewed this last time

CLASSES ARE A JAVASCRIPT FEATURE, NOT A TYPESCRIPT FEATURE. If you really feel like classes are completely useless without final, that is something to take up with the TC39 committee or bring to es-discuss. If no one is willing or able to convince TC39 that final is a must-have feature, then we can consider adding it to TypeScript. If it's legal to invoke new on something, that has a one-to-one runtime correspondence with inheriting from it. The notion of something that can be new'd but not super'd just doesn't exist in JavaScript We are trying our best to avoid turning TypeScript into an OOP keyword soup. There are many better composition mechanics than inheritance in JavaScript and we don't need to have every single keyword that C# and Java have. You can trivially write a runtime check to detect inheritance from a "should-be-final" class, which you really should do anyway if you're "worried" about someone accidently inheriting from your class since not all your consumers might be using TypeScript. You can write a lint rule to enforce a stylistic convention that certain classes aren't inherited from The scenario that someone would "accidently" inherit from your should-be-sealed class is sort of an odd one. I'd also argue that someone's individual assessment of whether or not it's "possible" to inherit from a given class is probably rather suspect. There are basically three reasons to seal a class: Security, performance, and intent. Two of those don't make sense in TypeScript, so we have to consider the complexity vs gain of something that's only doing 1/3rd the job it does in other runtimes. haven't heard a convincing argument for why TS doesn't need it

Just a reminder that this is not how it works. All features start at -100 https://blogs.msdn.microsoft.com/ericgu/2004/01/12/minus-100-points/. From that post

In some of those questions, the questions asks why we either “took out” or “left out” a specific feature. That wording implies that we started with an existing language (C++ and Java are the popular choices here), and then started removing features until we got to a point where we liked. And, though it may be hard for some to believe, that's not how the language got designed.

We have a finite complexity budget. Everything we do makes every next thing we do 0.1% slower. When you request a feature, you're requesting that every other feature become a little bit harder, a little bit slower, a little bit less possible. Nothing gets in the door here because Java has it or because C# has it or because it'd only be a few lines of code or you can add a commandline switch. Features need to pay for themselves and for their entire burden on the future.

What would change our mind here? People showing up with examples of code that didn't work the way it should have because the final keyword was missing.

The scenario here that the keyword attempts to address is one where someone mistakenly inherits from a class. How do you mistakenly inherit from a class? It's not an easy mistake to make. JavaScript classes are inherently fragile enough that any subclass must understand its base class's behavioral requirements, which does mean writing some form of documentation, and the first line of that documentation can simply be "Do not subclass this class". Or there can be a runtime check. Or the class constructor can be hidden behind a factory method. Or any other number of options.

In other words: the only correct process for inheriting from a class in JavaScript always starts with reading that class's documentation. There are too many constraints the base class might have to simply derive and start coding. If, at the very first step, you should already know not to try, what value is the static enforcement providing at step three?

Why must TypeScript have this keyword when the situation is already one in which you should have had encountered at least two separate roadblocks telling you not to be there to begin with?

I've been programming for approximately forever years now and I have not once tried to subclass something only to find out it was sealed and I shouldn't have tried. It's not because I'm a super genius! It's just an extremely uncommon mistake to make, and in JavaScript these situations are already ones where you need to be asking questions of the base class in the first place. So what problem is being solved?

If you're not interested in reinforcing the main feature of Typescript, please say it loud so that tech news can relay that on Twitter

We're very explicit about how we design the language https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals; non-goal number one speaks exactly to this suggestion.

My personal reaction after reading the many comments here is that there's a strong biasing effect due to constructs that exist in other languages. If you just approach this from a blank slate perspective, there are dozens of behavioral you could imagine, of which TypeScript has only a small subset.

You could easily imagine some keyword that was applied to a method and enforced that derived methods called it via super https://github.com/Microsoft/TypeScript/issues/21388. If C# and Java had this keyword, people would absolutely apply that keyword in places where it made sense. In fact, it'd arguably be much more commonly enforced than final, because it's impossible to apply a runtime check for, and is a much more subtle aspect of the base-derived contract than "derived classes may not exist". It'd be useful in a variety of ways that final wouldn't be. I would much rather have that keyword than this one (though I think neither meets the complexity vs value bar).

So, then, what would be an appropriate reason to consider implementing this?

When we look at feedback, strong considerations look like this:

I can't adequately express the behavior of this JavaScript library My code compiled, but really shouldn't have because it had this (subtle) error The intent of this code is not adequately communicated by the type system final hits these, but so would a modifier that says "This function can't be called twice in a row" or "This class's construction doesn't really finish until the next async tick". Not everything imaginable should exist.

We've never seen feedback like "I spent hours debugging because I was trying to inherit from a class that wasn't actually subclassable" - someone saying that would rightly trigger a 'wat' because it's not really imaginable. Even if the modifier existed, it wouldn't really help the situation, because libraries don't document if classes are intended to be final - e.g. is fs.FSwatcher https://nodejs.org/api/fs.html#fs_class_fs_fswatcher final ? It seems like even the node authors don't know. So final is sufficient if the authors know that it's final, but that's going to be documented regardless, and a lack of final doesn't really tell you anything because it's often simply not known either way.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/Microsoft/TypeScript/issues/8306#issuecomment-458268725, or mute the thread https://github.com/notifications/unsubscribe-auth/AA3NA4o9wu54CcJyK1C8WHVjXIQwfmsUks5vH1A8gaJpZM4IP8M3.

thorek avatar Jan 28 '19 19:01 thorek

Yeah, the discussion is so diffuse now. I would like to see these issues in a tracker where you can vote, like the one used for IntelliJ / webstorm issues. Get some actual numbers of how many people would like to see final for classes and/or methods.

bbottema avatar Jan 28 '19 21:01 bbottema

final would be very helpful

leandrit1 avatar Mar 10 '19 20:03 leandrit1

An abstract keyword is used to remind programmers that they should override the field. A keyword to remind them not to override it will be helpful in similar way.

david0u0 avatar Mar 26 '19 17:03 david0u0

Final methods can be crucial to making code more structured and/or secure.

For example, lets say you have an application that supports 3rd party plugins. You can force all plugins to extend an abstract class that implements an interface for any methods they MUST create and contains a few final methods that control the order of operations and allow you to implement hooks between operations. Because of this, your application doesn't need to be aware of the specifics of any individual plugin, and still be aware of some of its internal state.

Without final methods, they could interfere with your functions controlling the order of operations; potentially causing a bug, exploit, or other unexpected behavior within your application. While most situations will have some type of workaround, those workarounds can be complicated, repetitive, and sometimes unreliable; whereas final methods make it one simple solution when the method is defined.

Also, While this example is specific to plugins, it is applicable to other situations as well. (new dev on team, ensuring certain logic is not run out of scope, standardizing how code is run, making sure security based methods are not changed, etc. all could benefit from this)

ProjectCleverWeb avatar Apr 12 '19 09:04 ProjectCleverWeb