I have two .go files - client.go ( contains the main fund) and logic.go. One of them contains the function which needs to be executed when it is invoked from the client. {
client.go -
package main
func main() {
// url is the url of the server to which the REST call has to be sent to fetch the response
client := NewClient(url)
client.DummyFunc()
}
logic.go
import (
"fmt"
)
func DummyFunc(){
// Logic here which returns the json response
}
}
I am trying to understand what could be a good object oriented way in Go to do this. Since Go has its own style of object inheritance/composition/encapsulation, could you please suggest me a way to do this as I am new to this language.
Also, I want the main function in my client.go and logic.go should contain other utility functions which can be invoked from my client.go file.
Before addressing the OO way of doing this, does client.go
need to hold the main
function? Does logic.go
need to be separated from client.go
? Also, logic.go
must be part of a package. I'm having a hard time picking up what was left out for brevity versus what may be missing.
How I would do things:
main.go (would be the same for both cases)
package main
import "client"
func main() {
client := client.Client { ClientUrl: url } // This takes the place of NewClient(url)
client.DummyFunc()
}
client.go
package client
type Client struct {
ClientUrl string
}
func (c Client) DummyFunc() {
// Logic here which returns the JSON response
}
If you would like to keep logic
separate from client
, you could do this.
client.go
package client
type Client struct {
ClientUrl string
Logic // An anonymous field let's you call Logic functions
}
logic.go
package client
type Logic struct {
// Fields
}
func (l Logic) DummyFunc() {
// Logic here which returns the JSON response
}
Notice, since we kept Logic
anonymous in the Client
struct, we were able to call DummyFunc
.
You can see some more examples here: http://golangtutorials.blogspot.com/2011/06/inheritance-and-subclassing-in-go-or.html
EDIT --------------------------------------------------------
It's a little awkward, but here's client.go
with main function in it and logic.go
is separate. If you add more functions in logic
, then client
will be able to call all other functions.
client.go
package main
import "logic"
type Client struct {
ClientUrl string
logic.Logic
}
func main() {
client := client.Client { ClientUrl: url } // This takes the place of NewClient(url)
client.DummyFunc()
}
logic.go
package logic
import "fmt"
type Logic struct {
// Fields
}
func (l Logic) DummyFunc() {
fmt.Printf("In DummyFunc
")
}
With that being said, I'm not sure this is the best way to do it. If logic
doesn't have any fields, then it makes no sense to have it as a separate struct. I would make it a function of client
, as I pointed out in the first case in the original post.