Course contentsShow
← Software Engineering
Lesson 349 of 1,93310. RefactoringFree lesson

Move Method and Move Field

Learn to relocate methods and fields to classes where they better fit, improving cohesion and reducing coupling.

Move Method and Move Field

You'll learn how to relocate methods and fields to the classes where they truly belong, strengthening your code's organization and reducing unnecessary dependencies.

The Core Idea

Sometimes a method or field ends up in the wrong class. Perhaps a Customer class has a method that mostly works with Order data, or an Invoice class stores a field that really describes a PaymentProcessor. Move Method and Move Field are refactorings that relocate these misplaced elements to where they naturally fit.

When a method uses more features (data and methods) of another class than its own, it's showing Feature Envy—a code smell you've already learned about. Moving it improves cohesion (keeping related things together) and reduces coupling (minimizing dependencies between classes).

How It Works

Move Method: Identify a method that references another class heavily. Create a new method in that other class, move the logic there, and update the original class to call the new location (or remove it entirely if no longer needed).

Move Field: When a field is accessed more by another class than its own, relocate the field itself. Update all references to point to the new location.

Why This Matters

Think of organizing a toolbox: if you keep your hammer in the sock drawer because you used it once to hang a picture in your bedroom, it's technically "accessible," but it creates confusion. Moving the hammer to the toolbox where all building tools live makes everything easier to find and use.

Similarly, moving methods and fields to their proper classes makes your codebase more intuitive, easier to maintain, and reduces the number of connections between classes.

Key Takeaway: Move methods and fields to classes where they're most used—this increases cohesion within classes and decreases unnecessary coupling between them.