0
Planned

Replace parameter by field

matthieu.vergne 8 months ago updated 8 months ago 4

Hi,

I would like to suggest a new entry in the simplifying method calls section named "Replace parameter by field", since I don't see anything equivalent. If there is already something, then adding a related entry in this section would be an added value.

When a parameter is common to all the methods of a class, it is a hint this parameter is actually a fundamental part of the object. If it is indeed the case (the object have no sense without this parameter), then the parameter should be given to the constructor of the object rather than to its methods individually.

Example:

class Database {
  Database() {/* constructor */}
  void read(Session session, String id) {/*...*/}
  void write(Session session, Object document) {/*...*/}
  void query(Session session, String customQuery) {/*...*/}
}
should be replaced by:
class Database {
  Database(Session session) {/* constructor */}
  void read(String id) {/*...*/}
  void write(Object document) {/*...*/}
  void query(String customQuery) {/*...*/}
}
The reverse operation (Replace field by parameter) would be motivated by requiring the instance to have a larger scope than the parameter. For example, if we want to use a single instance of `Database` with several `Session` instances. Such a case may arise for performance purposes, although I think that a single instance for each session behind a proxy would do the trick more cleanly most of the time.
DIR2.0
Planned

Thanks, Matthieu, that's a nice one! I'll keep this one when working on the second edition of the course, thanks!

Glad you like it. {^_^}

I like a lot refactoring.guru (quite a fan of refactoring myself) but I am not familiar with its internals, especially this "course" you mention. Does that mean it will take some time before to be added to the website? Will it even be added?

I may have similar suggestions in the future, so I wonder whether this is the right place to make them.

Yeah, I need to process it first, format the way that the rest of the articles are written, then write the examples for each language, etc. You can write any feedback & suggestions to me directly either here or via email to support@refactoring.guru (as of now, I'm the only one reading and responding).

OK, thanks for the reactivity.

I may only contribute in Java, but if you have a template requiring the right components, please share it so my future contributions already come with the relevant stuff.