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

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.

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).

How do you prepare styles without StylePropable mixin?

Now that it's no longer recommended (or possible, given ES6 classes) to use the StylePropable mixin (and because libraries like react-mixin, that try to turn them into decorators have been nothing but trouble), and given that an official replacement hasn't been developed to my knowledge, what's the recommended way to incorporate the behavior (such as auto-prefixing) of the functions it provided, such as prepareStyles? I'm using ^0.14.0.

How to use CoffeeScript together with Google Closure

Recently I have started to use Google Closure Tools for my javascript development. Until now, I have used to write my code in CoffeeScript, however, the javascript generated by CoffeeScript seems to be incompatible with Google Closure Compiler's advanced mode.
Is there any extension to the CoffeeScript compiler adding Google Closure support?
There are various tools that aiming to make CoffeeScript usable with Google Closure Tools. I will describe three of them:
Bolinfest's CoffeeScript fork
Features:
Fixed function binding, loops, comprehensions, in operator and various other incompatibilities
Fixed classes syntax for Google Closure
Automatic generation of #constructor and #extends annotations
Automatically inserts goog.provide statement for each class declared
Python's like include namespace as alias support translated to goog.require and goog.scope
Drawbacks:
Constructor has to be the very first statement in the class
Cannot use short aliases for classes inside the class (i.e. class My.Long.Named.Car cannot be refered as Car in class definition as pure CoffeeScript allows)
User written JsDoc comments don't get merged with compiler generated ones
Missing provide equivalent for include
No support for type casting, this can be done only by inserting pure javascript code inside backticks "`"
Based on outdated CoffeeScript 1.0
Read more at http://bolinfest.com/coffee/
My CoffeeScript fork
Disclaimer: I am the author of this solution
This solution is inspired by the Bolinfest's work and extends it in these ways:
Constructor can be placed anywhere inside the class
Short aliases for classes work using goog.scope
User written JsDoc comments get merged with compiler generated, user written #constructor and #extends annotations are replaced by generated
Each namespace is provided or included mostly once, namespace, that is provided is never included. You can provide namespace by keyword provide
Support for typecasting using cast<typeToCastTo>(valueToBeCast) syntax
Based on CoffeeScript 1.6
Read more at https://github.com/hleumas/coffee-script/wiki
Steida's Coffee2Closure
Unlike the two solutions above, Steida's Coffee2Closure is postprocessor of javascript code generated by upstream nontweaked CoffeeScript. This approach has a one major advantage, that it will need no or only slight updates with continued development of CoffeeScript and still be actual. However, by the very nature of this approach, some of the features cannot be delivered. Currently it fixes only classes and bindings, loops, in operator and few other incompatibilities. It has no support for automatic annotation generation, type casting or custom keywords.
https://github.com/Steida/coffee2closure

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.

Why do dynamic languages like Ruby and Python not have the concept of interfaces like in Java or C#?

To my surprise as I am developing more interest towards dynamic languages like Ruby and Python. The claim is that they are 100% object oriented but as I read on several basic concepts like interfaces, method overloading, operator overloading are missing. Is it somehow in-built under the cover or do these languages just not need it? If the latter is true are, they 100% object oriented?
EDIT: Based on some answers I see that overloading is available in both Python and Ruby, is it the case in Ruby 1.8.6 and Python 2.5.2 ??
Dynamic languages use duck typing.
Any code can call methods on any object that support those methods, so the concept
of interfaces is extraneous.
Python does in fact support operator overloading(check - 3.3. Special method names) , as does Ruby.
Anyway, you seem to be focusing on aspects that are not essential to object oriented programming. The main focus is on concepts like encapsulation, inheritance, and polymorphism, which are 100% supported in Python and Ruby.
Thanks to late binding, they do not need it. In Java/C#, interfaces are used to declare that some class has certain methods and it is checked during compile time; in Python, whether a method exists is checked during runtime.
Method overloading in Python does work:
>>> class A:
... def foo(self):
... return "A"
...
>>> class B(A):
... def foo(self):
... return "B"
...
>>> B().foo()
'B'
Are they object-oriented? I'd say yes. It's more of an approach thing rather than if any concrete language has feature X or feature Y.
I can only speak for python, but there have been proposals for interfaces as well as home-written interface examples in the past.
However, the way python works with objects dynamically tends to reduce the need for (and the benefit of) interfaces to some extent.
With a dynamic language, your type binding happens at runtime - interfaces are mostly used for compile time constraints on objects - if this happens at runtime, it eliminates some of the need for interfaces.
name based polymorphism
"For those of you unfamiliar with Python, here's a quick intro to name-based polymorphism. Python objects have an internal dictionary that contains a string for every attribute and method. When you access an attribute or method in Python code, Python simply looks up the string in the dict. Therefore, if what you want is a class that works like a file, you don't need to inherit from file, you just create a class that has the file methods that are needed.
Python also defines a bunch of special methods that get called by the appropriate syntax. For example, a+b is equivalent to a.add(b). There are a few places in Python's internals where it directly manipulates built-in objects, but name-based polymorphism works as you expect about 98% of the time. "
Python does provide operator overloading, e.g. you can define a method __add__ if you want to overload +.
You typically don't need to provide method overloading, since you can pass arbitrary parameters into a single method. In many cases, that single method can have a single body that works for all kinds of objects in the same way. If you want to have different code for different parameter types, you can inspect the type, or double-dispatch.
Interfaces are mostly unnecessary because of duck typing, as rossfabricant points out. A few remaining cases are covered in Python by ABCs (abstract base classes) or Zope interfaces.