Which is best to use Functional component or Class Component - react-bootstrap

In react project, which is best to use a functional component or a Class component

I believe a functional component is easier to use simply because of the state-management.
Using a class component means that you will have to manage your state as one object. Which quickly becomes messy for large React components.
When using a functional component, states are stored as constants which means that you can access and manage them individually.
In the end its really just about which syntax you prefer.
More information can be found here

Related

External POCO classes to Aspnetboilerplate AbpEntities. i.e. no inheritace possible

We have a pretty common situation and I'd like to understand the best-practice or trade-offs in Aspnetboilerplate/AspNetZero.com to handle this best.
We import a package (NuGet) of pure C# classes (POCO). These are shared across several system. In our AspNetZero server, we want these to be first class persistent objects. However, they can't inherit from Entity, since they come from the Nuget. What is the best practice here?
My ideas to date (not being the expert here, of course):
If we were to use these classes as EF Navigation Properties in Apb Entities, i.e. always use them as complex-type properties of an Abp Entity class, it could do the trick. In this scenario, one would not even need to define a DbSet, although one could (see: https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application )
Alternatively, if we just reference these complex types from an Apb Entity, doesn't EF generate Entity-Proxies for these and automatically make them into EF Navigation Properties (see: https://blogs.msdn.microsoft.com/adonet/2009/12/22/poco-proxies-part-1/ ) or is this not an option the default Abp flow. We'd like to avoid too much custom code (risk).
Any other way via delegation?
Thanks for any Tips/Example/Info!

Component with shouldComponentUpdate vs stateless Component. Performance?

I know that Stateless components are a lot more comfortable to use (In specific scenarios), But since you cannot use shouldComponentUpdate, Doesn't that mean that the component will re-render for each props change?. My question is whether or not its better (Performance-wise) to use a class component with a smart shouldComponentUpdate than use a stateless component.
Are stateless components a better solution as far as performance goes?
consider this silly example:
const Hello =(props) =>(
<div>
<div> {props.hello}</div>
<div>{props.bye}</div>
</div>);
vs
class Hello extends Component{
shouldComponentUpdate(nextProps){
return nextProps.hello !== this.props.hello
};
render() {
const {hello, bye} = this.props;
return (
<div>
<div> {hello}</div>
<div>{bye}</div>
</div>
);
}
}
Let's assume these components both has 2 props and only one of them we want to track and update if changed (which is a common use-case), would it be better to use Stateless functional component or a class component?
UPDATE
After doing some research as well I agree with the marked answer. Although the performance is better in a class component (with shouldComponentUpdate) it seems as the improvement is negligible for simple component. So my take is this:
For complex components use class extended by PureComponent or Component (Depending on if you were gonna implement your own shouldComponentUpdate)
For simple components Use functional components even if it means that the rerender runs
Try to cut the amount of updates from the closest possible class base component in order to make the tree as static as possible (if needed)
I think you should read Stateless functional components and shouldComponentUpdate #5677
For complex components, defining shouldComponentUpdate (eg. pure render) will generally exceed the performance benefits of stateless components. The sentences in the docs are hinting at some future optimizations that we have planned, whereby we won't allocate an internal instance for stateless functional components (we will just call the function). We also might not keep holding the props, etc. Tiny optimizations. We don't talk about the details in the docs because the optimizations aren't actually implemented yet (stateless components open the doors to these optimizations).
https://github.com/facebook/react/issues/5677#issuecomment-165125151
There are currently no special optimizations done for functions, although we might add such optimizations in the future. But for now, they perform exactly as classes.
https://github.com/facebook/react/issues/5677#issuecomment-241190513
I also recommend checking https://medium.com/missive-app/45-faster-react-functional-components-now-3509a668e69f
To measure the change, I created this benchmark, the results are quite staggering! From just converting a class-based component to a functional one, we get a little 6% speedup. But by calling it as a simple function instead of mounting, we get a ~45﹪ total speed improvement.
To answer the question: it depends.
If you have complex/heavy components you probably should implement shouldComponentUpdate. Otherwise going with regular functions should be fine. I don't think that implementing shouldComponentUpdate for components like you Hello will make big difference, it probably doesn't worth the time implementing.
You should also consider extending from PureComponent rather than Component.

CodeIgniter: Decision making for creating of library & helper in CodeIgniter

