Inheritance and the constructor chain with native duktape/C functions - duktape

Using native functions to implement a class constructor is described in the duktape wiki. What's left out there however is how to implement a class hierarchy.
When your native constructor is called for a derived class, how do you handle the inheritance chain in duktape? In Javascript you would usually do something like:
function Base(){
}
...
function SubClass(){
// Call super constructor.
Base.call(this);
}
How would you implement that in duktape? We cannot use duk_call() since we don't have a method to call.

If you just want the same behavior as in the Ecmascript example, you would do something like:
duk_get_global_string(ctx, "Base");
duk_push_this(ctx);
duk_call_method(ctx, 0); /* = Base.call(this) */

Related

Classes vs modules in Node.js

My question is, if it is better the use classes in Node.js or the function, or prototypes and modules, I know that most use the modules and function prototypes, but which is better?
And we most consider that classes have always been in all programming languages the best option to work.
classes vs. modules is the wrong question
The question you are looking for is classes vs. prototypes.
Both classes and prototypes are used by modules.
Modules (ES2015 Modules) are what JavaScript uses to be able to export and import code. Before JavaScript officially implemented modules there were hacks to do this and create code encapsulation which fixed issues such as pollution of the global scope; Immediately Invoked Function Expressions is an example. Node.js with CommonJS and Angular with AMD and several others tried to figure out how to do this in a better way and implemented their own 'module' system. I would like to think ES2015 Modules were influenced by other languages and CommonJS/Amd etc. and as a result, we now have a module system in JavaScript.
As for classes, they themselves create code encapsulation, but they cannot export themselves, that's what modules do. The same applies for the prototype based code, it creates code encapsulation but cannot export it self just like classes.
Now to put this together.
Example of a module, this example has nothing to do with classes or prototypes, only-a-module.js:
const privateHello = 'hello' // <- module code (private)
export const publicHello = 'hello'; // <- module code (public)
Example of a module that uses a class, module-that-exports-a-class.js:
export class Classes { // <- module AND class code (public)
private privateHello = 'hello'; // <- class code (private)
public publicHello = 'hello'; // <- class code (public)
} // <- class code (public)
const anotherPrivateHello = 'hello'; // <- module code (private)
export const anotherPublicHello = 'hello'; // <- module code (public)
Example of a module that uses prototypes, module-that-exports-a-prototype.js:
export function Prototypes() { // <- module AND prototype code (public)
const privateHello = 'hello'; // <- prototype code (private)
this.publicHello = 'hello'; // <- prototype code (public)
} // <- prototype code (public)
const anotherPrivateHello = 'hello'; // <- module code (private)
export const anotherPublicHello = 'hello'; // <- module code (public)
What makes this confusing to beginners coming from OOP languages is that for example in Java a class file (file.class) is automatically exported as a class, this is by default as this is how Java works. This is not the case in JavaScript. You must state what you are exporting.
Classes are an attempt to implement so called classical inheritance while prototype is, you guessed it, prototypal inheritance. These are two ways to deal with code-reuse and objects that keep their own state.
If we want to make things even more complicated, a good followup question is OOP vs. functional programming. But you can read that up in other places.
My question is if it is better the use classes in nodejs or the function or prototypes and modules, i know that most use the modules and function prototypes, but which is better?
Your question seems a bit misguided. In node.js, one does not choose between classes, prototypes and modules.
First off classes in Javascript uses the prototype. The class syntax is just syntactical sugar for defining a constructor and methods on the prototype. When you use the class syntax, you are creating a constructor with a prototype and causing methods to be added to the prototype (under the covers). So, there is no tradeoff between using classes and using the prototype.
The only tradeoff there is there is between using the new class syntax to define your prototype vs. doing it the older, manual way.
Then, classes are pretty much orthogonal to modules. You use modules when you want to encapsulate a body of code in a module interface so you can reap all the benefits of using modules (easier sharing, reuse, documenting, testing, etc...). That module interface can be whatever you think is most appropriate for your circumstance. You can export a series of plain functions. You can export one or more object constructors. You can export factory functions that create objects for you that you can then use methods on. The module scheme is massively flexible so you can export pretty much any type of interface you want (and classes can be a part of that if you choose).
There is no "best" way to export things from modules because it depends upon your needs, your chosen architectural and coding style, etc...

Abstracting class using mongoose

