I've recently written a huge library in ECMAScript2015 which I would like to write a type definition for, so that it can be used in TypeScript projects.
Let's call the lib 'myShop' for now, with the basic structure being:
myShop.init(params): // function
myShop.cart.goto(); // function in namespace 'cart'
myShop.info; // variable that contains trivial information
My question is what the best practices would be, for typing the library. For just the sake of getting autocomplete in IntelliJ, there are many ways that seem to work.
My approach so far looks like this:
declare module myShop {
function init(param:List<string>): Promise;
var cart: ICart;
var info: Object;
}
interface ICart {
goto(): void;
}
Any tips for improvement? Is an interface for 'cart' correct? Should it rather be a module?
Thank you in advance!
Related
In Javascript we can define an object like this 👇
let obj={
property1:67,
func1: function (){
//Some code
}
}
Now if we want add a new property to obj I can just add a new property like this
obj.property2=733; //some value or function
Now I want to do the same thing in Java also.
I have a class Test 👇
public class Test{
int property1=67;
public void func1(){
//Some code
}
}
Now is it possible to do like the same thing like statement #2 in Java also?
Edit:
From the answers I got to know that we can use a Map for properties.
Now I want to know for methods.
Thanks
So I did a research and as I can see this is not simple.
In java you can not do that, actually, you can if you provide your own custom class loading, which is really a bad idea because then even if you change the class you want you must reload all classes that interact with this class.
Check this article to understand more about class loaders.
Of course, there are some other ways as:
ASM an all-purpose Java bytecode manipulation and analysis framework.
Javassist a library for editing bytecodes in Java
AspectJ aspect-oriented extension to the Java, mostly used to clean modularization of crosscutting concerns
I am gradually improving a codebase that originally had some AngularJs in various versions and some code that was not in a framework at all using various versions of a software API. (For some reason this API is available - to pages loaded through the application - on AngularJS's $window.external...go figure.)
In my pre-ES6, AngularJs 1.8 phase, I have three services that interact with the software's API (call them someAPIget, someAPIset, and someAPIforms). Something like this:
// someAPIget.service.js
;(function () {
var APIget = function ($window, helperfunctions) {
function someFunc (param) {
// Do something with $window.external.someExternalFunc
return doSomethingWith(param)
}
return {
someFunc: someFunc
}
}
angular.module('someAPIModule').factory('someAPIget', ['$window', 'helperfunctions', someAPIget])
})()
I then had a service and module a level up from this, with someAPIModule as a dependency, that aggregated these functions and passed them through under one name, like this:
// apiinterface.service.js
;(function () {
// Change these lines to switch which API service all functions will use.
var APIget = 'someAPIget'
var APIset = 'someAPIset'
var APIforms = 'someAPIforms'
var APIInterface = function (APIget, APIset, APIforms) {
return {
someFunc: APIget.someFunc,
someSettingFunc: APIset.someSettingFunc,
someFormLoadingFunc: APIforms.someFormLoadingFunc
}
}
angular.module('APIInterface').factory('APIInterface', [APIget, APIset, APIforms, APIInterface])
})()
I would then call these functions in various other controllers and services by using APIInterface.someFunc(etc). It worked fine, and if we switch to a different software provider, we can use our same pages without rewriting everything, just the interface logic.
However, I'm trying to upgrade to Typescript and ES6 so I can use import and export and build some logic accessible via command line, plus prepare for upgrading to Angular 11 or whatever the latest version is when I'm ready to do it. So I rebuilt someAPIget to a class:
// someAPIget.service.ts
export class someAPIget {
private readonly $window
private readonly helperfunctions
static $inject = ['$window', 'helperfunctions']
constructor ($window, helperfunctions) {
this.$window = $window
this.helperfunctions = helperfunctions
}
someFunc (param) {
// Do something with this.$window.external.someExternalFunc
return doSomethingWith(param)
}
}
}
angular
.module('someAPImodule')
.service('someAPIget', ['$window', 'helperfunctions', someAPIget])
Initially it seemed like it worked (my tests still pass, or at least after a bit of cleanup in the Typescript compilation department they do), but then when I load it into the live app... this.$window is not defined. If, however, I use a direct dependency and call someAPIget.someFunc(param) instead of through APIInterface.someFunc(param) it works fine (but I really don't want to rewrite thousands of lines of code using APIInterface for the calls, plus it will moot the whole point of wrapping it in an interface to begin with). I've tried making APIInterface into a class and assigning getters for every function that return the imported function, but $window still isn't defined. Using console.log statements I can see that this.$window is defined inside someFunc itself, and it's defined inside the getter in APIInterface, but from what I can tell when I try to call it using APIInterface it's calling it without first running the constructor on someAPIget, even if I make sure to use $onInit() for the relevant calls.
I feel like I am missing something simple here. Is there some way to properly aggregate and rename these functions to use throughout my program? How do alias them correctly to a post-constructed version?
Edit to add: I have tried with someAPIget as both a factory and a service, and APIInterface as both a factory and a service, and by calling APIInterface in the .run() of the overall app.module.ts file, none of which works. (The last one just changes the location of the undefined error.)
Edit again: I have also tried using static for such a case, which is somewhat obviously wrong, but then at least I get the helpful error highlight in VSCode of Property 'someProp' is used before its initialization.ts(2729).
How exactly are you supposed to use a property that is assigned in the constructor? How can I force AngularJS to execute the constructor before attempting to access the class's members?
I am not at all convinced that I found an optimal or "correct" solution, but I did find one that works, which I'll share here in case it helps anyone else.
I ended up calling each imported function in a class method of the same name on the APIInterface class, something like this:
// apiinterface.service.ts
// Change these lines to switch which API service all functions will use.
const APIget = 'someAPIget'
const APIset = 'someAPIset'
const APIforms = 'someAPIforms'
export class APIInterface {
private readonly APIget
private readonly APIset
private readonly APIforms
constructor (APIget, APIset, APIforms) {
this.APIget = APIget
this.APIset = APIset
this.APIforms = APIforms
}
someFunc(param: string): string {
return this.APIget.someFunc(param)
}
someSettingFunc(param: string): string {
return this.APIset.someSettingFunc(param)
}
someFormLoadingFunc(param: string): string {
return this.APIforms.someFormLoadingFunc(param)
}
}
angular
.module('APIInterface')
.factory('APIInterface', [APIget, APIset, APIforms, APIInterface])
It feels hacky to me, but it does work.
Later Update:
I am now using Angular12, not AngularJS, so some details may be a bit different. Lately I have been looking at using the public-api.ts file that Angular12 generates to accomplish the same thing (ie, export { someAPIget as APIget } from './filename' but have not yet experimented with this, since it would still require either consolidating my functions somehow or rewriting the code that consumes them to use one of three possible solutions. It would be nice not to have to duplicate function signatures and doc strings however. It's still a question I'm trying to answer more effectively, I will update again if I find something that really works.
I'm getting rather confused as to if something is possible or not.
I create a module that contains the following:
export function logText(){
console.log('some text');
}
export class Example {
constructor(){
logText();
}
}
The intent is for the user to call new Example to start off the module logic.
import { logText, Example } from 'example';
// Do some magic here to modify the functionality of logText
new Example();
Is it possible for the end user to modify logText?
It would make sense for there to be a way for users to do something like this, or they'd have to take the entire module into their own repo just to make small functionality tweaks.
I frequently see repos with lots of functions exported that are useless without the users having to remake almost all the functionality manually, making it rather pointless to do. One good example is this repo whre theuy even call the exported functions their 'API'. In that example these are rather pointless exports and at worse would just cause issues if someone tried to use them in conjunction with the main function. But if you could modify them and have them still run then it would make sense to me.
Given this:
import { logText, Example } from 'example';
Is it possible for the end user to modify logText?
Since you aren't being very specific about what you mean by "modify logText", I'll go through several options:
Can you reassign some other function to the variable logText?
No. You cannot do that. When you use import, it creates a variable that is const and cannot be assigned to. Even if it wasn't const, it's just a local symbol that wouldn't affect the other module's use of its logText() anyway. The import mechanism is designed this way on purpose. A loader of your module is not supposed to be able to replace internal implementation pieces of the module that weren't specifically designed to be replaced.
Can you modify the code inside of the logText function from outside of the module that contains it?
No, you cannot. The code within modules lives inside it's own function scope which gives it privacy. You cannot modify code within that module from outside the module.
Can you replace the logText() function inside the module such that the implementation of Example inside that class will use your logText() function?
No, you cannot do that from outside the module. You would have to actually modify the module's code itself or someone would have to design the Example interface to have a replaceable or modifiable logText() function that the Example object used.
For example, logText() could be made a method on Example and then you could override it with your own implementation which would cause Example's implementation to use your override.
Code in the module that you do not modify:
export class Example {
constructor(){
this.logText();
}
logText() {
console.log('some text');
}
}
Code doing the import:
import { Example } from 'example';
class MyExample extends Example {
constructor() {
super();
}
logText() {
console.log("my own text");
}
}
let o = new MyExample();
Can you create your own version of logText and use it locally?
Sure, you can do that.
function myLogText() {
do your own thing
}
And, you could even NOT import logText so that you could use the symbol name logText() locally if you wanted. But, that won't affect what Example does at all.
Are there ways to design the example module so that that logText() can be easily replaced.
Yes, there are lots of ways to do that. I showed one above that makes logText a method that can be overriden. It could also be passed as an optional argument to the Example constructor.
There could even be an exported object that allowed the caller to replace properties on that object. For example:
export const api = {
logText: function logText(){
console.log('some text');
}
};
export class Example {
constructor(){
api.logText();
}
}
Then, use it like this:
import { api, Example } from 'example';
api.logText = function() {
console.log('my Text');
};
I would generally not recommend this because it sets you up for usage conflicts between multiple users of the same module where each one tries to modify it globally in ways that conflict with each other. The subclassing model (mentioned above) lets each use of the module customize in its own way without conflicting with other usages of the module.
Is it possible for the end user to modify logText?
No, that's not possible, import bindings are immutable, and function objects are basically immutable wrt the code they contain.
It would make sense for there to be a way for users to do something like this, or they'd have to take the entire module into their own repo just to make small functionality tweaks.
Why not make the log function an optional argument in the constructor? Usually when something is variable it becomes a parameter.
export class Example {
constructor(log=logText){
log();
}
}
I have a class that has roughly this structure:
function MyClass() {
// constructur stuff
}
MyClass.prototype.myFunc = function () {
// example function
};
MyClass.myStaticFunc = function () {
// example static function
};
I spent some time now setting up the closure compiler annotations and finally got rid of all warnings. And what do you know, it reduces the size by a spectacular 100%. So then I read about exporting functions, but window['MyClass'] = MyClass will only export the constructor. To be honest, I'd rather not export every single method individually. I thought the compiler would export and not obfuscate all publicly available methods but those with a #private annotation.
What's the best way to teach the closure compiler to do that and not have to export every method individually?
Using ADVANCED_OPTIMIZATIONS you must export EVERY public method and property. If you do not want the public methods and properties renamed, then use SIMPLE_OPTIMIZATIONS.
See my Which Compilation Level is Right for Me post for more details.
I believe I found the answer: I can annotate methods with #export and run the compiler with --generate_exports. But maybe someone has an even better way.
I am having trouble wrapping my mind around primarily RequireJS. I see that it is a good/necessary technology, but implementing it, for me, has been a real stretch. I greatly appreciate your help!
I am trying to develop a fairly flexible application with Backbone and RequireJS. The problem is that I am totally used to syntax like new Person() without having to specify dependencies. Is there an efficient way to use RequireJS with quite a number of models? I think my problem is always working with returns. I considered using a factory method to create the model with the require function, but doing so necessitates that the require function is synchronous, which completely defeats the purpose of RequireJS.
It just doesn't seem right to have to require all of my models first and then include those in the instantiation function - or do I?
Do you have any suggestions or tutorials about how to structure and model an application like this?
Thank you for helping me out!
JMax
You can use what I call require js module pattern. If you know a group of classes are often used together you can do something like this.
First you define each class in a separate file and then you define a module to hold them together
Module.js
define([
'./models/FirstModel',
'./models/SecondModel',
'./views/FirstView',
'./views/SecondView',
'txt!./templates/template.tpl'
], function(FirstModel, SecondModel, FirstView, SecondView, template) {
return {
FirstModel: FirstModel,
SecondModel: SecondModel,
FirstView: FirstView,
SecondView: SecondView,
template: template
}
});
And then when you want to use class from this module you just do
define(['./Module'], function(Module) {
var AView = Module.FirstView.extend({
model: Module.FirstModel,
render: function() {
this.html(_.template(Module.template)(this.model.attributes));
if (something) {
this.$el.append(new Module.SecondView().render().el);
}
}
})
return AView;
});
I don't believe using modules defined with requirejs we should return an instance - we should always return a constructor or an object.
You should totally embrace the defining and requiring - with time you'll start to love it - without having to think much about adding/tracking dependencies etc. everywhere by hand or (so 2005!) having most of the stuff in one file :)