Skip to main content

Clean-Code

__str__ vs __repr__ in Python and When to Use Them

·3 mins
Introduction # In a previous post, we have done a comparison between __new__ and __init__. In this post, we are going to do something similar, but with a different pair. For those who don’t know, __str__() and __repr__() are two dunder methods which you can override in a class to change the way class is represented. These two little functions have been a source of confusion in my early career. Let us first go through them one by one and let us understand what they do first. Then we’ll do comparison among them with respect to their similarities and differences.

Optional Parameters Using Option Struct

·5 mins
Introduction # In last post we learned how we can use functional options to pass parameter to our functions. In this post we’ll see an alternative way to do the same thing. I’ll take the same code from the last post to keep things simple. Variadic Functions for Options # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 type Coffee struct { CoffeeBeans bool Sugar bool SteamedMilk bool } func New(opts ...func(Coffee) Coffee) Coffee { coffee := Coffee{CoffeeBeans: true} for _, opt := range opts { coffee = opt(coffee) } return coffee } // WithSugar adds sugar to the coffee. func WithSugar(coffee Coffee) Coffee { coffee.Sugar = true return coffee } // WithSteamedMilk adds steamed milk to the coffee. func WithSteamedMilk(coffee Coffee) Coffee { coffee.SteamedMilk = true return coffee } // Prepare makes a cup of coffee with given items. // Ignore the implementation for now. func (c Coffee) Prepare() string { v := reflect.ValueOf(c) typeOfC := v.Type() var items []string for i := 0; i < v.NumField(); i++ { if v.Field(i).Interface() == true { items = append(items, typeOfC.Field(i).Name) } } return fmt.Sprintf("Preparing coffee with %q:", items) } func main() { s := New(WithSugar) fmt.Println(s.Prepare()) } Here on line 1-5 we define type Coffee (or class if you would like to say). This is the analogy our code is build upon because I like coffee whenever I can.

Optional Parameters using Functional Options

·5 mins
Introduction # In Python you can assign default value to the functions, like so: 1 2 def my_func(posarg, named_arg=True, another_named_arg="Okay") # logic goes here... But in Go you can’t do this: 1 2 3 func myFunc(posarg, named_arg bool = true, another_named_arg string = "Okay") { // logic goes here... } This will throw a syntax error. Try that? In this post, we’ll see how can we overcome this issue the go way, with something called Function Options. Not sure if go is the only language that uses this syntax, if there is another language you are using, please let me know. Also, connect with me on LinkedIn