matryer/goblueprints

Go Idioms error handling err !=nil Refactor Inquiry

Closed this issue · 2 comments

Hi Mat,

I am just wondering why you are not using Golang err !=nil idiom for web socket read function.

You implement the following:

func (c *client) read() {
for {
if _, msg, err := c.socket.ReadMessage(); err == nil {
c.room.forward <- msg
} else {
break
}
}
c.socket.Close()
}

But could have been refactored to :

func (c *client) read() {

/* I understand you may have not wanted to introduce defer so early in the chapter */
defer c.socket.Close()
for {
if _, msg, err := c.socket.ReadMessage(); err != nil {
return
}
c.room.forward <- msg
}

Any specific reason why not use err !=nil instead of err == nil ?

I see this idiom is prevalent inGolang Core standard library code, I see more 3rd Party code like gorilla websocket. not strictly abide to this idiom.

I would be interested in hearing your comments or clarification regarding this subject.

Best Regards,
KK

Thanks for your question.

You’re right. It was an oversight. Your suggestion is the right way to do it.

Occasionally the rules are broken, where special error variables are returned, but generally, what you suggest is correct.

Mat

On 12 Jan 2016, at 07:30, kkruups notifications@github.com wrote:

Hi Mat,

I am just wondering why you are not using Golang err !=nil idiom for web socket read function

You implement the following:

func (c *client) read() {
for {
if _, msg, err := csocketReadMessage(); err == nil {
croomforward <- msg
} else {
break
}
}
csocketClose()
}

But could have been refactored to :

func (c *client) read() {

/* I understand you may have not wanted to introduce defer so early in the chapter */
defer csocketClose()

for {
if _, msg, err := csocketReadMessage(); err != nil {

return
}
croomforward <- msg
}

Any specific reason why not use err !=nil instead of err == nil ?

I see this idiom is prevalent inGolang Core standard library code, I see more 3rd Party code like gorilla websocket not strictly abide to this idiom

I would be interested in hearing your comments or clarification regarding this subject

Best Regards,
KK


Reply to this email directly or view it on GitHub #23.

Hi Matt,

Thanks for the quick reply and clarification.

Congratulations on book!

Best Regards,