Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I refactor chained methods?

Starting with this code:

 new Person("ET").WithAge(88)

How can it be refactored to:

 new Person("ET", 88)

What sequence of refactorings needs to be performed to complete the transformation?

Why? Because there could be hundreds of these, and I wouldn't want to introduce errors by doing it manually.

Would you say a drawback with fluent interfaces is they can't easily be refactored?

NOTE: I want to do this automatically without hand typing the code.

like image 205
Bjorn Reppen Avatar asked Sep 22 '26 17:09

Bjorn Reppen


1 Answers

Perhaps the simplest way to refactor this is to change the name "WithAge" to "InitAge", make InitAge private, then call it from your constructor instead. Then update all references of new Person(string).WithAge(int) to use the new constructor.

If WithAge is a one-liner, you can just move the code to your new constructor instead, and do away with InitAge altogether, unless having the additional method provides extra readability.

Having good unit tests will isolate where errors are introduced, if they are.

like image 81
lc. Avatar answered Sep 24 '26 06:09

lc.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!