I am trying to understand decorators which are not java's annotations but more like pre-processors in this article and I also found this SO question on setting info on a function. Let's say I have an interface like so
export default interface UserService {
#Path("/users/create")
#POST
createUser(user: CreateUserRequest): Promise<CreateUserResponse>;
#Path("/users/delete")
#POST
deleteUser(user: DeleteUserRequest): Promise<DeleteUserResponse>;
}
sidenote: It would be great to use this generated client in react UI as well as use in nodejs
I want my #Path and #POST, #GET to save info I can read and I think
class Path(path:string):
def __init__(self, path):
self.path = path
def __call__(self, func):
func.pathAnnotation = self
return func
I read I cannot loop over methods in an interface yet I would like to generate the http client that implements this interface so any API developers create, it automatically creates the implementation. (In java, we use the Proxy.java to generate an implementation). On server side, the controller implements the same exact API and I like to generate the 'scaffolding' meaning the http request to which endpoint to call if possible (not sure I can do that in nodejs just yet).
EDIT: An idea: Perhaps, I create an abstract class or class and every method throws an exception "Use XXXFactory to generate the implementation of this class". How do I loop over method in that class? and can I create classes that extend all these 'apis' at runtime such that I can inject him for everyone to use(like Proxy.java in java world)?
EDIT: perhaps I could do this in javascript with a prototype class somehow... generate all the methods to call a method with signature
Promise<Object> invoke(String method, object[] paramsToMethod);
Then, I can look up the method and #Path and #GET/#POST properties on that method. Can a prototype class extend a class in javascript such that any api defined (perhaps defined in typescript) is implemented by this one class? Then I have every api implemented by the same code for every microservice like we do in java? (This then means the platform team can swap protocols and developers do not care about protocols anymore like http, http2, binary, etc)
As per request, I have took some time to tinker around with reflection. The reflection is mostly needed to make the client automatically conform to what the service expects (type of parameters/return type), and I think it might be possible with reflect-metadata.
Ok so the idea is to have decorators store metadata about the method in a map, where a key is the class and the value is a collection of the methods with metadata.
Then where you get the client, it aggregates all the metadata for each method into one function that can be used.
It's a vague start but I think it can work. I actually might also turn this into a small snippet or library too if I have the time.
But actually, this should be a statically generated client, not a dynamic one. Because then it is far easier to validate and do the code generation.
Playground
I have a master application that accepts plugin modules, except for some functionality (authentication) where for some reason it seems hell-bent to prevent plugins from adding authentication methods. Despite that, I still need to do exactly that - add a new authentication method, but via a plugin.
The master application has a typescript module that exports an Authenticator class,
export class Authenticator {
constructor(arg) { dostuff(arg); }
}
I need to somehow intercept the constructor argument and store it in my plugin. The Authenticator class is instantiated in private code, but fortunately, after my plugin is initialized - so I get a chance to run some code; is there any way to dynamically modify the Authenticator class object (i.e. the class itself) so that I may capture the argument, when it is actually instantiated? Note that I can't use a decorator (I'd need to modify the main app), and I can't instantiate a proxy instead of the Authenticator (again, I would need to modify the main app in order to do so).
I've tried modifying Authenticator.constructor or Authenticator.prototype.constructor but neither works apparently. Is there any other way?
Two DIFFERENT Blazor components define the following instance method:
[JSInvokable]
public void MyInstanceMethod()
{
...
}
At load time they call a js function, passing themselves to js:
await JS.InvokeAsync<object>("jsFunction", new DotNetObjectRef(this));
In js, the passed .NET object reference is saved in a variable named _callback.
Later, an event occurring in javascript calls back the instance method
_callback.invokeMethodAsync("MyInstanceMethod");
The browser console fails with the following error:
blazor.webassembly.js:1 Uncaught (in promise) Error:
System.InvalidOperationException:
The assembly 'WebApplication7.Client' contains more than one [JSInvokable] method
with identifier 'MyInstanceMethod'.
All [JSInvokable] methods within the same assembly must have different identifiers.
BTW, everything goes well if only one component has the method.
Isn't this a violation of one of the fundamental scope features in any OO language?
Can anybody tell me why methods, including instance methods, are required to have different identifiers to be JSInvokable?
If this is a limit of Blazor, is there a plan to fix it?
Looks like there is a bug in Blazor. Steve Sanderson:
Sounds like a bug. Thanks for reporting it.
It makes sense to require static methods to have assembly-wide unique identifiers. However it doesn't make sense that instance methods need assembly-wide unique identifiers. We should only require the identifier to be unique within the type of the instance you're passing.
As a workaround, you could do something like:
[JSInvokable("SomeUniqueIdentifier")]
public void MyInstanceMethod()
{
...
}
I know it's annoying to need a workaround like this. We'll fix the underlying bug (most likely after 3.0 ships).
I read it on mdn.
The original is:
The static keyword defines a static method for a class. Static methods are called without instantiating their class and are also not callable when the class is instantiated.
I thought static in js is similar to static in java but the sentence in question confuses me.
It is similar. However, Java allows calling static methods on the instance:
p1.distance(p1, p2);
which does the same thing as
Point.distance(p1, p2);
The first one is not allowed in JavaScript.
Why is there a distinction between privileged and public methods?
Why should I even bother with public methods, aren't privileged
methods more natural? They feel more intuitive as they allow access
to private methods and variables like in java.
Is there a specific reason behind this or was this an error in the
spec(got a little ahead of myself there!) or am I missing something?
In what situation would you use a public method over a privileged method?
here is the code to demonstrate:
var Foo = function(){
var privateVar = "i am private";
function privateFunc(){
console.log(privateVar);
}
this.privilegedFunc = function(){
privateFunc(); // can access
}
};
Foo.prototype.publicFunc = function(){
privateFunc(); // cannot access
};
var foo = new Foo();
foo.privilegedFunc(); // prints "i am private"
foo.publicFunc(); // Uncaught ReferenceError: privateFunc is not defined
it's just like any OOP language (without the visibility keywords though), if you need a method to be called outside the instance, public, else, private.
Functions that are not bound to this, cannot be accessed outside the scope because they are defined and declared in the scope of the constructor function.
And as per your latest comment, there are many reasons and scenarios where you will have to expose an objects function in order to be used by other objects e.g.
As per your comment in this answer, lets see some advantages of the prototype approach.
By using prototype, you are able to change a method and the change will reflect to all instances that share the same prototype, without the prototype, each instance will have it's own version of the given method, therefore you will have to change them one by one.
Another advantage, is performance, functions/methods declared in the prototype are only created once, whereas without the prototype, each time you use the new keyword to instantiate from a constructor function, all functions inside the constructor functions scope will have to be created.
It's important to note that there's no distinction in the spec between "privileged" and "public" methods (in fact I don't think the spec uses these terms at all - Douglas Crockford does), they are governed by the exact same rules, the most fundamental of which in play being function scope.
Note: I'll follow your terminology in my answer, but I actually recommend against it: more often you'll find people calling your privileged methods public, and your public methods prototype methods.
In your example, this.privilegedFunc has access to the private variable privateFunc because they are defined in the same scope - that is, the scope of the Foo constructor function. privilegedFunc will be able to use its reference to privateFunc even when called from "outside", via the so-called closure mechanism of the language.
To answer your questions directly:
Why is there a distinction between privileged and public methods?
There isn't a fundamental distinction. You defined two functions in different scopes, and as such, they can reference different variables.
Why should I even bother with public methods, aren't privileged methods more natural?
Natural is quite a subjective term. However, if you don't wish to expose fields directly, you need to use a privileged function to manipulate them from the outside.
They feel more intuitive as they allow access to private methods and variables like in java.
That intuition is based only on familiarity :) No wonder that when you try to use Javascript as Java, the parts which work differently in the two languages will seem the least intuitive. This doesn't mean that you should try to imitate the style you would use in either in the other, some solutions are better suited for Javascript, some better for Java.
Is there a specific reason behind this or was this an error in the spec or am I missing something?
(Such a fundamental error in the spec?! God no.) I'm not sure what you mean by "this", but the difference in visibility is explained by function scopes, see above.
In what situation would you use a public method over a privileged method?
For example, if you don't need to expose private fields via closures. An other noteworthy difference is that functions on the prototype will be shared (i.e. effectively the same function instance) amongst instances, while private and privileged methods will be unique to the instance, which can have an effect on memory footprint.
What you call "privileged" methods aren't part of the language syntax. Rather, it's a design pattern. It is possible due to the fact that javascript implement closures (the ability of functions to access the scope of an outer function even after that outer function has returned).
There is a theory that all languages that implement closures (or even just first-class functions) can implement an object system. Several functional languages took this approach when adding OO to the language: that OO features are not part of the language syntax but a library that you can use (or even write yourself). One of the prime examples of this is CLOS (Common Lisp Object System) in Lisp. It's a library that adds OO features to the language without needing to modify the language syntax.
As you have discovered, using a closure to access local variables does a good enough job to emulate the "feel" of private variables and public methods. This is a feature of closures - that you can create your own OO system without needing OO features.
The OO system in javascript was added because OO was a big deal then. Admittedly, if Brendan Eich didn't add OO to javascript we could have evolved a (or several) OO systems from scratch using pure javascript. Indeed, in the early 2000s people weren't comfortable with the prototypal object system in javascript and developed their own OO system to emulate what they were used to.
In javascript, the OO system has no concept of private methods or variables. This was deliberate. Several other languages share this philosophy that private members are a "mistake". The idea that privacy is bad practice was borne out of years of experience using libraries that made a feature you needed to access private. For languages that encourages open source or distribution of code that's not too big of an issue. You can always modify the library code to export what you want. But for languages that encourages distribution of libraries as compiled binaries that's a big issue. At the time javascript was created, most OO languages had features allowing you to distribute your libraries as compiled binaries. So there was a small backlash against the concept of privacy.
So.. when would you use a closure to emulate private variables? Use it when you really need something like a private variable.
Why is there a distinction between privileged and public methods?
I'm assuming you read Douglas Crockford website (this page). It's a distinction I haven't really seen used by other authors. I don't make that distinction, but I do know that the function has access to the constructor closure.
Why should I even bother with public methods, aren't privileged methods more natural? They feel more intuitive as they allow access to private methods and variables like in java.
They have a different meaning than public methods.
A) They are defined by the constructor and as such, they have access to the constructor scope. That's their privilege.
B) They aren't shared by its prototype.
A means that the function will be instantiated every time the constructor is being called. When you use the prototype, it's just linked.
B means that they are essentially different functions.
obj1.privileged !== obj2.privileged
Is there a specific reason behind this or was this an error in the spec or am I missing something?
No error from where I see it. It's just a language feature.
In what situation would you use a public method over a privileged method?
When you don't need access to any closures inside the constructor and want to take leverage of the prototype chain.
Not sure about the semantics and naming convention, but as far as patterns, here's how I'd break this down for the most cases:
privateFunc:
I'd use this type of function whenever I want to encapsulate some functionality inside a function (either when reusing this function several times, or simply because it has a logical reason to do so) that I don't want to expose as an API, usually because it doesn't make sense as an API.
publicFunc:
I'd use this type of function whenever I want to expose an API, and the implementation doesn't require any "closed" (as in closure) variables. Basically anything that uses the state of an instance of the type but needs no other resources. Also for "static" methods that are used directly from the type (same as Object.keys() for example), but this won't be declared on the prototype but rather directly on the type.
priviledgedFunc:
Same use case as publicFunc except the use of helper, "closed" variables is either required or greatly simplify implementation. There's a downside to this technique in that these methods are properties of each instance, and incur runtime penalty to construct and assign.
Why is there a distinction between privileged and public methods?
It's a consequence, not a driver, of the language's design. You will actually do fine without bothering yourself with this terminology distinction I think.
Why should I even bother with public methods, aren't privileged
methods more natural? They feel more intuitive as they allow access to
private methods and variables like in java.
Is there a specific reason behind this or was this an error in the spec > or am I missing something?
In what situation would you use a public method over a privileged method?
There are a couple of situations where you would want to bother yourself with public methods that come to mind:
Privileged methods are defined everytime an object is created while public methods are defined once at parse time. So if you are writing something that creates a bucket load of object, e.g. particle system, you may want to use public method.
You can use public methods are pure function without instantiating an object.
Your are thinking about this the wrong way. You should be thinking about scope here and not access level (public/private/protected) Javascript is not a traditional object oriented programming language.
In your example, the "privateMethod" is simply scoped to the "Foo" function, and thus cannot be accessed outside the function. Your "privilegedFunction" is attached to "this" which in javascript is the context of the "Foo" function. You can access it from an "instance" of Foo as your example shows because of scoping, and it has nothing to do with access level.