How to expose a generator to ES5 code? - babeljs

This question is specific to library creation. Similar questions have been asked related to tests, but libraries require a different approach because they are consumed independently.
I'm writing a library that exposes a class that is iterable using a generator. It is compiled to ES5 with babel and includes the polyfill.
How can ES5 code iterate over the generator in a straightforward way?
I'm thinking about adding a toArray method to the class that turns the result into an array:
// GeneratorClass is exposed by the library
var generator = new GeneratorClass();
generator.toArray().forEach(function (item) {
// ...
});
Is this a common approach? Or is there a better one?
Even though they are available, you can't expect consumers to know/care about how to use the generator[Symbol.iterator] and iterator.next methods.

Related

How to write Dart idiomatic utility functions or classes?

I am pondering over a few different ways of writing utility classes/functions. By utility I mean a part of code being reused in many places in the project. For example a set of formatting functions for the date & time handling.
I've got Java background, where there was a tendency to write
class UtilsXyz {
public static doSth(){...};
public static doSthElse(){...};
}
which I find hard to unit test because of their static nature. The other way is to inject here and there utility classes without static members.
In Dart you can use both attitudes, but I find other techniques more idiomatic:
mixins
Widely used and recommended in many articles for utility functions. But I find their nature to be a solution to infamous diamond problem rather than utility classes. And they're not very readable. Although I can imagine more focused utility functions, which pertain only Widgets, or only Presenters, only UseCases etc. They seem to be natural then.
extension functions
It's somehow natural to write '2023-01-29'.formatNicely(), but I'd like to be able to mock utility function, and you cannot mock extension functions.
global functions
Last not least, so far I find them the most natural (in terms of idiomatic Dart) way of providing utilities. I can unit test them, they're widely accessible, and doesn't look weird like mixins. I can also import them with as keyword to give some input for a reader where currently used function actually come from.
Does anybody have some experience with the best practices for utilities and is willing to share them? Am I missing something?
To write utility functions in an idiomatic way for Dart, your options are either extension methods or global functions.
You can see that they have a linter rule quoting this problem:
AVOID defining a class that contains only static members.
Creating classes with the sole purpose of providing utility or otherwise static methods is discouraged. Dart allows functions to exist outside of classes for this very reason.
https://dart-lang.github.io/linter/lints/avoid_classes_with_only_static_members.html.
Extension methods.
but I'd like to unit test some utility functions, and you cannot test extension functions, because they're static.
I did not find any resource that points that the extension methods are static, neither in StackOverflow or the Dart extension documentation. Although extension can have static methods themselves. Also, there is an open issue about supporting static extension members.
So, I think extensions are testable as well.
To test extension methods you have 2 options:
Import the extension name and use the extension syntax inside the tests.
Write an equivalent global utility function test it instead and make the extension method call this global function (I do not recommend this because if someone changes the extension method, the test will not be able to caught).
EDIT: as jamesdlin mentioned, the extension themselves can be tested but they cannot be mocked since they need to be resolved in compile time.
Global functions.
To test global functions, just import and test it.
I think the global functions are pretty straightforward:
This is the most simple, idiomatic way to write utility functions, this does not trigger any "wtf" flag when someone reads your code (like mixins), even Dart beginners.
This also takes advantage of the Dart top-level functions feature.
That's why I prefer this approach for utility functions that are not attached to any other classes.
And, if you are writing a library/package, the annotation #visibleForTesting may fall helpful for you (This annotation is from https://pub.dev/packages/meta).

Static method and constructor interception mocking in Scala/Spark

