Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The lack of inheritance and creation methods are a bit annoying at times (particularly the latter), but there's still benefits of adopting an OOP approach in Go.

For example, say you're writing a CMS and want to make strings like the article title to be used in the URL (for readable URLs and SEO), displayed in HTML (eg inside heading tags) and also potentially used for string comparisons, you'd need to have a function to URL / HTML encode the string and you'd need to remember to do it each time you outputted the string. This can make it very easy to introduce vulnerabilities where you forget to HTML encode the string. With methods, you can force the developer to state which format to output the string as:

    type DisplayText struct {
        Value string
    }
    
    func (dt DisplayText) HTMLEscaped() string {
        return html.EscapeString(dt.Value)
    }
    
    func (dt DisplayText) URLEscaped() string {
        return url.QueryEscape(dt.Value)
    }
    
    var article_title DisplayText
So now when ever you call article_title, you have to specify the string encoding. Which is not only more secure (eliminates the risk of forgetting to encode your string), but also more readable:

    fmt.Println(article_title.HTMLEscaped)
vs

    fmt.Println(html.EscapeString(article_title))


The last line was probably intended as

  fmt.Println(html.EscapeString(article_title))


You're right, it was. I'll correct that now.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: