Where to Put Our Trust

I love Nephi. Especially his powerful words of reflection and prayer in 2 Nephi chapter 4. Here's just one gem for a thought today.

"O Lord, I have trusted in thee, and I will trust in thee forever. I will not put my trust in the arm of flesh; for I know that cursed is he that putteth his trust in the arm of flesh. Yea, cursed is he that putteth his trust in man or maketh flesh his arm." (verse 34)

I am reminded that we, as a people, altogether too often put our trust in men. They have names like Trump, Biden, Romney, Monsen, Nelson, and many others. This is not to say there is nothing good in these men. Indeed there may be much to be admired, but our trust, our faith, these we should reserve for the Lord, and Him alone. 

How are we cursed if we put our trust in man? Other words for cursed may be damned or doomed. I have wondered at these words. I have observed the pains we suffer when men we trusted have failed us. If we believe that a mere mortal is beyond the reach of weakness, failure, and sin, we will nearly always be disappointed. More dangerously, if we allow such trust to replace or stand in for our faith in God, then surely we walk on the razor's edge of doom.

It is upon that edge of doom that our own faith may be shattered when the men we trusted turn out to be just that, mere mortal men, subject to the buffetings of Satan, able to make mistakes, and equally in need of mercy as we are every day.

Let us harken to the words of Nephi and escape the fate of such a curse.

We Are Mortal - Weak and Imperfect

I believe it's healthy to realize that all people make mistakes and have weaknesses and fall far short of perfection. This includes all who serve in Church leadership.

It's equally unhealthy to assume that Church leaders are infallible or beyond reproach. There has been far too much of that and it has damaged many lives. We must stop doing that.

As long as it's run by mortal men, the Church will make mistakes and eventual corrections. For decades many tried to convince us otherwise. It often resulted in testimonies, based on false assumptions, too easily assailed.

Only the Lord is perfect. Thankfully He has an amazing capacity for patience as He works with weak men to bring about His purposes on earth.

I fully sustain Church leaders but have never believed they are more than men and women who struggle every day, just like the rest of us, to serve God in the best way they know how.

We Are Not Gods

There is a risk that we, as technologists, may become drunken with the power that knowledge gives us over the non-technical folk. They look to us for answers because we have the Dilbert Knack, and they trust us to really know.

Capricorn

And just when we fall through the rabbit hole of illusion that such power creates, when we have decided that we are gods, knowing and seeing all, those pesky humans, mere mortals they, go off and make a business-driven decision that runs contrary to every tenet of elegant design and best practices that we have graciously delivered to them at great sacrifice to ourselves on digital tablets for their own good because they cannot possibly know what is good for themselves.

Our ego blinds us to the truth. We are not gods. And when the business people reject our ideas, only humility will prevent us from making complete fools of ourselves. 

Indeed, we can only be truly effective when we come to understand that we serve at the pleasure of our employer, and we want to serve their interests but understand our place as a servant. We can gently persuade. We can teach. And we can be there when things go south, having the wisdom to never say, "See. I told you so."

Keith D. Jensen - A Son's Tribute