All, Here is a problem that my searches have yielded little insight into. I think this should be a fairly common problem for all of us developing against big data frameworks but also seek 100% test coverage. So I will post the question here in an attempt to gather the best community response & ideas.
Consider the scenario where we need to mock a class that instantiate an external API object
class SolrClientWrapper {
def doWork() = {
val cli = new CloudSolrClient("zkHost1")
???
}
}
To get 100% test coverage, and without actually relying on the Solr server to be up at all times during unit testing, we shall have a way to intercept the call to new CloudSolrClient. As far as I know, the ONLY library available is PowerMock
Here is The Twist
PowerMock and other Mock libraries require asm as a dependency, but a complex framework Spark project also require asm. There are version conflicts and thus (test-)runtime hell.
What is the best design refactor/libraries for this situation?
Instead of creating a new CloudSolrClient object within the SolrClientWrapper class, it should be passed as a dependency. Then in your test you can pass a mock instead of the real object. Note that there are many dependency injection frameworks and mechanisms that can make it easier for you to manage your dependencies (e.g. to automatically instantiate them and pass to the constructor for you).
Not sure what asm is, but the code you posted should be easily testable without such dependencies once you remove parts of the code that instantiate stuff inside the class body (and thus the need to "intercept" anything).

Pros and Cons of react-native Component versus React.createClass to implement UI components?