I'm developing an application in which I need to have some abstraction.
I mean there, that I would like to "simulate" an interface behaviour like creating a contract inside of my concrete classes.
Actually, dealing with Users, I'm having a UserMongoRepository class with the contract implemented :
getAll() returns the full list of users by promise
getById(id) returns the user concerned by promise
save(user) saves the user by promise
... etc
I have the same methods implemented inside of the UserMysqlRepository (allowing me to switch behaviour when a change is needed.
Problem
My problem is that I'm dealing with Mongoose that doesn't act like a datamapper, but more like an active record.
It means that my implementation of save(user) would be a bit weird like following :
save(user){
let mongooseUser = this.convert(user);
return user.save();
}
The convert method allows me to switch from a standard Model to a specific Mongoose model. It allows me, again, to have some abstraction and to don't have to rewrite my full application data access.
My real problem is when I try to unit test my full class :
import MongooseUser from '../../auth/mongooseModel/MongooseUser';
/**
* UserMongoRepositoryclass
*/
export default class UserMongoRepository{
/**
* Create an UserMongoRepository
*/
constructor(){
}
/**
* Convert a User to a MongooseUser
*/
convert(user){
return new MongooseUser({email:user.mail,password:user.password,firstname:user.firstName, lastname:user.lastName});
}
findById(id){
return MongooseUser.find({id:id});
}
save(user){
return user.save();
}
}
In a standard way, I would inject my DAO inside of my constructor, and being able to mock it.
In the case of mongoose, it's a bit disturbing, because the element that makes the job isn't an instantiated object (so that I can mock it) but a class definition imported at the top of the document.
Solutions
Should I pass the MongooseUser class definition as a parameter inside of the constructor ?
Implying that I will have this code inside of the convert method :
let user = new this.MongooseUser({})
Have you got a better idea, to abstract mongoose behaviour in data mapper way ?
I don't want to use another module, it's, in my sense, the most advanced one with NodeJS...
I'm not familiar with the import syntax (nor EMCASCRIPT-6), though you say you're using node.js, so I'd recommend using the proxquire package. The idea is that the package allows you to require an external package, while stubbing the requirements that that package would use. So in your case, you could do something like:
proxyquire('../my/class/that/uses/mongoose', {
mongoose: MyTestMongooseImplementation
})
Which would allow you to use your own mongoose implementation while still using your MongooseUser as you have defined it in your package. Alternatively, you could just override the the MongooseUser class (path relative to the the file whose requirements you are stubbing:
proxyquire('/path/to/UserMongooseRepository', {
'../../auth/mongooseModel/MongooseUser': MyTestMongooseUser
})
Documentation: https://www.npmjs.com/package/proxyquire

Difference between Mockito #Spy and #Mock(answer = Answers.CALLS_REAL_METHODS)

What is the difference between these two declarations in Mockito?
#Mock(answer = Answers.CALLS_REAL_METHODS)
ArrayList<String> mock;
#Spy
ArrayList<String> spy;
The former CALLS_REAL_METHODS style creates an uninitialized object; no constructors are run and no fields are set. Generally this syntax is unsafe, as real implementations will interact with uninitialized fields that may constitute an invalid or impossible state.
The latter #Spy style allows you to call a constructor of your choice, or Mockito will try to call a no-arg constructor if the field is uninitialized. The fields are then copied into a generated Spy (that extends the spied-on type), allowing for much safer and more-realistic interactions.
Requisite reminder: Don't actually mock Java collections outside of toy examples, and don't forget to use doReturn syntax when overriding spies and CALLS_REAL_METHOD mocks or else you'll call the real method within the when call.

Wrapping constructor call in the method to the static call using ASM bytecode manipulation

My query is related to bytecode manipulation using ASM.
I have one method as follows --
/*Original method code*/
String str ="abs";
// create object of SampleClass2 // constructor calling
SampleClass2 sample = new SampleClass2();
// call instance method
sample.PrintMe(str);
In the above method, I want to change the SampleClass2() constructor to one static method call which will return same SampleClass2 object after doing some logic. So after that my method will look something like this.
/*
* After bytecode manipulation*
*/
String str ="abs";
// get a constructor using static call
SampleClass2 sample = StaticClass.getSampleClass2Object();
sample.PrintMe(str);
Please tell me how can I achieve this using ASM bytecode manipulation. Do we need to change the existing bytecode stack for the same like DUP
The main problem is that the object is first created with a "new" instruction, followed by the call to the constructor. You'd have to replace both the "new" and the constructor call, which might be difficult to achieve. If you want to go along that road, make sure to check out Chapter 8 (Tree API -> Method Analysis) p 115 in the ASM documentation.
However, if that is enought, you could simply add a call to a static method to do some post instantiation logic, which is fairly simple. Just find the constructor call, and add a static invocation to a method afterwards which takes a SampleClass2 as parameter and returns a SampleClass2 (probably the same instance)

Weird inheritance in Node.js

I've been poking into some Node.js modules in the hopes of learning something I could have missed while creating a module with similar functionality. Then I came across this code from Hound:
function Hound() {
//why this?
events.EventEmitter.call(this)
}
//ok, so inheriting the EventEmitter
util.inherits(Hound, events.EventEmitter);
I know that the util.inherits() function from Node.js creates a new Parent instance as the prototype of the child constructor as stated in the docs:
The prototype of constructor will be set to a new object created from superConstructor.
So if our constructor is inheriting EventEmitter through util.inherits(), what is that code in the constructor for?
It's just making your Hound class an EventEmitter object.
It gives your the EventEmitter instance methods to the class.
E.g., houndInstance.emit('something')
Other objects that are listening to these events can then respond to them.
Per your comment:
// constructor
function Hound() {
// equivalent of calling a "super" or "parent" constructor
SomeClass.call(this);
}
In JavaScript, .call(context) is a means of invoking a function in a specific context. In the example above, we're just calling the SomeClass constructor and passing this (the Hound class in this example) as the context.
From your comments:
But doesn't util.inherits() already cover that? Or am I missing something?
What you are missing is that util.inherits() merely inherits the parent object. It doesn't set up the constructor to automatically call the parent object's constructor. In most cases it would be enough since most objects don't do much initialization in their constructors.
But events.EventEmitter apparently does some initialization in the constructor that has some important side effects. Since prototypical inheritance does not automatically call the parent's constructor you need to call it manually in this case. Hence the events.EventEmitter.call(this) line.
Note that an alternative is to use the module pattern which always calls the parent's constructor. That is because the module pattern is not inheritance per-se but emulates inheritance by abusing the mixin/decorator pattern - it creates an object from the parent constructor and manually add attributes to it. Lots of people don't like the module pattern because it duplicates functions and attrubutes - hence they see it as wasting memory. Also, it's not proper inheritance and so breaks stuff like instanceof.

Resources