Reputation: 141
I'm new on go; have two files that share similar behavior and was told to use composition to avoid having duplicated code, but can't quite understand the concept of composition.
Both files have common functionality but have their differences one of another.
player1.go
package game
type confPlayer1 interface {
Set(string, int) bool
Move(string) bool
Initialize() bool
}
func Play(conf confPlayer1) string {
// code for Player1
}
// ... other funcs
player2.go
package game
type confPlayer2 interface {
Set(string, int) bool
Move(string) bool
// Initializer is only for Player1
}
func Play(conf confPlayer2) string {
// code for Player2, not the same as Player1.
}
// ... the same other funcs from player1.go file
// ... they differ slighly from player1.go funcs
Is there a way to combine all into a single player.go file?
Upvotes: 0
Views: 2062
Reputation: 6404
Golang uses composition.
- Object composition: Object composition is used instead of inheritance (which is used in most of the traditional languages). Object composition means that an object contains object of another object (say Object X) and delegate responsibilities of object X to it. Here instead of overriding functions (as in inheritance), function calls delegated to internal objects.
- Interface composition: In interface composition and interface can compose other interface and have all set of methods declared in internal interface becomes part of that interface.
Now to specifically answer your question, you are talking about interface composition here. You can also see code snippet here: https://play.golang.org/p/fn_mXP6XxmS
Check below code:
player2.go
package game
type confPlayer2 interface {
Set(string, int) bool
Move(string) bool
}
func Play(conf confPlayer2) string {
// code for Player2, not the same as Player1.
}
player1.go
package game
type confPlayer1 interface {
confPlayer2
Initialize() bool
}
func Play(conf confPlayer1) string {
// code for Player1
}
In above code snippet confPlayer1 interface has composed interface confPlayer2 in it, except Initialize function which is only part of confPlayer1.
Now you can use interface confPlayer2 for player 2 and confPlayer1 for player1. see code snippet below:
player.go
package game
type Player struct{
Name string
...........
...........
}
func (p Player) Set(){
.......
.......
}
func (p Player) Move(){
........
........
}
func Play(confPlayer2 player){
player.Move()
player.Set()
}
Upvotes: 1