go icon indicating copy to clipboard operation
go copied to clipboard

x/tools/gopls: extract func/method arg(s) to struct

Open danp opened this issue 1 year ago • 5 comments

Given something like this, where timeout is an option:

func search(query string, timeout time.Duration) {}

When it's time to add another option, one might extract timeout to an options struct so it's then easy to add more things:

type searchOptions struct {
  timeout time.Duration
}

func search(query string, opts searchOptions) {}

A code action for this kind of extraction would be very helpful!

danp avatar Feb 06 '24 17:02 danp

There should be parameters that this code action doesn't move to a struct, such as those with types context.Context, *testing.T, or testing.TB. To play it safe, one might want to also skip any parameter with name ctx.

mvdan avatar Feb 06 '24 17:02 mvdan

We all think this is a great idea. And unlike other refactorings, this is unlikely to suffer from dropped comments, so need not wait for us to fix AST comments :)

This would be a reasonable area for a contribution, albeit a challenging one.

There should be parameters that this code action doesn't move to a struct, such as those with types context.Context, *testing.T, or testing.TB. To play it safe, one might want to also skip any parameter with name ctx.

Code actions operate on a range, so it could include any selected parameters.

findleyr avatar Feb 06 '24 17:02 findleyr

Change https://go.dev/cl/563235 mentions this issue: gopls/internal/golang: add extract argument code action

gopherbot avatar Feb 11 '24 18:02 gopherbot

Change https://go.dev/cl/620995 mentions this issue: gopls/codeaction: add function parameters extraction feature.

gopherbot avatar Oct 18 '24 01:10 gopherbot

We should also modify the parameter references within the func.body.

func search(ctx context.Context, aa int, bb int) int {
	return aa + bb
}

====>

type searchOpts struct{
	aa int
	bb int
}

func search(ctx context.Context, opts searchOpts) int {
	return opts.aa + opts.bb
}

tttoad avatar Oct 18 '24 05:10 tttoad