[Effective JavaScript notes] 56th: avoid unnecessary state

Source: Internet
Author: User

APIs are sometimes categorized into two categories: stateful and stateless. The behavior of a stateless API provides functions or methods that depend only on the input, regardless of the state of the program. The method of the string is stateless. The contents of a string cannot be modified, only depending on the contents of the string and the arguments passed to the method. Regardless of the other part of the program, the expression "foo". toUpperCase () always produces "foo". Instead, the method of the Date object is stateful. Calling the ToString method for the same date object produces different results, depending on whether the various set methods of date have modified the properties of date.

Stateful and stateless

Stateless APIs are easier to learn and use, more self-describing, and less prone to error. But the state is sometimes required, the Web API Canvas library. is a stateful library that provides user interface element methods for drawing shapes and pictures to its plane. A program can use the Filltext method to draw text to a canvas.

c.fillText(‘hello,world~!‘,75,25);

The method provides a string for drawing and a position in the picture. It does not, however, make other attributes of the text being drawn, such as color, transparency, or text style. All properties are specified individually by changing the internal state of the canvas.

c.fillStyle=‘blue‘;c.font=‘24pt serif‘;c.textAlign=‘center‘;c.fillText(‘hello,world~‘,75,25);

The stateless version of the API might look like this:

c.fillText(‘hello,world~‘,75,25,{    fillStyle:‘blue‘,    font:‘24pt serif‘,    textAlign:‘center‘})

Why is it preferable to have a stateless version later?
First, it is not fragile. In order to be customizable, stateful APIs need to modify the internal state of the canvas, which causes the drawing operations to interact with each other, even if there are no associated actions.

Default value Issues

For example, the default fill style is black. If you want to get the default value, you must not change the default value. If you want to use the default values for drawing operations after the default values have been modified, you must display the specified default values.

c.fillText(‘text 1‘,0,0);c.fillStyle=‘blue‘;c.fillText(‘text 2‘,0,30);c.fillStyle=‘black‘;c.fillText(‘text 3‘,0,60);

The stateless API automatically reuses the default values compared to stateful APIs.

c.fillText(‘text 1‘,0,0);c.fillText(‘text 2‘,0,30,{fillStyle:‘blue‘});c.fillText(‘text 3‘,0,60)

Notice how each statement becomes more readable. Any separate call to the Filltext method does not have to know all the modifications that precede it. In fact, the canvas may have been modified in some completely separate parts of the program. A piece of code elsewhere modifies the state of the canvas, which is prone to error.

c.fillStyle=‘blue‘;drawMyImage(c);c.fillText(‘hello,world~‘,75,25);
Modularity issues

Stateless APIs make your code more modular, avoiding the interplay of different parts of your code, and making your code easier to read.
Stateful APIs are more difficult to learn. It is difficult for non-professionals to know if all the necessary states have been initialized correctly. When you need a stateful API, you need to be careful to record these state dependencies. But the stateless API completely eliminates implicit dependencies, so there is no need to provide additional documentation at the very beginning.

Complexity of

Another benefit of stateless APIs is simplicity. Stateful APIs tend to cause additional claims, setting the internal state of an object only before the method is called. Consider a popular "INI" configuration file format parser. For example, a simple INI file is like this.

[Host]address=172.0.0.1name=localhost[Connection]timeout=10000

One way to manipulate this data API is to provide a setsection method to select a zone before using the Get method to find the configuration parameters

var ini=INI.parse(src);ini.setSection(‘Host‘);var addr=ini.get(‘address‘);var hostname=ini.get(‘name‘);ini.setSection(‘Connection‘);var timeout=ini.get(‘timeout‘);var server=new Server(addr,hostname,timeout);

For stateless APIs, it is not necessary to create additional variables to save the extracted data before updating the zone.

var ini=INI.parse(src);var server=new Server(ini.Host.address,ini.Host.name,ini.Connection.timeout);

Note: Once you explicitly specify a zone, you can simply represent the INI object as a dictionary, and each region is simpler to use as a dictionary.

Tips
    • Use stateless APIs as much as you can

    • If the API is stateful, indicate which states are associated with each operation

Related reading
    • 5th chapter: Arrays and dictionaries

[Effective JavaScript notes] 56th: avoid unnecessary state

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.