Hey All,

Per popular request, below is chapter 1 of my new book, Quality Code with Go for free. Enjoy!

With all books on a programming language, comes a new crowd of developers excited to jump in and learn about it. The problem is, it's difficult to know where to start. Any book that you purchase will have a title, but if that title doesn't say Getting Started or Beginner, it's hard to know if that book is a good place to begin the journey.

This book isn't exactly a Getting Started book, meaning, I assume that you have prior Go knowledge. However, if you need a brief introduction to how Go works or a refresher, this chapter will help.

It certainly won't go into all of the beginner-level topics, but it'll give an overview and allow you to take what you've learned to do some more digging.

Remember, there is no such thing as easy, there's just simple. Everything is hard when you first start it, but don't get discouraged. Anyone can learn Go with drive and passion.

The source code for this book is available on GitHub: https://github.com/AdminTurnedDevOps/Quality-Code-With-Go

Procedural vs Functional vs Object Oriented

How you write code and how you analyze said code will differ depending on what language you use and how the code needs to be structured.

Maybe you need an object to call or a class that needs to be initiated and used in another piece of code. Maybe you simply need an algorithm that carries out a specific set of steps or computational steps. Maybe you simply need a few functions to carry out some steps.

What all of that encompasses is the programming paradigm that you're going to be using.

The three typical programming paradigms you'll see are object-oriented programming (OOP), Procedural based programming, and functional based programming.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/89cefaf2-cd23-4099-99a0-aa9d42c8c627/Untitled.png

Object-Oriented

When you write object-oriented programming, you're defining your code as objects, AKA, classes and methods.

Let's take a brief example of Python Object-Oriented code.

Below, there is a class called Cars. Within the Cars class, there are three objects that can be initiated:

  • The make of the car (Make)
  • The model of the car (Model)
  • The year of the car (Year)

This means that the class can return the three objects and you can use the three objects to input data.

class Cars:
    def __init__(self, Make, Model, Year):
        self.Make = Make
        self.Model = Model
        self.Year = Year

After you've defined the class, you can start initiating objects with values. For example, A 2020 Ford F150.

myCar = Cars("Ford", "F150", "2020")

After you've initiated the objects, you can print out the objects. If you use the print method on myCar.Make, Ford will be printed to the screen.

print(myCar.Make)

The idea is, you can take an object and use it in an application to create values for specific needs. For example, creating the objects of a Ford F150.

Procedural

Procedural programming defines a list of steps that a program must take to reach the desired end goal, or state. Go, by nature, is a procedural-based programming language.

Essentially, you have multiple algorithms that execute as a step-by-step. A sequential series of execution steps, if you will. You don't organize code in objects or classes.

As an example for procedural programming, we'll use Go.

First, you would start off with a main function. In many cases, the main function is used to call the sub functions, AKA, what steps you want to take and in what order.

package main

func main() {
	step1()
	step2()
	step3()
}

The functions that are defined are in a step-by-step nature, so one after another.

package main

func main() {
	step1()
	step2()
	step3()
}

func step1() {

}

func step2() {

}

func step3() {
	
}

Functional

Functional programming (FP) treats code like a mathematical evaluation, AKA, functions that avoid a specific state and mutable data.

In functional programming, you define code in 100% functions with clearly defined tasks. This is where functional sort of overlaps with procedural. With a language like Go, you're writing pure functions that have detailed instruction, like functional based programing. The key difference is because it's procedural, you're calling Go functions in a specific order.

Go is very much a multi-paradigm language. It's procedural by definition, but has a ton of functional principles in it.

func add (x int) func(y int) int {
	return func(y int) int {
		fmt.Println("Hurray, I'm doing functional programming!")
		return x + y
	}
}

Functions

