Go Language Object Oriented Programming: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
(34 intermediate revisions by the same user not shown)
Line 5: Line 5:
* [[Go_Language#Object_Oriented_Programming|Go Language]]
* [[Go_Language#Object_Oriented_Programming|Go Language]]
* [[Go Functions]]
* [[Go Functions]]
* [[Go_Interfaces#Overview|Go Interfaces]]
* [[Object-Oriented_Programming#Overview|Object-Oriented Programming]]
* [[Object-Oriented_Programming#Overview|Object-Oriented Programming]]


Line 14: Line 15:
<span id='Structs_as_Receiver_Types'></span><span id='Structs_as_Receiver_Type'></span>The most common pattern for implementing object-orientation is to use a <code>struct</code> as data encapsulation mechanism, optionally declaring fields as [[Go_Packages#Unexported_Members|unexported]], thus preventing direct access to them from outside the package, and then associating the struct with functions, by declaring the struct type as the [[#Receiver_Type|receiver type]] for those functions. The functions become [[#Method|methods]] of the type. This construct is the closest equivalent to a class in other programming languages. The standard dot notation is then used to call a method on the instance of the receiver type.
<span id='Structs_as_Receiver_Types'></span><span id='Structs_as_Receiver_Type'></span>The most common pattern for implementing object-orientation is to use a <code>struct</code> as data encapsulation mechanism, optionally declaring fields as [[Go_Packages#Unexported_Members|unexported]], thus preventing direct access to them from outside the package, and then associating the struct with functions, by declaring the struct type as the [[#Receiver_Type|receiver type]] for those functions. The functions become [[#Method|methods]] of the type. This construct is the closest equivalent to a class in other programming languages. The standard dot notation is then used to call a method on the instance of the receiver type.


Go does offer inheritance, overriding and polymorphism in the language syntax the same way other OOP languages do, but these features are available and can be implemented with a combination of [[Go_Structs#Embedded_Fields|struct field embedding]] and [[Go_Interfaces#Overview|interfaces]]. See: {{Internal|Go_Inheritance_and_Polymorphism#Overview|Go Inheritance and Polymorphism}}
Go does NOT offer inheritance, overriding and polymorphism in the language syntax the same way other OOP languages do. [[#Go_Does_Not_Have_Type_Inheritance|Type inheritance is NOT available]]. Behavior inheritance can be implemented with [[Go_Interfaces#Overview|interfaces]]. Polymorphism can be implemented with a combination of [[Go_Structs_Embedded_Fields#Overview|struct field embedding]] and [[Go_Interfaces#Overview|interfaces]].


=<span id='Method'></span>Methods=
=<span id='Method'></span>Methods=
 
{{Internal|Go_Methods#Overview|Go Methods}}
A '''method''' of a type is a function that was associated with the type, by declaring the type to be a [[#Receiver_Type|receiver type]] for that function, with the special syntax described below. If a method name starts with an uppercase character it is automatically [[Go_Language#Exported_Identifiers|exported]].
 
==Method Naming==
There are a number of well-known methods names like <code>Read</code>, <code>Write</code>, <code>Close</code>, <code>Flush</code>, <code>String</code>, etc. that have canonical signatures and meanings. To avoid confusion, do not give your methods one of these names, '''unless it has the same signature and meaning'''. If indeed the method you are developing has the same meaning as a method on a well-known type, give it the same name and signature: your string converter method should be called <code>String</code>, not <code>ToString</code>.
{{Internal|Go_Style#Methods|Go Style}}
==Method Set==
A type may have a '''method set''' associated with it. There are two kinds of method sets: [[Go_Interfaces#Interface_Method_Set|interface method sets]] and user-defined types method sets, described below. In the case of user-defined type method set, there's a distinction between the type method set and the pointer type method set. If a type does not have any of the previously mentioned method sets, it is said to have an empty method set. In a method set, each method must have a unique non-blank method name. The language specification defines the method sets here: {{External|https://golang.org/ref/spec#Method_sets}}
 
=Receiver Type=
 
A '''receiver type''' for a function is a type that is associated with the function with dedicated syntax:
 
<font size=-1.5>
func (<I><font color='teal'>receiver_parameter_name</font></i> <font color='teal'><i><b>receiver_type</font></I></b>|<font color='teal'><i><b>receiver_type_pointer</font></I></b>) function_name(...) ... {
  ...
}
</font>
 
Declaring a receiver type turns the function into a [[#Method|method]] of the type. Depending on whether we want to be able to modify the receiver instance in the method or not, the receiver type can be declared as a [[#Pointer_Receiver_Type|pointer receiver type]] or a [[#Value_Receiver_Type|value receiver type]].
 
<span id='Implicit_Parameter'></span>Regardless of whether we use a pointer or a value receiver type, the function gets an '''implicit parameter''', which is a pointer to the instance in case of a pointer receiver type, and a value of the type in case of a value recover type:
 
<font size=-1.5>
func function_name(<I><font color='teal'>implicit_receiver_parameter</font></i> <font color='teal'><i><b>receiver_type</font></I></b>|<font color='teal'><i><b>receiver_type_pointer</font></I></b>, ...) ... {
  ...
}
</font>
 
We call that '''receiver parameter'''. It is, loosely, the logical equivalent of the <code>[[Python_Language_OOP#The_self_Parameter|self]]</code> function parameter in Python and the implicit method parameter <code>this</code> in Java. The receiver parameter can be simply thought of as the first parameter of the function. In the underlying implementation, it is indeed not much else indeed.
 
==<span id='Receiver_Naming'></span>Receiver Parameter Naming==
As we write idiomatic Go code, it is common to use the first letter or a short two-letter abbreviation of the type as the name of the receiver parameter. A short name makes sense because these parameters typically appear on almost every line of the method body. Receiver names should be consistent cross a type's methods, do not use one name in one and other name in another.
 
<syntaxhighlight lang='go'>
func (b *Buffer) Read(p []byte) (n int, err error)
</syntaxhighlight>
<syntaxhighlight lang='go'>
func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request)
</syntaxhighlight>
 
In our case, if the name of the type is <code>Color</code>, the name of the parameter is <code>c</code> or even <code>color</code>. We might even consider naming the receiver parameters with abbreviations of the interfaces they represent. See  [https://blog.heroku.com/neither-self-nor-this-receivers-in-go#naming-the-receiver this article] for arguments against naming that parameter "this" or "self".
 
Alos see: {{Internal|Go_Style#Receivers|Go Style}}
 
==Value Receiver Type==
The syntax to declare a value receiver type for a function is:
<font size=-1.5>
func (<I><font color='teal'>receiver_parameter_name</font></i> <font color='teal'><i><b>receiver_type</font></I></b>) function_name(...) ... {
  ...
}
</font>
Example:
<syntaxhighlight lang='go'>
type Color struct {
  color string
}
 
func (c Color) SomeMethod() string {
  return "dark " + c.color
}
</syntaxhighlight>
 
In the example above, <code>Color</code> is the receiver type, and <code>c</code> is the variable that refers to the particular receiver type value the method was invoked on. The invocation target is passed as '''value''' inside the function.
 
The specification defines the '''method set of a type''' as the method set associated with the values of the type.
 
The method is invoked on the receiver type instances with the usual dot notation syntax:
<syntaxhighlight lang='go'>
color := Color{"blue"}
result := color.SomeMethod() // the method will return "dark blue"
</syntaxhighlight>
 
The invocation '''copies''' the <code>color</code> '''value''' into in the <code>c</code> variable inside the function, making <code>c</code> an [[#Implicit_Parameter|implicit parameter]] of the method. There is no formal <code>c</code> function parameter in the signature, yet the method body has access to <code>c</code>, which behaves similarly to any other function parameter. That is why the following syntax makes sense, and it also works. The syntax confirms that <code>SomeMethod()</code> is a method associated with the type <code>Color</code>, and when invoked with the instance of the type as its first (implicit) parameter, it behaves exactly as expected:
<syntaxhighlight lang='go'>
color := Color{"blue"}
Color.SomeMethod(color)
</syntaxhighlight>
 
Because the receiver instance is passed by value, hence a copy of that value is passed inside the function, the method cannot modify the invocation target instance. A [[#Pointer_Receiver_Type|pointer receiver type]] must be used if instead to modify the target.
 
==Pointer Receiver Type==
The syntax to declare a pointer receiver type for a function is:
 
<font size=-1.5>
func (<I><font color='teal'>receiver_parameter_name</font></i> *<font color='teal'><i><b>receiver_type</font></I></b>) function_name(...) ... {
  ...
}
</font>
Example:
<syntaxhighlight lang='go'>
func (c *Color) SomeOtherMethod() {
  c.color = "dark " + c.color
  // (*c).color = "dark" + (*c).color is an equivalent, longer
  // syntax. The compiler can handle the simpler syntax.
}
 
...
 
color := Color{"blue"}
color.SomeOtherMethod() // equivalent with (&color).SomeOtherMethod()
fmt.Println(color) // will print "{dark blue}"
</syntaxhighlight>
 
In the example above, a pointer to a <code>Color</code> instance is passed inside the method, so the method can mutate the target instance it was invoked on. The invocation copies the pointer to the <code>Color{"blue"}</code> value into in the <code>c</code> variable inside the function, making <code>c</code> an [[#Implicit_Parameter|implicit parameter]] of the method. Similarly to the value receiver type syntax, there is no formal <code>c</code> function parameter in the signature, yet the method body has access to <code>c</code>, which behaves similarly to any other function parameter. That is why the following syntax makes sense, and it also works. The syntax confirms that <code>SomeMethod()</code> is a method associated with the type <code>*Color</code> (note that it is a pointer type), and when invoked with the pointer to a type instance as its first (implicit) parameter, it behaves exactly as expected:
<syntaxhighlight lang='go'>
color := Color{"blue"}
(*Color).SomeOtherMethod(&color)
</syntaxhighlight>
 
===Invoking on <tt>nil</tt> Pointers===
Since pointers are involved, methods declared with pointer receiver types may be invoked on a <code>nil</code> pointers, which will lead to a "invalid memory address or nil pointer dereference" panic:
<font size=-2>
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0xbe79030]
goroutine 1 [running]:
main.(*Color).SomeOtherMethod(...)
        .../cmd/gotest/main.go:8
main.main()
        .../cmd/gotest/main.go:14 +0x10
Process finished with the exit code 2
</font>
 
If the implementation semantics allows it, the method may guard against <code>nil</code> pointers:
<syntaxhighlight lang='go'>
func (c *Color) SomeOtherMethod() {
  if c == nil {
    return
  }
  c.color = "dark " + c.color
}
</syntaxhighlight>
 
==Dot Notation works with Both Values and Pointers==
The Go compiler knows how to use the dot notation with both values and pointers.
 
There is no need to invoke a method defined with a pointer receiver type with:
<syntaxhighlight lang='go'>
(&variable).SomeMethod()
</syntaxhighlight>
This will work:
<syntaxhighlight lang='go'>
variable.SomeMethod()
</syntaxhighlight>
Similarly, inside the method, there is no need to dereference the pointer receiver type parameter:
<syntaxhighlight lang='go'>
func (v *SomeType) SomeMethod(...) {
  (*v).someField // not necessary
}
</syntaxhighlight>
This will work:
<syntaxhighlight lang='go'>
func (v *SomeType) SomeMethod(...) {
  v.someField
}
</syntaxhighlight>
 
==Mixing Value and Pointer Receiver Types==
When using pointer receivers, it is good programming practice to have all method use pointer receivers, or none of them use pointer receivers. If we mix value and pointer receivers, the IDE would detect that as static check warning:
 
<font size=-2>
  Struct Color has methods on both value and pointer receivers. Such usage is not recommended by the Go Documentation.
</font>
 
==Functions as Receiver Types==
 
<font color=darkkhaki>TODO: https://go.dev/blog/error-handling-and-go#simplifying-repetitive-error-handling</font>


=Encapsulation=
=Encapsulation=
Line 220: Line 53:
=<span id='Interface'></span>Interfaces=
=<span id='Interface'></span>Interfaces=
{{Internal|Go_Interfaces#Internal|Go Interfaces}}
{{Internal|Go_Interfaces#Internal|Go Interfaces}}
=<span id='Inheritance'></span><span id='Polymorphism'></span><span id='Overriding'></span>Inheritance and Polymorphism=
=Inheritance=
{{Internal|Go_Inheritance_and_Polymorphism#Overview|Go Inheritance and Polymorphism}}
 
==Go Does Not Have Type Inheritance==
 
Go does not have type inheritance in the same sense a fully featured object-oriented programming language has.
 
In Java or Python, a type can be at the same time other type. For example, a Dog instance is at the same type an Animal instance, where "Dog" and "Animal" are two distinct types in the type system, and "Dog" inherits "Animal". The language syntax supports this model.
 
In Go, one instance is of one type, and one type alone. The instance cannot be at the same time an ancestor type and a descendant type.
 
==Behavior Inheritance==
 
Go supports inheritance of behavior, by allowing interface inheritance. <font color=darkkhaki>Explain this better.</font>

Latest revision as of 02:26, 4 November 2024

External

Internal

Overview

Go is an object-oriented language, but the object orientation programming model is relatively simple, compared with other object-oriented languages. It has been said about Go that is "weakly" object-oriented. Go does not use the term "class", there is no class keyword in the language. However, Go allows associating data with methods, which what a class in other programming languages really is.

Go provides syntax to associate an arbitrary local type with arbitrary functions, turning them into methods of that type. The local type can be a type alias, a struct or a function. In this context, "local" means a type that is defined in the same package as the function. That is why a programmer cannot add new methods to built-in types.

The most common pattern for implementing object-orientation is to use a struct as data encapsulation mechanism, optionally declaring fields as unexported, thus preventing direct access to them from outside the package, and then associating the struct with functions, by declaring the struct type as the receiver type for those functions. The functions become methods of the type. This construct is the closest equivalent to a class in other programming languages. The standard dot notation is then used to call a method on the instance of the receiver type.

Go does NOT offer inheritance, overriding and polymorphism in the language syntax the same way other OOP languages do. Type inheritance is NOT available. Behavior inheritance can be implemented with interfaces. Polymorphism can be implemented with a combination of struct field embedding and interfaces.

Methods

Go Methods

Encapsulation

Encapsulation in this context is giving access to private data, such as package-internal data or private struct fields, via public methods. This way, access to data is controlled.

Encapsulation can be implemented with package data and with structs, where the "private" fields are declared using identifiers that start with lower cap letters, so they are not visible outside the package. Controlled access to them is given via accessor and mutator methods, or getters and setters, which are functions that have been declared to use the struct as a receiver type:

type Color struct {
	color string
}

func (c *Color) Init(color string) {
	c.SetColor(color)
}

func (c *Color) Color() string {
	return (*c).color
}

func (c *Color) SetColor(color string) {
	(*c).color = color
}

...

var c Color
c.Init("blue")
fmt.Println(c.Color()) // prints blue
c.SetColor("red")
fmt.Println(c.Color()) // prints red

Interfaces

Go Interfaces

Inheritance

Go Does Not Have Type Inheritance

Go does not have type inheritance in the same sense a fully featured object-oriented programming language has.

In Java or Python, a type can be at the same time other type. For example, a Dog instance is at the same type an Animal instance, where "Dog" and "Animal" are two distinct types in the type system, and "Dog" inherits "Animal". The language syntax supports this model.

In Go, one instance is of one type, and one type alone. The instance cannot be at the same time an ancestor type and a descendant type.

Behavior Inheritance

Go supports inheritance of behavior, by allowing interface inheritance. Explain this better.