Why create a function that returns a single line of a function that does the same thing?

Issue

I’m trying to understand various coding architectures by looking into various public codes. One of which is the mime/multipart implementation by the Go team.

The below snippet is what I’ve seen. https://cs.opensource.google/go/go/+/refs/tags/go1.19.3:src/mime/multipart/formdata.go;l=156

func (r *Reader) ReadForm(maxMemory int64) (*Form, error) {
    return r.readForm(maxMemory)
}

func (r *Reader) readForm(maxMemory int64) (_ *Form, err error) {
    form := &Form{make(map[string][]string), make(map[string][]*FileHeader)}
    defer func() {
        if err != nil {
            form.RemoveAll()
        }
    }()

    // Reserve an additional 10 MB for non-file parts.
    maxValueBy

...more code here

I’ve read through some stuff about SOLID, DRY, public/ private relationships so I can’t say I know a lot of best practices/ common strategies.

Looking at the above, it looks to me like its a function that makes a private function public.

The only thing that comes to my mind is that its purely for documentation sake? But nothing concrete in my mind.

So what I’m struggling to understand here is what’s the benefit of doing so?

Thank you all for taking the time to read this.
Any comments/ reading suggestions is very much appreciated.

Solution

It is for the sake of the documentation. The PR comment explains:

Named returned values should only be used on public funcs and methods when it contributes to the documentation.

Named return values should not be used if they’re only saving the programmer a few lines of code inside the body of the function, especially if that means there’s stutter in the documentation or it was only there so the programmer could use a naked return statement. (Naked returns should not be used except in very small functions)

This change is a manual audit & cleanup of public func signatures.

To hide the return value names, the original function

func (r *Reader) ReadForm(maxMemory int64) (f *Form, err error) {
   ⋮
}

was changed to

func (r *Reader) ReadForm(maxMemory int64) (*Form, error) {
    return r.readForm(maxMemory)
}

func (r *Reader) readForm(maxMemory int64) (_ *Form, err error) {
   ⋮
}

The error return value name can not be eliminated because
deferred function accesses the error return value.

Answered By – Cerise Limón

Answer Checked By – David Marino (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.