Generality in Functions

◀ Function Template▶ Function Pointer
Amazon As discussed in the previous section, a function template is able to replace multiple functions using genericity. This is one way to reduce code size. However, this type of situation does not come up often because you normally make a function deal with only certain argument types.

Another way to replace many functions with one function is to generalize the meaning of the functions, and then write one or two functions that accommodate all of them. Sometimes this is achievable but not always.

Usually to achieve this effect, a flag is necessary as one of the arguments of the function. As an example, let’s consider the following scenario. You are writing a server that serves a client’s requests. Assume there are exactly five request types a client may issue. You decide to write five functions to serve the requests.


First you determine what the request is, then call the appropriate function. However, you can also write one function that servers a request given its identity, and you can merge the parts where the requests are doing the same things into one block of code, thereby reducing code size.

So you simply have one function in which there are several if or switch statements. This is actually in regards to the program I mentioned in the beginning of Chapter 4.2.
◀ Function Template▶ Function Pointer

fShare
Questions? Let me know!