1.3.3 understand program running
In a general imperative style, a program consists of objects with internal states, which can be directly changed or changed by calling object methods. This means that when we call a method, it is difficult to know which state this operation affects. For example, in the C # code snippet in listing 1.1, we create an ellipse, obtain its border, call the method on the returned rectangle, and finally return the ellipse to the caller.
Listing 1.1 working with ellipse andrectangle (C #)
Ellipse ellipse = new ellipse (newrectangle (0, 0,100,100 ));
Rectangle boundingbox = ellipse. boundingbox;
Boundingbox. Inflate (10, 10 );
Return ellipse;
How can we know the status of the elliptic after the code is run? Can we read the code? It is very difficult, because boundingbox may point to an elliptical border [that is, the reference type], the inflate method can modify the rectangle, and the ellipse also changes; or, the rectangle type may be a value type (in C #, it is declared using the keyword struct). When we assign it to a variable, it will be copied, in this way, the inflate method will not modify the original rectangle, and the result is a new rectangle, so the third row will not have any effect.
In functional programming, most data structures are immutable, so we cannot modify them. Therefore, after an ellipse or rectangle is created, it cannot be changed. The only thing you can do is to create a new ellipse using the new border method.
In this way, it is easy to understand how the program runs, as shown in listing 1.2. If the ellipse and rectangle are both immutable, we can rewrite the previous code segment. As you can see, it is easier to understand program behavior.
Listing 1.2 Working with immutable ellipseand rectangle (C #)
Ellipse ellipse = new ellipse (newrectangle (0, 0,100,100 ));
Rectangle boundingbox = ellipse. boundingbox;
Rectangle smallerbox = boundingbox. Inflate (10, 10 );
Return new ellipse (smallerbox );
When writing a program with an immutable type, the only thing the method can do is to return the result. It cannot modify the status of any object. As you can see, because the result of the inflate method returns a new rectangle, a new ellipse is created. As the return result, the border of the ellipse is modified. This method may be a bit unfamiliar for the first time, but remember that this is not a new idea for. NET developers. In. net, strings may be the most famous immutable type. Of course, there are many examples, such as date and time and other value types.
Function programming further utilizes this idea to make it easy to see how the program runs, because the results of the method can fully explain what the method is doing. We will discuss immutable in detail later, but we should first discuss a very useful field: implementing multi-threaded applications.