After developing in CodeIgniter for awhile, I find it difficult to make decisions when to create a custom library and when to create a custom helper.
I do understand that both allow having business logic in it and are reusable across the framework (calling from different controller etc.)
But I strongly believe that the fact that CI core developers are separating libraries from helpers, there has to be a reason behind it and I guess, this is the reason waiting for me to discover and get enlightened.
CI developers out there, pls advise.
i think it's better to include an example.
I could have a
class notification_lib {
function set_message() { /*...*/}
function get_message() {/*...*/}
function update_message() {/*...*/}
}
Alternatively, i could also include all the functions into a helper.
In a notification_helper.php file, i will include set_message(), get_message(), update_message()..
Where either way, it still can be reused. So this got me thinking about the decision making point about when exactly do we create a library and a helper particularly in CI.
In a normal (framework-less) php app, the choice is clear as there is no helper, you will just need to create a library in order to reuse codes. But here, in CI, I would like to understand the core developers seperation of libraries and helpers
Well the choice comes down to set of functions or class. The choice is almost the same as a instance class verses a static class.
If you have just a simply group of functions then you only need to make a group of functions. If these group of functions share a lot of data, then you need to make a class that has an instance to store this data in between the method (class function) calls.
Do you have many public or private properties to store relating to your notification messages?
If you use a class, you could set multiple messages through the system then get_messages() could return a private array of messages. That would make it perfect for being a library.
There is a question I ask myself when deciding this that I think will help you as well. The question is: Am I providing a feature to my framework or am I consolidating?
If you have a feature that you are adding to your framework, then you'll want to create a library for that. Form validation, for example, is a feature that you are adding to a framework. Even though you can do form validation without this library, you're creating a standard system for validation which is a feature.
However, there is also a form helper which helps you create the HTML of forms. The big difference from the form validation library is that the form helper isn't creating a new feature, its just a set of related functions that help you write the HTML of forms properly.
Hopefully this differentiation will help you as it has me.
First of all, you should be sure that you understand the difference between CI library and helper class. Helper class is anything that helps any pre-made thing such as array, string, uri, etc; they are there and PHP already provides functions for them but you still create a helper to add more functionality to them.
On the other hand, library can be anything like something you are creating for the first time, any solution which might not be necessarily already out there.
Once you understand this difference fully, taking decision must not be that difficult.
Helper contains a group of functions to help you do a particular task.
Available helpers in CI
Libraries usually contain non-CI specific functionality. Like an image library. Something which is portable between applications.
Available libraries in CI
Source link
If someone ask me what the way you follow when time comes to create Helpers or Libraries.
I think these differences:
Class : In a nutshell, a Class is a blueprint for an object. And an object encapsulates conceptually related State and Responsibility of something in your Application and usually offers an programming interface with which to interact with these. This fosters code reuse and improves maintainability.
Functions : A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value. You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well.
So go for Class i.e. libraries if any one point matches
global variable need to use in two or more functions or even one, I hate using Global keyword
default initialization as per each time call or load
some tasks are private to entity not publicly open, think of functions never have public modifiers why?
function to function dependencies i.e. tasks are separated but two or more tasks needs it. Think of validate_email check only for email sending script for to,cc,bcc,etc. all of these needs validate_email.
And Lastly not least all related tasks i.e. functions should be placed in single object or file, it's easier for reference and remembrance.
For Helpers : any point which not matches with libraries
Personally I use libraries for big things, say an FTP-library I built that is a lot faster than CodeIgniters shipped library. This is a class with a lot of methods that share data with each other.
I use helpers for smaller tasks that are not related to a lot of other functionality. Small functions like decorating strings might be an example. Or copying a directory recursively to another location.

Best practices for implementing models in the MVC pattern

What are the best practices for implementing models in the MVC pattern. Specifically, if I have "Users" do I need to implement 2 classes. One to manage all the users and one to manage a single user. So something like "Users" and "User"?
I'm writing a Zend Framework app in php but this is more a general question.
The model should be driven by the needs of the problem. So if you need to handle multiple users, then a class representing a collection of Users might be appropriate, yes. However, if you don't need it, don't write it! You may find that a simple array of User objects is sufficient for your purposes.
That's going to be application and MVC implementation specific. You might well define a class collecting logically related classes, or you could define a static register on the user class. This is more of an OO question than MVC.
I'll second Giraffe by saying the use of included collections is almost always better than trying to write your own.
But I think your original question could be reworded a little differently... "Do I need a separate class to manage users other than the User class?
I use a static factory class to build all of my users and save them back to the database again. I'm of the opinion that your model classes need to be as dumbed down as possible and that you use heavy controller classes to do all of the work to the model classes.

How to construct two objects, with each other as a parameter/member

