Using keyword arguments in constructors

We can always add new constructor functions to make it easier for creating objects. Using keyword arguments solves the following two problems:

  • Code readability
  • Ability to specify default values

Let's go ahead and define a new constructor as follows:

function TextStyle(;
font_family,
font_size,
font_weight = "Normal",
foreground_color = "black",
background_color = "white",
alignment = "left",
rotation = 0)
return TextStyle(
font_family,
font_size,
font_weight,
foreground_color,
background_color,
alignment,
rotation)
end

Here, we have elected to provide default values for most of the fields except font_family and font_size. It is simply defined as a function that provides keyword arguments for all fields in the struct. Creating the TextStyle object is much easier and the code is more readable now. In fact, we have obtained an additional benefit that the arguments can be specified in any order, as shown here:

style = TextStyle(
alignment = "left",
font_family = "Arial",
font_weight = "Bold",
font_size = 11)

This is, indeed, quite a simple recipe. We can just create this kind of constructor for every struct and the problem is solved. Right? Well, yes and no. While it is fairly easy to create these constructors, it is a hassle to do that for every struct everywhere. 

In addition, the constructor definition must specify all field names in the function arguments, and these fields repeat in the body of the function. So, it becomes quite difficult to develop and maintain. Next, we will introduce a macro to simplify our code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.140.5