Wednesday, March 2, 2022

Generalization functionality

An ideal reusable module should focus on solving a general problem rather than a very specific problem. For example, we have a requirement of converting inches to centimeters. We can easily write a function that converts inches into centimeters by applying a conversion formula. What about writing a function that converts any value in the imperial system to a value in the metric system? We can have one function for different conversions that may handle inches to centimeters, feet to meters, or miles to kilometers, or separate functions for each type of these conversions. What about the reverse functions (centimeters to inches)? This may not be required now but may be required later on or by someone who is reusing this module. This generalization will make the module functionality not only comprehensive but also more reusable without extending it.

To illustrate the generalization concept, we will revise the design of the myrandom module to make it more general and thus more reusable. In the current design, we define separate functions for one-digit and two-digit numbers. What if we need to generate a three-digit random number or to generate a random number between 20 and 30? To generalize the requirement, we introduce a new function, get_random, in the same module, which takes user input for lower and upper limits of the random numbers. This newly added function is a generalization of the two random functions we already defined.

With this new function in the module, the two existing functions can be removed, or they can stay in the module for convenience of use. Note that the newly added function is also offered by the random library out of the box; the reason for providing the function in our module is purely for illustration of the generalized function (get_random in this case) versus the specific functions (random_1d and random_2d in this case).

The updated version of the myrandom.py module (myrandomv2.py) is as follows:

# myrandomv2.py with default and custom random functions

import random

def random_1d():

"""This function get a random number between 0 and 9"""

return random.randint(0,9)

def random_2d():

"""This function get a random number between 10 and 99"""

return random.randint(10,99)

def get_random(lower, upper):

"""This function get a random number between lower and\

upper"""

return random.randint(lower,upper)

Share:

0 comments:

Post a Comment