Go - Builder Pattern

Builder is a common pattern to create or initialize a particular object. It helps to break down individual steps of the creation by providing functions we can use to set different properties and then usually with a Build method, which uses these properties to create the object. Implementing Builder pattern Define a struct with all the properties of the object. package builder type User struct { UID string Name string Email string Password string } Create methods to set the properties of the object. // creates a new UID for the user func (u *User) createUid() *User { u.UID = generateUID() return u } // sets the name and email of the user func (u *User) setNameEmail(name, email string) *User { u.Name = name u.Email = email return u } // sets the password of the user func (u *User) setPassword(password string) *User { u.Password = hashPassword(password) return u } Create a Build method to create the object. // Build creates a new user func (u *User) Build() *User { return u } Example usage package main import ( "builder-pattern/builder" "fmt" ) func main() { user := &builder.User{} user.createUid().setNameEmail("Adharsh", "dev@adharsh.in").setPassword("password").Build() fmt.Println(user) } The key is to make the methods return the pointer to the object so that we can chain the methods together. This is a common pattern in Go and is used in many places. ...

Go - Concurrency Pipeline

Pipeline is yet another common pattern we see in concurrent programming. Stages for a data processing pipline can be for example, Read the file Process the data Transform the data Write the data to another file Let’s check an example of such a pipeline in Golang. package pipeline import ( "fmt" "time" ) type FileData struct { src string data string } // readData stage where we read the file // it returns a channel of FileData to use in the next stage func readData(filePaths []string) <-chan FileData { out := make(chan FileData) go func() { for _, path := range filePaths { time.Sleep(1 * time.Second) // Simulate file read out <- FileData{src: path, data: "data"} } close(out) }() return out } // processData stage where we process the data // it returns a channel of processed FileData to use in the next stage func processData(in <-chan FileData) <-chan FileData { out := make(chan FileData) go func() { for data := range in { time.Sleep(1 * time.Second) // Simulate data processing out <- FileData{src: data.src, data: data.data + " processed"} } close(out) }() return out } // transformData stage where we transform the data // it returns a channel of transformed FileData to use in the next stage func transformData(in <-chan FileData) <-chan FileData { out := make(chan FileData) go func() { for data := range in { time.Sleep(1 * time.Second) // Simulate data transformation out <- FileData{src: data.src, data: data.data + " transformed"} } close(out) }() return out } // writeData stage where we write the data to a file func writeData(in <-chan FileData) bool { for data := range in { time.Sleep(1 * time.Second) // Simulate file write fmt.Printf("Writing data to %s\n", data.src) } return true } // RunPipeline runs the pipeline // each stage is a go routine // and they are connected via channels func RunPipeline(filePaths []string) { readDataCh := readData(filePaths) processDataCh := processData(readDataCh) transformDataCh := transformData(processDataCh) writeData(transformDataCh) } In the above example, we have implemented a pipeline with 4 stages. Each stage is a go routine and they are connected via channels. ...

Go - Concurrency Workerpool

Golang has excellent support for concurrency. Let’s see how to implement a common pattern - worker pool in Golang. Worker pool A worker pool is a collection of threads that are waiting for tasks to be assigned. We can limit the number of concurrent operations at a time with this approach. Usually starting a new concurrent thread or routine is not practical for every task especially when the number of tasks is large. ...

gRPC - Overview

gRPC is a very useful tool to use as a medium for communication or data transfer between services. It has great support for multiple languages and platforms. What is RPC? Remote Procedure Call (RPC) is the concept of calling a function on a program from another program, these programs can be running on different machines. REST API is an example of RPC where a client service sends an http request to a server to invoke some logic and get the response. ...

Interfaces

Interfaces are one of my favorite concepts in programming. It’s a clean way to define contract and decouple the implementation parts from code. Interfaces indicate what a class or struct should do, or define the type of methods which a class or struct should implement. We can refer an interface and understand how the different parts used by a code block should behave. I mostly use it to define segments of code, like http handler, service, storage to indicate that a segment is going to recieve some implementation, which will have certain methods which can be used in them and worry about the implementation later. ...

HTMX - Navigation Methods

When working with web applications, it’s common to navigate between different pages. It’s one of the basic parts of a web application. While using HTMX, it offers a few ways to achieve navigation between pages. Let’s explore them. hx-push-url attribute ( client ) This attribute is used to push a new URL to the browser’s history. This will change the URL without reloading the page. <a hx-get="/about" hx-push-url="true">About</a> or <a hx-get="/about" hx-push-url="/about-page">About</a> Hx-Push-Url header ( server ) We can also use Hx-Push-Url header to push a new URL to the browser’s history. This will change the URL without reloading the page. ...

HTMX - Trigger events from Server.

When using HTMX is a common pattern to write event based actions or ui updates in the client side. It’s a good practice to use javascript as event based scripting system in our client side code. Some events from the server might be required in client side to update the DOM or to trigger some actions. A common pattern to achieve this is to respond a header Server-Event with a value holding the custom event and then using javascript, you can handle the custom event. ...

Kubernetes - Overview

Kubernetes is an open-source platform designed to automate deploying, scaling, and operating application containers. It’s a very powerful tool which allows us to declare how the infra should look like and the kubernetes will make sure that the infra is in the desired state. It has a large, rapidly growing ecosystem. Kubernetes services, support, and tools are widely available. How Kubernetes Works Kubernetes uses a declarative model, allowing users to specify their desired state for the deployments and services they run. The Kubernetes Control Plane takes these declarations and works to ensure that the current state matches the desired state. If a pod crashes, the controller notices the discrepancy and starts a new pod to maintain the desired state. This model enables scalability and reliability for containerized applications. ...

Python - Overview

Python is an interpreted, high-level, and general-purpose programming language known for its readability and concise syntax. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming. Python’s extensive standard library, dynamic typing, and dynamic binding options make it highly attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components. Few things I like about Python are Readability and Syntax: Python’s syntax is simple and clean. Extensive Standard Library: Python comes with a large standard library that includes modules for various tasks, such as connecting to web servers, reading JSON, and more. Few things I dislike about Python are ...

Kotlin - Overview

Kotlin is a modern, statically typed programming language that makes development faster and more enjoyable. It is widely used for Android app development, web development, and server-side development. Kotlin supports object-oriented and functional programming paradigms, making it versatile for various types of projects. It’s capability of DSL (Domain Specific Language) creation makes it more powerful. Few things I like about Kotlin are Extension functions and higher-order functions make the code more readable and maintainable. Kotlin’s null safety features reduce the risk of null pointer exceptions. Few things I dislike about Kotlin are ...