(Thoughts I shared at my dad's given funeral today.)

The greatest compliment I ever received was, “You look just like your dad.” And the greatest compliment of my dad that I’ve ever heard, I heard last night at the viewing from Jim Young when he said, “Keith was my best friend.” I think there are a number of people who would say the same.

I want to begin with the most important thing about Dad. It’s what makes him my hero. It’s what makes me want to be more like him in my life.

Dad was born the youngest boy of 8 children. He has one younger sister. His father suffered from allergies, so dad did all the farm work as a teenager. His father also struggled with alcoholism and was not often a kind or tender man. Dad’s parents were divorced because of this after all the kids had left home. 

We all know that the cycle of abuse often goes from generation to generation. But Dad broke that cycle. Neighbors would take him to church where he learned to love the Lord and formed a desire to serve Him all his life. 

Dad’s testimony of Jesus Christ and the Atonement is deep and profound. He worked all his life to emulate the Savior, loving everyone and taking every opportunity to serve them. He was kind, gentle and patient with his family and neighbors. They saw in him a spiritual power that exceeded his tremendous physical strength.

I never saw him raise his voice or a hand to anyone. He was never vengeful, nor did he demand payment for hay that others had taken on credit. As a child, I could not understand that. Eventually I came to understand it. Truly he lived the phrase, “forgive us our debts as we forgive our debtors.”

Dad taught me many things that have served me well in my life. 

He taught me to be inventive. Our first bale wagon had two rod levers to control hydraulic operations. The furrows in the fields often tipped bales flat, so they needed to be turned up on their edge before the bale wagon could pick them up.

I would ride on the tractor wheel fender and jump off to run ahead and turn the flat bales. That was not particularly safe or efficient, so Dad got inventive. He selected an old steel seat, probably from a horse drawn hay rake—you never knew when something like that was going to come in handy, he’d say.

With the seat welded to the side of the bale loader, we went back to work. I would sit there and jump off and run ahead to turn the flat bales and wait for the seat to catch up to me. The only trouble was that the bale loader needed to be raised just an inch or two at the end of the field to turn around without gouging the hay with the skid. 

Dad would pull on the lever that operated the chain on the bale loader a little further and raise it up just a little with me riding on that seat. On one of those turns, the lever got stuck. The bale loader launched me up and over to the other side of the wagon. Dad stopped hauling and we went straight to the shop where he promptly cut off the seat.

And that is how we got our first motorcycle. Todd and I would take turns riding that Kawasaki up and down the furrow rutted hay fields turning the fallen bales up on their side. It was great fun.

Dad taught me to embrace change. He installed pressurized irrigation and bought wheel lines and hand lines. He improved and upgraded his equipment lineup from time to time. He reclaimed ground that had been overwhelmed with salt grass and alkali. We chained two tractors together to plow that sod. He loved John Deere but wasn’t afraid to use something else when it made sense—which was not that often. Just get the job done. That was the important thing.

Dad taught me to read scripture. He would often gather the family at 6 a.m. to read the Book of Mormon. Each member of the family took turns reading. Dad would correct our pronunciation and prompt us if we got stuck. Whenever I hear someone struggle with reading scripture, I remember Dad’s love for scripture. They were sacred and we ought to read them properly.

Dad taught me to work. Once or twice, up and down the field, and he’d put me in the driver’s seat. Another round while he watched and corrected me when I messed up. Then he would go work on something else until I was done, broke down, or hungry. Later in my teen years, sometimes a friend would ride along with me as I worked. They were always amazed that I was able to operate machinery. I took great pride in that as a kid. Thanks, Dad.

Dad taught us to love the Lord. He would bear his testimony to us. He would have us all kneel in family prayer. He never shirked his duties in the Church. He read his scriptures nearly every day. He sat us down to watch General Conference every six months. He gave wise counsel and never had an unkind word for anyone.

Dad taught me to serve others. When it would snow heavily, he would send me with the old John Deere 3020 and blade to LaMar Sherman’s place to plow the snow all the way up the hill to his house. Doing that small act of kindness always made me feel warmer inside.

Dad taught me to solve problems with what I had. There was not always time to go to town to get a new part, so he would weld a fix and we would get back to work. I became an expert welders helper and I learned the fine art of holding a flashlight to help him work in the dark to get a machine fixed and running again. And that is a rare skill. 

Dad taught me that you go to the house and eat dinner ONLY when the work is done. And perhaps that was the most important lesson.

I testify that God lives and loves us. I know that Jesus is the Christ and that He suffered and died for our sins that we might be made pure and worthy to live with Him and the Father forever. All we need to do is have faith in Him, keep His commandments, make and keep covenants, and most importantly endure to the end. 

That’s what he taught me. And Dad did all of that. He loved his sons for the work they did on the farm, but he might have appreciated the hard work that my sisters did even more. He told Mom that the boys worked hard in the fields until they got hungry and then they’d come looking for something to eat. But the girls would stay out on the tractor all day until the job was done.

Even when Alzheimer’s was robbing him of his memories, he would put on his coat, hat and gloves and go feed the cows and horses twice a day, every day. After years of doing that, he had worn a deep trail from the house to the corrals under the red rock bench in Ioka.

Last summer when Mom wasn’t able to care for Dad, he spent the very last of his energies in mortality lifting the spirits of his new neighbors at the care center. He would go from room to room, shake everyone’s hand and tell them how glad he was to see them. He did not need to remember them. He knew they were his brothers and sisters.

Yes, Dad taught us all to stay until the job is done. He taught us to endure to the end. This lesson defines his life. He learned it at an early age and continued doing it until the very end. 

Perhaps his headstone could read, “He stayed until the job was done.”

Keith D. Jensen - A Life Sketch

(I wrote this life sketch of of my dad to be read by my sisters at the funeral today:)

Keith Devon Jensen was born June 4th, 1940, in Huntington, Utah. He was the youngest boy of 8 children. His parents were John Alferd Jensen and Ila Woolman. Until he was 9 years old, he spent summers at his father’s sawmill in Huntington Canyon. He played in the big piles of sawdust and loved the old steam engine whistle.

His parents sent him to Primary and Sunday School. Valiant leaders and neighbors helped Keith learn to love the Lord and to serve Him. His patriarchal blessing promised he would serve a mission, so he was disappointed that he could not afford to go. Much later in life he served joyfully as a ward and stake missionary, going with the full time missionaries to teach and serve many members of his community. 

Keith learned to work hard as young man. Fun and games were for other kids. There was always a cow to milk or farm work to do. His father had terrible allergies, so Keith did all of the farm work as a teenager. That work ethic showed in everything he did in his life.

In high school, Keith joined the pep club to be closer to LaRue McElprang, a cute sophomore in the band. Soon they began dating and became sweethearts. While LaRue finished high school, Keith sold his horse in order to attend college in Price. He studied auto mechanics.

Keith would catch a ride from Huntington to Price with his sister-in-law on her way to work in the morning and hitchhike back home in the afternoon to see LaRue. Date money came from a tool pusher job at the college.  

LaRue graduated from high school in 1960 and by December of that year Keith gathered enough courage to ask LaRue’s dad for permission to marry her. To his delight, Milton McElprang agreed and on Christmas eve that year, Keith proposed to LaRue. They were married on July 28, 1961, in the Manti Temple.

They moved to Salt Lake City and lived in the old Liberty Park ward. Todd was born a year and a day later and Tyler arrived about three years after that.

Keith worked as a mechanic for about a year then went to work for Linford Brothers Glass. It wasn’t long before he became a journeyman glazer. He installed windows in the old Deseret Gym where he fell from a scaffold and broke his pelvis. Healing was slow but he was back at work some weeks later. As the new guy, it fell to Keith to install windows in the research facility at Fish Springs National Wildlife Refuge south of south of Dugway Proving Grounds. On the long dirt road home in the dark, he fell asleep and drove of the road into the desert. When he woke up there was no road and no way to see where it was, so he turned the wheel in the direction he thought he should go until he found the road again, guessing which way was home. He guessed right.

In addition to working as a glazer, Keith and LaRue worked to manage several rental homes owned by LaRue’s father. They loved their friends but longed for a simpler life away from the city. LaRue’s father bought ground in Cedar View and Hancock Cove. Keith and LaRue moved to the Cove in 1966 into a little red brick house. A few years later, Keith and LaRue bought the farm from her father and continued to help manage the herds on the pastures in Cedar View.

Keith farmed and started a dairy which ended in devastation when the herd got out into a fresh alfalfa field and most of the cows died from bloat. It was a monumental struggle, but Keith and LaRue carried on and kept the farm. 

Keith gained a reputation among his neighbors as a friend to all with a kind smile, warm handshake, and generosity with his time. He often traded labor with fellow farmers, each helping to harvest silage. He was known to sell hay to many on credit when he knew they would never be able to pay him, and he never worried about getting paid.

Four daughters followed and then a son from 1967 to 1980, Ruth Ann, Melissa, Rebecca, Maria, and David. A few years later Leonardo was adopted from Colombia. A perfect crew for farming and moving handlines. All the children learned to work hard on the farm, acquiring skills and learning a work ethic that have served them all well throughout their lives.

Keith often leased additional farm ground. He was particular about producing good alfalfa hay. He would often rise at 2 or 3 o’clock in the morning to go bale hay with the perfect dew on. On one morning, he drove through town to one of those farms just a little too fast. Two young Roosevelt City police officers pulled him over. He didn’t have his seat belt on, so he jumped out of the old Bronco and walked back to the police car.

“Does your mama know where you boys are at this time of night?” he asked.

They told him how fast he was going.

“Oh, that old thing. It can’t even go that fast,” he said.

They asked where he was going in such a hurry.

“I’m going to bale hay. Why? Do you want to come help?” he asked.

No. They did not want to help and waived him on his way.

The farm in Hancock Cove eventually became Sterling Meadows. Other farm ground was acquired and leased. Keith continued to work the farm while LaRue worked at the hospital in Roosevelt. In the mid ‘90s, they moved the family to Ioka where LaRue still lives.

Keith was a faithful member of the Church of Jesus Christ of Latter-day Saints, serving over the years as Sunday School president, Elders Quorum president, High Councilor, Bishop, Young Men’s president, and dedicated ward and stake missionary and home teacher. He loved the people he served and did so because of his firm faith in the Lord Jesus Christ. His dedicated service to others led many in our community to renewed faith and activity in the gospel of Jesus Christ. 

Keith and LaRue’s children have blessed them with 35 amazing grandchildren with 8 spirited great-grandchildren. Two more are on their way. They have all learned to love Grandma and Grandpa spanning many years, each with precious memories of days on the farm. Jaelise, one of the oldest grandchildren (my oldest), put it this way:

“Cowboy shirts. Mint gum. Baling twine. Puttin' around. Rodeo broadcasts. Always teasin'. Four-wheeler rides. Sandwich cookies. Silly faces. Farmers hands. Warm hugs. Sly grins. Morning chores. Biggest heart. Best gramps of a lifetime.

“I wish grandpas never died...”

Keith and LaRue also invited into their home four Navajo foster children, John Thomas, Dorothy Smith-Bain, Ruby Thomas Dickson, and Gilbert James. John has passed on. Mom and the older kids who knew them still stay in touch with the girls. Ruby and Dorothy still call them Mom and Dad. In all they spent a total of 6 years in Keith and LaRue’s home. John spent many additional summers working for Dad on the farm.

Some years ago Mom knew that Dad was losing his ability to remember. Eventually he agreed and was diagnosed with Alzheimer’s disease. One of the hardest days in his life was watching his farm equipment being auctioned off after accepting that he would no longer be able to work the farm. He kept a bright smile and appreciated all who came to help.

He continued to do the chores every morning and every night, putting on his coat, hat and gloves, and walking the well worn path to the corrals until finally he could not even remember how to do that. He retained his personality and love of others until the very last.

Mom cared for Dad until she was physically unable to adequately care for his needs. Her hardest day was leaving him at the care center in Vernal last summer. She visited him several times each week. 

The caregivers at the nursing home called Mom not many days after he was admitted. They asked if Keith had been a bishop. Yes, Mom said, and asked why. They told her that he spent his day going from room to room, shaking hands and telling residents he was glad to see them and cheering them up. The nursing staff said he changed the whole unit because of this.

His memory may have failed him but his heart never did.

Debug Go in Windows Subsystem for Linux 2

I’m starting a new job in two days writing Go for Linux, so I thought I ought to do a little experimentation with debugging Go in VS Code on Windows Subsystem for Linux. I already had WSL enabled but had not used it much. After a little experimentation on my laptop, I discovered that debugging does not work in WSL (v1) but it does in WSL 2.

After a little experimenting, I got it working on my laptop and determined to do the process again while taking some notes on my desktop machine. This is as much to remind myself as to inform others. If you find it useful, so much the better.

Existing Start Point

I started with a current version of Windows 10 Pro with WSL enabled and Ubuntu installed from the Windows Store. I also had Go installed in Windows but not in WSL. This gives you WSL 1 and the Go Delve debugger will not run remotely via VS Code on WSL 1.

Windows Insider Program

You need a newer version of Windows 10 that comes with WSL 2. For that, you need to join the Windows Insider Program.  Once you do that, you can use Windows Update to install the latest version of the OS, currently build 19041.1.

Enable WSL 2

Now you need to open PowerShell in Administrator mode and follow the instructions here.

You run these two commands to enable WSL 2:

dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart

Now if you run

wsl --list 

You should see something like this:

PS > wsl --list
Windows Subsystem for Linux Distributions:
Ubuntu (Default)

Now you need to convert to use WSL 2 rather than 1 which is the default by running the following with the output shown:

wsl --set-version Ubuntu 2

wsl --set-default-version 2

wsl --list --verbose

PS C:\WINDOWS\system32> wsl --list --verbose
  NAME      STATE           VERSION
* Ubuntu    Stopped         2

Windows Terminal

This step is optional but I recommend it. Go to the Windows Store and install the Windows Terminal. It makes switching between WSL bash and PowerShell and Windows cmd prompt very easy. You can learn more about it here.

Update Your Ubuntu WSL 2 Environment

Now open the Ubuntu bash shell and run the following commands to update, upgrade and install golang.

$ sudo apt-get update
$ sudo apt-get upgrade
$ sudo apt-get install golang-go

Once you have updated and upgraded and installed Go, you can run go version and get go1.10.4, the current Ubuntu default which is not the version you need. This version will not run with the new version of the Delve debugger that the VS Code extension uses. But not worry, upgrading to a new Go is easy.

The above install will put the 1.10.4 version in the /usr/lib/go directory. Do a more VERSION in that directory and you’ll see that I’m right.

Upgrade Go to Latest

Now you need to download and install the latest Go version, currently 1.13.5. Execute the following commands:

wget https://dl.google.com/go/go1.13.5.linux-amd64.tar.gz

sudo tar -xvf go1.13.5.linux-amd64.tar.gz

sudo mv go /usr/local

This will put the new version of Go in a different directory allowing you to revert to the previous installed version if you want. After the files are in place, you need only update your environment Go paths. Open the ~/.bashrc file in your favorite editor. For quick stuff like this I use nano. Now add the following lines at the end of the file:

export GOROOT=/usr/local/go
export GOPATH=$HOME/go
export PATH=$GOPATH/bin:$GOROOT/bin:$PATH

Either close your bash shell and open a new one to get the udpated settings or execute source ~/.bashrc to update the current session. Then execute go version and you should see go version go1.13.5 linux/amd64.

VS Code from WSL

Open VS Code from Bash Shell with:

code .

VS Code will open after the shell installs VS Code Server for x64. If you have the Go extension installed already, all you need to do is install it to WSL. Just open the extensions and click on the install button.

InstallGoWSL

A reload of VS Code will be required. In fact, I found that a reload was required or at least needed to get some of the following steps to work properly but that was a minor inconvenience.

Create a new directory called gotest and a file in it called app.go using VS Code. Paste in the code from https://github.com/tylerjensen/d-go-rust/blob/master/Go/Hello/app.go and hit F5 to debug after adding a break point. VS Code will require that you install go-outline and the delve debugger, so just click Install on the pop up notifications.

Now you’re up and running, building and debugging Go in Linux in WSL 2.

Random Thoughts on Programming Languages

I noted with interest that Microsoft is delving into Rust for some things in the OS where they have memory related security holes. 

We seem to need a language for each of the following:

  • OS
  • Desktop GUI
  • Web front end
  • Web back end
  • Services (web backend without a front end)
  • Data querying 
  • Systems (data serving, near the metal)
  • CLI utils to listen to the GUI or the anti-GUI user or the scripters
  • Script for the scripters

C and C++ remain relevant for the OS but Rust seems to be scratching at the surface.

Javascript rules the browser (written in C++) but WebAssemby (also written in C++) is scratching at the door and will bring many languages to play there once WA has cut ties with JS interop dependency for DOM and HTTP coms.

The web backend and services is a mess of nearly every language on the planet. From JS to Ruby (wretch). Even here JS dominates with Node. The rest of the field is up for grabs.

Data querying is still SQL followed my a mishmash of things for querying noSQL datastores, usually some form of JSON over REST, though binary serialization in gRPC is growing for both data and services.

Systems are still primarily C and C++ but Java and C# play some Part in some database platforms. Go, Rust and others are also knocking on the door. Kubernetes is a good Go example, a tech that is red hot right now.

The CLI world is a free for all. Python is fast becoming a favorite for the automation and ML scripters. This category does seem to favor interpreted over compiled but even that is a pile of chaos and debate.

One thing is certain. There is only one master language in all of computing. Heaven help us. It's English. And there is no consistent compiler, interpreter or IDE for the foul thing.

OOP in D, Go and Rust

Caveat Emptor: I am no expert in any of these languages. DO NOT read this post and assume any such thing.

Picking up where I left off with Hello World in D, Go and Rust in VS Code, this post restarts the thread of my personal learning and exploration of these three programming languages:

Of these three, only D is really an OOP language, but I wanted to see how close I could get in Go and Rust. I started with D and then morphed and adapted as I moved to Go and finally to Rust. The code in this experiment is overly simplistic and meant only to explore basic OOP principles. Nothing in this code is meant to demonstrate best practices in any of these languages.

Update All

First things first. Like my blog, the system on which I wrote the previously noted post has been neglected these past few months. I updated VS Code from June 2019 v1.26.1 to October 2019 v1.40.2. I had Auto Update enabled, so my extensions were updated as well: DLang to v 1.16.7, Go to 0.11.9, and Rust (rls) to 0.7.0.

Next I updated my language environments by downloading and installing the latest releases for Windows:

*dirty: Yeah, I wondered about that too. Apparently it is an artifact of their build system after moving to GitHub. Nothing to worry about. Probably.

The D installer did ask for some VC runtime redistributables or and install of Visual Studio. I already had Visual Studio 2019 installed but would later remember that it had been uninstalled and I had not installed the VC++ dev options. This left no VC redistributables on my machine apparently, as I would soon learn when trying to use the Rust compiler.

dlangvcmingw

Validate Prior Code

The D and Go compilers worked with the prior post’s Hello World code just fine. The Rust compiler complained like this:

PS D:\langc\rust\Hello> rustc app.rs
error: linker `link.exe` not found
   | = note: The system cannot find the file specified. (os error 2) note: the msvc targets depend on the msvc linker but `link.exe` was not found note: please ensure that VS 2013, VS 2015, VS 2017 or VS 2019 was installed with the Visual C++ option error: aborting due to previous error

This was easily resolved by closing VS Code, opening Visual Studio Installer, and adding Desktop development with C++ in Workloads. Opened VS Code again and ran rustc app.rs and the problem was solved.

The app.exe grew by a few bytes for D and Rust but shrunk just a little for Go. I’m not certain why but I thought that was interesting.

Code in GitHub

Rather than listing out all the code in this post, I put the old Hello World code and the new code for this post into https://github.com/tylerjensen/d-go-rust which should make it easier for you to see the effort as a whole. There is nothing special about this repo. It’s just a learning playground and definitely does not purport to be a demonstration of proper practices in any language, let alone best. So reader beware!

Object Oriented Programming

There is no shortage of opinions available on the web as to what constitutes “Object Oriented Programming” but there are certainly some comment themes. Here are the few principles that I selected to use in my attempt to build and compare some OOP code in D, Go and Rust. This is not a comprehensive list and definitely not an attempt to authoritatively define OOP.

  • Objects / Classes — data structures and methods (or functions)
  • Encapsulation — data and logic protection (private vs. public)
  • Composition — support for “has a” relationships
  • Inheritance — support for “is a” relationships
  • Polymorphism — an object that “is a” thing can be used as a thing
  • Open Recursion — a thing can call itself and access its data (this or self)

There may be many other elements of OOP and some of them may be important to you, but for now, let’s see if we can limit it to the scope defined in the bullets above, at least for this foray into learning three new languages.

General Approach

To keep things simple, I’m limiting each effort to one or just a few files. Implementation of methods/functions are simplistic console outputs. Only one complexity was added because I wanted to see how each language deals with date and time. As simple as date/time may seem to humans, it’s another thing entirely to a computer and each language has its own way of dealing with the variety of RFC standards for date/time data.

Another effort I’ve made to keep this simple is that each example is built as a simple console application. No libraries built. No HTTP listener. No windows. No command line arguments. No real architectural organization or realistic naming or code documentation. This is an effort to learn the basics of the languages rather than their best practices. I’ll leave that to the experts in each language.

I’ve tried to write the same code in each language. Mostly. There are differences, especially with the Rust code. The Rust compiler is rather opinionated and to eliminate warnings, I’ve complied with its suggestions.

Here’s the list items I’ve tried to create in each code base:

  • Interface Printable with Print method
  • Abstract class Person that implements Printable interface
  • Demographics class that has a DOB date and encapsulates age behind a GetAge method
  • An Employee class that inherits from Person and composes a Demographics instance
  • An overridden Print method in the Employee class
  • Overloaded methods that take a Person, Employee and Printable as an argument to examine polymorphism

OOP in D

I chose to start in D because it really is an OOP language where Go and Rust, technically speaking, are not. This would give me a simpler entry point into building some code that looks like the kind of OOP that I’m used to seeing in C#. This would allow me to cover most of the elements of OOP that I wanted to explore.

The D code is split into three files, each defining a “module” because within a given module, all private and public class members are accessible to all others. This means that to ensure encapsulation, you have to use separate modules which are defined by the module keyword and follow the convention that the module name is the same as the file name.

I’m not going to show all the code here, but here’s the “per” module which has the interface, abstract class, and the composable class defined. It’s not all that different from my C-based languages including my favorite C#.

module per;

import std.stdio;
import std.datetime;

public interface Printable 
{
  void Print();
} 

public abstract class Person : Printable
{
  public void Print() 
  { 
    writeln("Person printed.");
  }
  public string Name;
}

public class Demographics
{
  private int age;
  public Date DateOfBirth;

  this(Date dob)
  {
    DateOfBirth = dob;
  }

  public int GetAge()
  {
    SysTime today = Clock.currTime;
    
    // Example of open recursion - 'this'
    this.age = today.year - DateOfBirth.year;
    
    return age;
  }
}

The rest of the code can be found here: https://github.com/tylerjensen/d-go-rust/tree/master/D/oop

It’s rather self explanatory for anyone familiar with C-based languages. I won’t spend much time explaining the code. My lazy approach to looking at overloading and polymorphism can be found in the app.d file in the poly methods.

OOP in Go

The first thing an OOP developer runs into with Go is that it has no concept of a class. Rather data defined in a “struct” and those structs can have functions added to them outside the scope of the struct using what Go calls a “receiver” meaning that the function extends the struct with behavior. Encapsulation is easy. A struct member that begins with a capital letter is public. A lowercase letter is private. But similar to D, unless that struct lives in a separate package, the private member is accessible. Unlike D, a package must be in it’s own directory, so you will find the per.go and emp.go files in their own subdirectories.

Go does have a concept of an interface but it does have have an explicit declaration of an object implementing that interface. There are some advantages to this and if you assign a pointer of an instance of a struct to an interface variable and your struct does not implement receiver functions that comply with the interface, the compiler will spit that back out at you.

Here’s the same code as shared above for D. The per.go file is fairly easy to read. In fact, I quite like Go’s readability.

package per

import (
  "fmt"
  "time"
)

type Printable interface {
  Print()
}

type Person struct {
  Name string
}

func (p Person) Print() {
  fmt.Printf("Person printed.\n")
}

type Demographics struct {
  age         int
  DateOfBirth time.Time
}

func (d Demographics) GetAge() int {
  t := time.Now()
  d.age = t.Year() - d.DateOfBirth.Year()
  return d.age
}

And honestly, I’m not missing those semi-colons.

As you peruse the code https://github.com/tylerjensen/d-go-rust/tree/master/Go/oop, you will see that in app.go that Go does not support overloaded functions (methods), unless they are receiver functions for different types but that’s outside the scope of this post. It does allow you to declare a variable of type interface and then assign it a pointer to a struct variable that implements that interface in receiver functions.

OOP in Rust

Of all three languages, I had more trouble with Rust. It’s paradigms are more foreign to my C# mind, but that’s okay. In most respects, it is very similar to Go but has no garbage collector and relies on a lighter, faster approach called ownership and borrowing. I’m not sure if we call that OB or BO. Either way it is a constraint that does make you think more about resource usage and what you’re doing with your data structures.

Rust does support a concept of an interface but they call it a trait. Encapsulation was easier but I ran into trouble thinking I needed to do something similar to Go’s packages using Rust modules (“mod” keyword). I could not get the trait defined in one module and used in another. I did find some documentation and feature requests that indicate that this is not supported. So I dropped back to a single file and one module.

Here’s a partial listing of app.rs found here https://github.com/tylerjensen/d-go-rust/blob/master/Rust/oop/app.rs 

pub trait Printable {
  fn print(&self);
}

pub struct Person {
  pub name: String
}

impl Printable for Person {
  fn print(&self) {
    println!("Person Print {}", self.name);
  }
}

pub struct Demographics {
  // Cannot make this private and not require initialization 
  age: i32,
  pub date_of_birth: chrono::DateTime<chrono::offset::Utc>
}

impl Demographics {
  pub fn calc_age(self: &mut Self) -> i32 {
    self.age = Utc::now().year() - self.date_of_birth.year();
    return self.age;
  }
}

You can see that Rust does have explicit implementation for a trait (interface) and that you must pass a reference of the struct to a function of an “impl” code block for a given struct. This is definitely different than Go. But if you look carefully, you’ll see that if the implementation is going to change data in the struct, you must pass “self” as a mutable pointer. This means that calling the “calc_age” function can only be done by an instance that is declared at mutable using the “mut” keyword. If you mess up on this, the compiler will let you know.

Conclusion

I don’t know what’s next but I’m having fun. I don’t think I will continue to try to push Go and Rust into the OOP hole. They have strengths that are worth exploring without being constrained by an approach the languages were not designed to support. Exploring and learning their best practices could be fun.

Each language has its strengths and quirks. Go is certainly more popular and Rust is growing. The D language remains rather small in terms of market penetration and is nurtured by a smaller group of very dedicated computer scientists. I do not know if it will survive. Go and Rust definitely will as their communities are much larger.

More fun to come. Stay tuned.