I have two classes that each need an instance of each other to function. Ordinarily if an object needs another object to run, I like to pass it in the constructor. But I can't do that in this case, because one object has to be instantiated before the other, and so therefore the second object does not exist to be passed to the first object's constructor.
I can resolve this by passing the first object to the second object's constructor, then calling a setter on the first object to pass the second object to it, but that seems a little clunky, and I'm wondering if there's a better way:
backend = new Backend();
panel = new Panel(backend);
backend.setPanel();
I've never put any study into MVC; I suppose I'm dealing with a model here (the Backend), and a view or a controller (the Panel). Any insights here I can gain from MVC?
It's time to take a look at MVC. :-) When you have a model-view-controller situation, the consensus is that the model shouldn't be aware of the view-controller (MVC often plays out as M-VC), but the view is invariably aware of the model.
If the model needs to tell the view something, it does so by notifying its listeners, of which it may have multiples. Your view should be one of them.
In a circular construction scenario I'd use a factory class/factory method. I would normally make the construction logic private to the factory (using friend construct, package level protection or similar), to en sure that no-one could construct instances without using the factory.
The use of setter/constructor is really a part of the contract between the two classes and the factory, so I'd just use whichever's convenient.
As has been pointed out, you really should try to find a non-circular solution.
First of all, contrary to what others has said here, there's no inherent problem with circular references. For example, an Order object would be expected to have a reference to the Customer object of the person who placed the Order. Similarly, it would be natural for the Customer object to have a list of Orders he has placed.
In a refernce-based language (like Java or C#) there's no problem, at all. In a value-based language (like C++), you have to take care in designing them.
That said, you design of:
backend = new Backend();
panel = new Panel(backend);
backend.setPanel(panel);
It pretty much the only way to do it.
It's better to avoid circular references. I would personally try to rethink my objects.
panel = new Panel(backend);
You do this in this routine something like
Public Sub Panel(ByVal BackEnd as BackEnd)
Me.MyBackEnd = BackEnd
BackEnd.MyPanel = Me
End Sub
You don't need BackEnd.SetPanel
It is better to use Proxies. A proxy links one object to another through raising a Event. The parent hands the child a proxy. When the child needs the parent it calls a GetRef method on the proxy. The proxy then raises a event which the parent uses to return itself to the proxy which then hands it to the child.
The use of the Event/Delegate mechanism avoids any circular reference problems.
So you have (assuming that the backend is the 'parent' here)
Public Sub Panel(ByVal BackEnd as BackEnd)
Me.MyBackEnd = BackEnd.Proxy
BackEnd.MyPanel = Me
End Sub
Public Property MyBackEnd() as BackEnd
Set (ByVal Value as BackEnd)
priBackEndProxy = BackEnd.Proxy
End Set
Get
Return priBackEndProxy.GetRef
End Get
End Property
Here is a fuller discussion on the problem of circular references. Although it is focused on fixing it in Visual Basic 6.0.
Dynamic Memory Allocation
Also another solution is aggregating Panel and BackEnd into another object. This is common if both elements are UI Controls and need to behave in a coordinated manner.
Finally as far as MVC goes I recommend using a a Model View Presenter approach instead.
Basically you have your Form Implement a IPanelForm interface. It registers itself with a class called Panel which does all the UI logic. BackEnd should have events that Panel can hook into for when the model changes. Panel handles the event and updates the form through the IPanelForm interface.
User clicks a button
The form passes to Panel that the user clicked a button
Panel handles the button and retrieves the data from the backend
Panel formats the data.
Panel uses IPanelForm Interface to show the data on the Form.
I've been delaying implementing the lessons learned here, giving me plenty of time to think about the exact right way to do it. As other people said, having a clear separation where the backend objects have listeners for when their properties change is definitely the way to go. Not only will it resolve the specific issue I was asking about in this question, it is going to make a lot of other bad design smells in this code look better. There are actually a lot of different Backend classes (going by the generic class names I used in my example), each with their own corresponding Panel class. And there's even a couple of places where some things can be moved around to separate other pairs of classes into Backend/Panel pairs following the same pattern and reducing a lot of passing junk around as parameters.
The rest of this answer is going to get language specific, as I am using Java.
I've not worried a whole lot about "JavaBeans," but I have found that following basic JavaBean conventions has been very helpful for me in the past: basically, using standard getters and setters for properties. Turns out there's a JavaBean convention I was unaware of which is really going to help here: bound properties. Bound properties are properties available through standard getters and setters which fire PropertyChangeEvents when they change. [I don't know for sure, but the JavaBeans standard may specify that all properties are supposed to be "bound properties." Not relevant to me, at this point. Be aware also that "standard" getters and setters can be very non-standard through the use of BeanInfo classes to define a JavaBean's exact interface, but I never use that, either.] (The main other JavaBean convention that I choose to follow or not as appropriate in each situation is a no-argument constructor; I'm already following it in this project because each of these Backend objects has to be serializable.)
I've found this blog entry, which was very helpful in cluing me into the bound properties/PropertyChangeEvents issue and helping me construct a plan for how I'm going to rework this code.
Right now all of my backend objects inherit from a common class called Model, which provides a couple of things every backend in this system needs including serialization support. I'm going to create an additional class JavaBean as a superclass of Model which will provide the PropertyChangeEvent support that I need, inherited by every Model. I'll update the setters in each Model to fire a PropertyChangeEvent when called. I may also have JavaBean inherited by a couple of classes which aren't technically Models in the same sense as these but which could also benefit from having other classes registered as listeners for them. The JavaBean class may not fully implement the JavaBean spec; as I've said, there are several details I don't care about. But it's good enough for this project. It sounds like I could get all this by inheriting from java.awt.Component, but these aren't components in any sense that I can justify, so I don't want to do that. (I also don't know what overhead it might entail.)
Once every Model is a JavaBean, complete with PropertyChangeEvent support, I'll do a lot of code cleanup: Models that are currently keeping references to Panels will be updated and the Panels will register themselves as listeners. So much cleaner! The Model won't have to know (and shouldn't have known in the first place) what methods the Panel should call on itself when the property updates.

Resources