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

There is a task - write code that

  • operates immutable objects
  • is inheritance free
  • reflection methods free

And final keyword is necessary here, IMHO.

ghost avatar Nov 28 '17 22:11 ghost

I see final as a great way to remind yourself and users of your code which protected methods they should be overriding, and which they shouldn't. As a sidenote, I'm also a proponent of explicitly stating that you're overriding, partially so that the reader knows, but also so that the transpiler complains if you typo the method's name.

zigszigsdk avatar Dec 03 '17 16:12 zigszigsdk

@zigszigsdk Since methods are never overridden, how would this work?

aluanhaddad avatar Dec 03 '17 22:12 aluanhaddad

For final: The same way as it works now, except the transpiler would complain if one hides a super's method -which has been declared final- from the this context.

For override: The same way it works now, except the transpiler would complain if one declares a method override, and its super doesn't have a method by that name, or it does have one but it's declared to be final. It could possibly also be warning you if you hide a super's method from the this context and don't state override.

zigszigsdk avatar Dec 04 '17 12:12 zigszigsdk

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.

@mhegazy Not quite! Another important function is to be explicit about which parts of the class expect to be overriden.

For example, see item 17 in "Effective Java": "Design and document for inheritance or else prohibit it":

It is not uncommon to receive subclassing-related bug reports after modifying the internals of a nonfinal concrete class that was not designed and documented for inheritance. The best solution to this problem is to prohibit subclassing in classes that are not designed and documented to be safely subclassed. There are two ways to prohibit subclassing. The easier of the two is to declare the class final.

Same goes for final methods, in my opinion. It's very rare that a class is designed to support overriding any of its public methods. This would require very intricate design and a huge amount of testing, because you'd have to think of every possible combination of states that might result from combination of non-overrided and overriding behaviour. So instead a programmer might declare all public methods final except one or two, which would decrease the number of such combinations dramatically. And more often that not, one or two overridable methods is precisely what's needed.

sbichenko avatar Jan 03 '18 10:01 sbichenko

I think that final classes and methods are very important. I hope you will implement it.

jazzfog avatar Jan 06 '18 05:01 jazzfog

Another compelling user case @mhegazy . Today I learned the Template Method Pattern, and found that final is required to prohibit subclasses changing the template method as the Template Method Pattern in wikipedia says. But I cannot do this in my lovely TypeScript. What a pity!

Template pattern lets subclasses redefine certain steps of an algorithm without changing the algorithm's stucture

legend80s avatar Jan 06 '18 14:01 legend80s

For me it's as simple as trying to enforce composition in cases over inheritance. Without final you can't do this.

lucasyvas avatar Jan 14 '18 18:01 lucasyvas

As much as I'd also like to see final come to typescript, I think the underlying message that Microsoft is trying to send us is that if we want final, we should use a language that supports it.

hk0i avatar Jan 14 '18 19:01 hk0i

I would like to see this issue re-opend and implemented.

When building a library that you are going to use internally or share publicly (such as on npm), you don't want those who use it to have to browse the code and search through comments or docs to see if the class can/can't be overwritten. If they overwrite it throw an error.

In my code, I have a class that gets extended, and when some sort of event takes place it triggers a method. If the sub-class defines the method it will that one otherwise it will fall back to the default one. However there are also other methods in the class that are not "fallback" methods, they are more of helper methods such as adding an item to the DOM in which case I don't want these methods to get overwritten.

TheColorRed avatar Jan 18 '18 16:01 TheColorRed

My 5 cents on the topic are that this should be re-opened and implemented.

I would use it to enforce clients of libraries to make their own concrete classes and not extends from some other existing already. Like @lucasyvas said, favor composition. Or just enforce new concrete class implementation to provide to the Dependency Injection in angular for example.

davidmpaz avatar Jan 22 '18 12:01 davidmpaz

I also vote for re-opening, with support for both classes and methods

Xample avatar Jan 24 '18 14:01 Xample

I don't say that we shouldn't I am just unsure of how the pattern of the final keyword would work in the context of typescript?

wouldn't the final keyword stop users/ programmer to override/ inherit from the said class/method?