What are the advantages of one versus the other?
Is one being deprecated and I should be using the newer one whichever that may be?
Should I be creating Components or React Class to develop my UI?
I see some examples using Component. For example:
export default class ItemList extends Component {
constructor(props) {
//binding functions
this.renderHeader = this.renderHeader.bind(this);
this.renderRow = this.renderRow.bind(this);
super(props);
this.state = {
dataSource: this.props.state.planDataSource,
planName: null
}
}
And others using
var ItemList = React.createClass({
getInitialState: function() {
return {
dataSource: this.props.state.planDataSource,
planName: null
};
},
I am learning react-native by example and I am confused as to which is preferred.
I recently converted a React class to a component and discovered that the "this" pointer does not work because React classes used autobinding and Components require explicit binding.
You should prefer Class over createClass because it will probably be deprecated.
The most notable new feature is support for ES6 classes, which allows developers to have more flexibility when writing components. Our eventual goal is for ES6 classes to replace React.createClass completely, but until we have a replacement for current mixin use cases and support for class property initializers in the language, we don't plan to deprecate React.createClass.
https://facebook.github.io/react/blog/2015/03/10/react-v0.13.html
No Autobinding
Methods follow the same semantics as regular ES6
classes, meaning that they don't automatically bind this to the
instance. You'll have to explicitly use .bind(this) or arrow functions
=>.
No Mixins
Unfortunately ES6 launched without any mixin support.
Therefore, there is no support for mixins when you use React with ES6
classes. Instead, we're working on making it easier to support such
use cases without resorting to mixins.
https://facebook.github.io/react/docs/reusable-components.html
Unless you're using mixins, always use class (read ES6) instead of React.createClass. Most of the react-native code are in ES6, so it helps to stay up to date with the current standards.
There is no difference regarding performance/UI. class (ES6) is a better way of writing react/react-native/JS code anyways. FWIW: http://es6-features.org/.
As I saw in you comment, you're looking for an answer in simple words:
When looking at the example you provide in your question, you might be thinking "Oh my, why should I use this more verbose version with extends Component if it basically does the same as createClass?"
Well, the syntax using extends Component is the modern way of writing React Native UI Components and Javascript code in general. You should stick to this all the time unless you need a special feature called mixins because using the createClass way of writing components might soon be deprecated in React Native as pointed out by the other answers.
This modern version of Javascript is called ECMAScript 6 (with its compiler called babel which translates the new Javascript syntax into the old one so that that the current browsers can all understand it). It introduced this new more object-oriented way of writing Javascript with classes.
The naming in React is quite confusing when starting to transition to the new JS syntax, because the old syntax with createClass actually is not part of the new object-oriented syntax with classes, methods and such.
This article nicely contrasts the differences between the two syntax styles you asked about in your question.
As an additional tipp, you don't have to bind this to your functions (e.g. this.renderHeader = this.renderHeader.bind(this); in your example if you define your custom functions by using another feature of ECMAScript 6 called arrow functions. This immediately deletes two more lines of code from your example and the two approaches require roughly the same amount of typing.

By how much is the compiled js reduced in size by using concrete classes instead of interfaces

I have read that for GWT, specifying methods to return a concrete implementation, for example:
public ArrayList<String> getList();
instead of the normally-preferred "abstract interface", for example:
public List<String> getList();
results in GWT producing a smaller compiled javascript file, because the client (ie js) code doesn't have to cater for all known implementations of the interface (in the example of List, the client code would have to be able to handle LinkedList, ArrayList, Vector, etc), so it can optimize the js by not compiling unused implementations.
My closely-related questions are:
Is this true? (the following questions assume it is true)
Is the optimization per-class that uses interfaces, or per application? ie
Do I see a benefit just refactoring up one class? or
Do I only see a benefit once all client classes are refactored to not use interfaces?
The following assumes that you use the interface as part of the signature of GWT RPC service. I think if you do not use the interface in the signature of GWT RPC service, the effect of using classes instead of interfaces should be minimal (e.g. the GWT compiler will only compile the used implementations)
Is this true? (the following questions assume it is true)
Yes, the output of the GWT compiler gets smaller when it 'knows' better which classes might be send from server to client.
Is the optimization per-class that uses interfaces, or per application? ie
In case of GWT RPC, per application.
Do I see a benefit just refactoring up one class?
Yes, one interface replaced by an implementation can reduce generated code size by a few kb, if the interface would require to include code for many classes.
However, apart from using implementations instead of interfaces, also a 'blacklist' of classes can be defined in the module definition file to explicitly circumvent the inclusion of implementations in the generated code: something like
<extend-configuration-property name="rpc.blacklist"
value="-java.util.ArrayList" />
I just did a test based on the sample app generated by webAppCreator, but I added 3 simple services that returned either List<String> or ArrayList<String>, depending on the build.
The results were that having all services use ArrayList<String> saved about 5Kb from the compiled javascript over having any mix of the return types.
That proves the saving is real and per-app (not per-service).
It also show how much it saves (in this case).
This doesn't actual to the GWT-compiler in general. Such approach is applied only for classes used with code generation. For example, when using Remote Procedure Calls. See this question for more detail information. Thus, if you declare an interface instead of a concrete class as the return type, the compiler includes all possible implementations in your compiled code. This increases time of compilation and a amount of generated code.
Actually one might develop application using GWT without RPC. In this case compiled code doesn't bloat when using interfaces.

NodeJS modules vs classes

To me classes are quite similar to NodeJS (CommonJS) modules. You can have many of them, they can be reused, they can use each other and they are generally one-per-file.
What makes modules so different from classes? The way you use them differs, and the namespace difference is obvious. Besides that they seem very much the same thing to me or perhaps I am just not seeing the obvious benefit here.
Modules are more like packages (to use the Java term) than classes. You don't instantiate a module; there is only one copy of it. It's a tool for organizing related functionality, but it doesn't typically encapsulate the data of a particular instance of an object.
Probably the closest analogue to a class (setting aside those libraries that actually construct class-based inheritance in JavaScript) is just a constructor function. You can of course put such functions inside a module.
function Car() {
this.colour = 'red';
}
Car.prototype.getColour = function() { return this.colour; };
var myCar = new Car();
myCar.getColour(); // returns 'red'
You use both modules and classes for encapsulation, but the nature of that encapsulation is different.
JS was initially a prototypal inheritance system. It was super simple like the rest of the language. But then Netscape decided to make it be more like Java and added the idea of constructors to the language. Hence pseudo classes were born.
You can check this link to know how prototypal OOP is used in JS:
http://howtonode.org/prototypical-inheritance
One critical thing; that "generally one-per-file" thing is not true; modules are absolutely one-per-file. A require() that brings the module's exports into the namespace has no way of distinguishing between the exported contents of that module; everything that module (file) exports are imported with a require() statement. Attempting to put more than one module into a file only means that you'll get everything in that file when you try to load "either" module.