Less Encapsulation With Object-Oriented Programming

A look at the apparent contradiction of following object-oriented principles leading to tight coupling.

Erik Engheim
7 min readMar 28, 2021

--

Scott Meyers is a well known guy in the C++ developer community. He wrote a book called Effective C++, which is composed of items, which give specific advice on best practices in C++. Most of these I have forgotten and I no longer program in C++. Yet there is one item I believe has relevance to all object-oriented programming:

Effective C++ item 23: Prefer Non-member Non-friend Functions to Member Functions

In this story I want to talk about how this applies to my recent discussions of Java and Go programming. You see the Go standard library very much follows this advice while the Java standard library does not.

I want to try to demystify this advice because it will help explain why the Go code I showed in my previous story is so much shorter and easier to read than the Java code: Object-Oriented Coding: Java vs Go.

Let us take the example of io.Writer objects in Go, which can be compared to Java's OutputStream objects. It is defined like this:

type Writer interface {
Write(p []byte) (n int, err error)
}

Unlike OutputStream it is just an interface. It is not an actual implementation of anything. One Go type which implements this interface is os.File. It has methods such as:

Chmod(mode FileMode) error
Chown(uid, gid int) error
Fd() uintptr
Name() string
Stat() (FileInfo, error)
...

The list goes on. You can see a full overview of the type here: in the official Go package documentation.

A tip if you are not used to reading Go code. The type info comes last, and Go can return multiple values. So e.g.

Stat() (FileInfo, error)

This method returns both a file info and error object. If there was no errors, then the error object will be nil. Secondly if several arguments have the same type you can list the type at the end of a list of arguments:

Chown(uid, gid int) error

--

--

Erik Engheim

Geek dad, living in Oslo, Norway with passion for UX, Julia programming, science, teaching, reading and writing.