My way of seing Final is that it's "Freeze" the data which mean it's can't be changed anymore. I mean this can be nice to use it's although can be truly an hassle for peoples who want to "bug" fix or change some behavior.

niokasgami avatar Mar 17 '18 06:03 niokasgami

@niokasgami Freeze is related to [data] (https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Object/freeze) and already available as part of ES6. Final applies to classes and methods (variable can be readonly and therefore act as "final" as we cannot override a super variable).

The "Final" keyword is used in JAVA where sealed is in C#.

As typescript is strongly inspired by C#, there should be a higher probability that "sealed" will be the chosen one. Now, we could possibly have confusion with the ES6 seal which basically seals the object at runtime?

Xample avatar Mar 17 '18 08:03 Xample

@Xample I think you can also use final on local variables in Java. I remember having to do it when I was writing an android app. I think it required me to do it with an event but I am not 100% certain.

function(){
    let final myVariable = 'Awesome!'
    document.addEventListener('scroll', e => {
        console.log(myVariable)
        myVariable = 'Not Awesome' // Throws an error
    })
}

TheColorRed avatar Mar 17 '18 15:03 TheColorRed

@TheColorRed Well, final local variable in Java means constant, isn't it?

eternalphane avatar Mar 17 '18 16:03 eternalphane

@EternalPhane I guess so, I have always used const in a global like scope... Never thought of using it within a function or method... I guess me previous comment is void then...

TheColorRed avatar Mar 17 '18 16:03 TheColorRed

@Xample Yeah I see your point for Sealed from the C# it's not working as the same Honestly in my opinion BOTH keyword seal and final couldn't really enter the category since both can be confusing (sealed for seal etc) and Final we are unsure how to apply it for since in Java it is used as an constant :/

niokasgami avatar Mar 18 '18 00:03 niokasgami

In java you can final any variable, method or class. For variables it means the references cannot be reassigned (for non-reference types this means you cannot change their values either). For classes it means no extensions (extends... keyword). For methods it means no overriding in subclasses.

Main reasons to final in java:

  • Reduce immutability of variables: for thread safety
  • Finalize classes so they cannot be inherited: forces composition over inheritance because inheritance is inherently complicated when your subclasses start inadvertently calling super methods
  • Prevents simple programming errors: if you have no intent on changing a value, good news it's no longer possible
  • Used for what most people think of when they imagine constants: reusable values that you will see everywhere, as in public static final String KEY = "someStringKeyPathHere", useful for reducing mistakes but has an added compile time benefit of not recreating multiple string objects for the same value

I may have left out a couple of use cases but I was trying to keep it very general and give some examples.

@TheColorRed Android requires it when you declare a variable outside of a callback (anonymous class) and then reference it inside. I think this aligns with thread safety issues again. I think they are trying to stop you from reassigning the variable from another thread.

Despite its usefulness I don't think we will see this feature coming any time soon. It might be a good time to look at other solutions or, as in my case, drop typescript all together and deal with the sloppiness in JS. Javascript has a lot of "benefits" by not having any of this type hinting or anything and ultimately your code will be converted to JS anyway. If you want browser compatibility you can write ES6 and use Babel to convert it.

I think realistically even though you can give a slap on the wrist for some of these benefits, you don't get any of the real benefits of the java-esque final once it's been converted to js.

hk0i avatar Mar 18 '18 05:03 hk0i

@hk0i I think I could understand your point but overall I agree and kinda disagree in the same time about your opinion.

Most of the code in typescript are I would say for debugging/tracking purpose for helping the programmer to well I guess do "clean" code (please don't quote me on that I know they have some typescript spaghetti code out here hahah)

most of typescript feature doesn't get transpilled most of the time when converted to JS because they just don't exists in JS.

Although when you runtime/ write your code it's help to see error in your code and to track it more easily than with JS (and HECK JS can be hard to track bugs lol)

So I think the use of the final keyword could be seing as an blocker for API user to know : Oh okay this class shouldn't be extended since it's extension could provoke weird behavior etc...

Typescript as good language it is I find myself sad to find that it lack some important feature such "true" static class keyword who stop peoples from calling the class constructor but still being able to access it.

niokasgami avatar Mar 18 '18 06:03 niokasgami