Hugo G
Hugo G

Reputation: 16496

What criteria is used to determine whether to refactor a code piece or not?

Refactoring code is usually a matter of applying better suiting patterns, applying coding conventions or improving performance. On the other hand, refactoring costs time and introduces the risk of including new bugs.

What criteria should be used to determine whether to refactor a code unit or not?

My guesses are:

What other aspects need to be evaluated and is there a formula or system for determining this? I'm looking for scientific or at least systematic approaches.

EDIT: I think the question is a bit off of what I actually wanted to know. It's rather: Once you found a possible code smell, how do you prioritize and communicate it? What makes one refactoring more important/urgent than another?

Upvotes: 0

Views: 688

Answers (2)

Nik Sumeiko
Nik Sumeiko

Reputation: 8723

When business requirements changes and it's hard to incorporate new software behaviour into a codebase, this is a main criteria for refactoring‌! At this moment, it becomes high priority, since it would unblock us to implement desired changes.

First make it easy to change, than make an easy change ;)

When to refactor:

  • It's hard to make a change — too many places requires modification;
  • Arrangement part within a test is way big;
  • Code smell(s) presence;
  • Implementation has many dependencies;
  • Common design pattern could replace a custom solution;
  • When source code isn't understandable;

 
As regarding when not to refactor, I'd say probably when writing code for a startup without validated product market fit. Your project could be over shortly, therefore what for to make it technically scalable before making it work.

Upvotes: 0

Marko Krstic
Marko Krstic

Reputation: 1447

There are many different situations and reasons when you should do refactoring. For example, your method is doing a lot of things. If method is doing a lot of things, it's very difficult to test it, so you need to break down into smaller and simpler methods.

Usually you should keep that one class is responsible only for one thing, and if it's not, then it's time for refactoring.

Also if method has a lot of parameters, then maybe your method is in a wrong class or maybe can be optimize on some other way.

If you have a lot of if-else conditions, then probably you should take some state/strategy pattern to eliminate if-else.

There are really a lot of cases where you should start doing refactoring, and the best is first to read the book Refactoring of Martin Fowler. In this book he covers a lot of situations and I would highly recommend it.

Upvotes: 1

Related Questions