golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
121.61k stars 17.41k forks source link

x/tools/refactor: "Extract" features #10736

Open jmhodges opened 9 years ago

jmhodges commented 9 years ago

This is a feature request, not a bug.

It would be nice to have a command that makes it easy to extract methods and functions from code.

Something like: a command that takes a range of code in a file that should be replaced with a function or method call and a name for that function or method (let's just call it "func").

The code in the given range would be replaced in the file with a call to the new func (with return values, too) and a definition of the func would be inserted into the current file next door to the current func (or, wherever the struct is defined in the current package if it's only in one place). The arguments and return value for the func would be inferred from the variables the code range uses.

It would be nice for the command to infer whether to build a function or method by looking to see if the range of code given is inside a method and if the code refers to the method's target.

More magic would be to allow the addition of functions and methods to structs in other packages with this tool.

jmhodges commented 9 years ago

A modern example of this tooling, including the determination of arguments and return values, can be found in IntelliJ's Extract Method when writing Java code.

(IntelliJ's Extract Method, Extract Constant, etc. will also look for nearby code in the same scope as the containing method that has the same AST structure and ask if the user would like to use the method for that code as well. That would be great extra magic, but I wouldn't want to gate a first version on that.)

blinsay commented 9 years ago

It would also be awesome to have the ability to extract a constant too.

akavel commented 8 years ago

For the record, a tool implementing this seems now to be available at:

https://github.com/godoctor/godoctor (see: http://gorefactor.org/doc.html#refactoring-extract)

(reportedly created under Alan's guidance)