Functions are the same in most languages (sometimes they're called methods). The idea of a function is to have a step-by-step process that the code is supposed to follow to perform an action. It also gives you the ability to put functionality in one place. For example, let's say you need an app or a script that authenticates to Azure. Having an AzureAuth() function would be great for that. The code is all in one place and you can use the function later on in the code you write.

Declaring a function in Go looks something like this:

func AzureAuth() {
	
}

First, you start off with the func identifier, which tells Go that you're planning on writing a function.

Next, you have the name of the function with parenthesis right after it. The parenthesis are for specifying parameters if you have any. Even if you don't have any parameters, you still need to add in the parenthesis.

Finally, you have brackets. Inside of the brackets is where you put the functions code.

Notice how the first bracket is on the line where the func is defined. If you try to put it on the next line, for example, the same thing you can do in C#, the compiler will yell at you and let you know that the function body is missing.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/2cd16b22-efd9-4e47-8129-2ca0712e9ea6/Untitled.png

Packages

When it comes to packages in Go, they're no different than modules or libraries in other languages. Packages are a way you can interact with other platforms and resources, like making calls via HTTP or interacting with Azure and AWS.

A package typically consists of some sort of Software Development Kit (SDK). A package can also contain things like help data, documentation, templates, and anything else that an author of a package things would be relevant to whoever is using it.

Standard Packages

Go has a ton of built-in packages in the language, for example the fmt package which allows you to do things like print output to a command line.

package main

import (
	"fmt"
)

func main() {
	fmt.Println("Hello Readers!")
}

There are a ton of helpful packages that fall into many categories, including:

  • Interacting with HTTP and making API calls
  • Error handling
  • Archiving
  • Zipping
  • Encryption
  • So much more

I encourage you to take a look at the standard package librray. Don't feel like you have to memorize all of these or even use all of them. I maybe use 5% of it.

https://golang.org/pkg/

Third-Party Packages

When you want to use a specific SDK from Azure or AWS, or even a cool open source package that you found on GitHub, that's called a third-party package. A third party package isn't embedded into Go like standard packages, so you need a way to retrieve that package.

That's where the go get command comes into play. go get can download a third-party package for you.

For example, at a command line you can use go get to install the Azure SDK.

go get github.com/Azure/azure-sdk-for-go

Once you install the Azure SDK, you then have access to all of the types and functions for the code you're writing.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/120c473a-2c0e-4834-86e4-78cc1d83b6b0/Untitled.png

Importing Packages

When you import a package, it means you need some functionality from that package. For example, the fmt package allows you to print to the console with the Println() function. To use the Println() function, you need to ensure you import the fmt package.

There are three primary ways to import a package.

Automation Imports

One of the really cool things about Go is that if you try to use a package, say the fmt package but you don't have it imported, once you specify the fmt package inside of the Go code, the package will get automatically imported.

For example, let's say you type the following in a main.go file:

fmt.Println("Hello, readers!")

Once you save, the package will be automatically imported. into the main.go file.

import (
	"fmt"
)

fmt.Println("Hello, readers!")

Line by Line

Although I think that this is the messiest way, it's still a way, so I want to bring it up.

You can add in multiple import statements for each package you want to use, for example:

import "fmt"
import "os"

As you can imagine, if you're using ten packages, the code can start to look messy and isn't the best in terms of quality. Just because it works, doesn't mean it should be done.

Import Statement

The best way to import packages is with an import statement. An import statement can hold as many packages as you need inside of the Go file.

For example, you can see below that the fmt and os package are imported under the same import statement.

import (
	"fmt"
	"os"
)

As you ca see, it's the cleanest approach by far. It allows you to import package all under one place and shows you can easy way to specify what packages are available.

Variables

A variable, by definition, is the same as any other programming language. It simply holds a value. You define a key, AKA, the name of the variable. Then you define a value that the key will hold. Once you have that value, you can see the variable in code. That way, you don't have to worry about hard-coding values in code as that's never a good practice. From a quality code perspective, unless it's absolutely, 150% known that the value will never need to change, you always want to ensure the code you write is reusable. Typically, with hard-coded values, the code automatically becomes reusable. That's one of the reasons coders use variables.

One thing with Go is that there is a few different ways to declare variables. In this section, you'll take a look at four key ways to specify variables in Go.

Declaring a Single Variable Without a Default Value

The first way to declare a variable (and first does not mean best), is by declaring a variable without a default value.

You first start off with the var keyword. After you specify the var keyword, you name the variable. Once you name the variable, you specify what type the variable is (more on Go types in the upcoming section Strongly Typed). An example below shows the variable carType

var carType string

You can then define the value of carType later in the code.

Declaring a Single Variable With a Default Value

Just like the carType example above, you can also define a default value for the variable.

var carType string = "Ford"

Multiple Variable Decleration

Another really cool thing you can do with variables is specify multiple key/names and values. For example, let's say you wanted to take the carType variable and add in a carYear variable as well with default values.

var carType, carYear string = "Ford", "2020"

You simply separate the variable values my commas.

The one thing to point out that's most important is the types must be the same. For example, you can't mix a string and an int when you're using Multiple Variable Decleration.

Shorthand Variable Decleration

Probably the most popular way to define a variable in Go is by using shorthand. Let's take the carType example again.

carType := "Ford"

Notice the colon (:) in the code? That's the key difference for the short hand.

Which One Should You Use?

With all options comes one simple question - which one is best? The answer is, from a code quality perspective, you should use the type of variable that you can define a type. The reason why is because Go is a statically typed language. It's specifically there to help you define types so you know what the code is supposed to be doing.

For example, let's say you have a variable that's supposed to be a string, but you use an int. The compiler may not complain, but if the application is expecting a string, you aren't going to have a fun deployment process.

When it comes to code quality, the idea is to use the tools that the language gives you to provide quality.

Strongly Typed

As we saw in the previous section, Variables, Go is a strongly typed language. That means, variables and parameters are bound to a specific type (string, int, etc.). We saw the examples in the Variables section, but you may be wondering Why is Go statically typed?

The idea behind statically typed languages are, you know what the code is supposed to be doing. If the variable or parameter is supposed to be a string, it's going to be a string and you must define that. Having code that isn't statically typed is a breeding ground for bugs. Let's take an example.

package main

import (
	"fmt"
)

func test() {
	var carType string = "Ford"
	var owned int = 1
	
	fmt.Println(carType + owned)
}

As you can see above, the code is trying to add a string and an int together, which won't work in statically typed language. The reason why is because they're different types and you can't put them together. Before even running the code, the compiler will yell at you at build time and give you a mistmatch error. The mismatch is string and int

In a language that's dynamically typed, say PHP, the algorithm above would work until you run the code. The compiler will be fine with it and let you build the code.

Statically typed languages allow you to catch a bug like in the code above before you even try running the code. At build time, the compiler will let you know the code is invalid. When it comes to code quality, a statically typed language is great.

Running Go Code

Up until this point, you've seen and written a lot of Go code. You saw how functions and variables work. You saw how different types and values work. However, you haven't ran any code.

In this section, you'll learn how to run Go code from the command line.

To run Go code, you'll use the Go command-line. If you don't already have Go installed, you'll need to do that first.

To install Go on Windows, you can use the .EXE installer.

To install Go on MacOS, you can use the .PKG installer.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/170046b3-b44a-4045-8811-b60e187206fa/Untitled.png

Run Go Code

Running Go code is the same across any operating system. First, you'll specify the go run command. The go run command runs the .go file. After you specify go run, you specify the Go file name. For example:

go run main.go

To run a Go file named, for example, main.go, make sure that you're in the directory where the main.go file exists, or specify the fully qualified path at runtime.

go run /path/to/gofile/main.go