Refactoring Examples

Real-world code transformations powered by research-backed patterns

Eliminate duplication

Extract repeated logic into reusable components, reducing code size and improving maintainability

players/views.py
-18 lines+11 linesExtract Mixin
BEFORE
Auth logic mixed with business logic
24  @method_decorator(login_required, name='dispatch')
25  
29    class AdminManageUsersView(View):
30      def get(self, request, *args, **kwargs):
31        # Check if the current user is an admin
32        try:
33          player = Player.objects.get(user=request.user)
34          if not player.is_admin:
35            return HttpResponseForbidden("...")
36        except Player.DoesNotExist:
37          return HttpResponseForbidden("...")
x2 DUPLICATED
38        # Get all users...
...
52    def post(self, request, *args, **kwargs):
53      # Check if the current user is an admin
54      try:
55        player = Player.objects.get(user=request.user)
56        if not player.is_admin:
57          return HttpResponseForbidden("...")
58      except Player.DoesNotExist:
59        return HttpResponseForbidden("...")
61      # Handle user deletion...
AFTER
Auth logic cleanly separated
New Classline 10
10  class AdminRequiredMixin(LoginRequiredMixin):
11    """Mixin to require admin status."""
12  
13    def dispatch(self, request, *args, **kwargs):
14      try:
15        player = Player.objects.get(user=request.user)
16      except Player.DoesNotExist:
17        return HttpResponseForbidden("...")
18  
19      if not player.is_admin:
20        return HttpResponseForbidden("...")
21  
22      return super().dispatch(request, *args, **kwargs)
...
38  class AdminManageUsersView(AdminRequiredMixin, View):
42    def get(self, request, *args, **kwargs):
43      # Get all players and map...
...
59    def post(self, request, *args, **kwargs):
60      # Handle user deletion...

Remove indirection

Eliminate unnecessary wrapper functions that add complexity without value

pages/_app.tsx
-4 linesRemove Indirection
BEFORE
Unnecessary wrapper function
42  <Layout>
43    <Component {...pageProps} />
44    <UserTracking />
45    <LoginTracking />
USELESS WRAPPER
46  </Layout>
...
118  function LoginTracking() {
119    return <LoginTracker />;
120  }
AFTER
Direct component usage
42  <Layout>
43    <Component {...pageProps} />
44    <UserTracking />
45    <LoginTracker />
46  </Layout>
...
Simpler & More Direct
Removed 4 lines of unnecessary indirection. The code is now easier to understand and maintain.

Separate logic

Extract mixed concerns into focused modules for better testability and reusability

features/auth/hooks.ts → features/auth/storage.ts
-25 lines+3 linesExtract Storage Logic
BEFORE
Storage logic mixed with UI hook
41  const [logins, setLogins] = useStateLastUsedLogin[0]();
43  
44  // Load from localStorage on mount
45  useEffect(() => {
47    try {
48      const stored = localStorage.getItem(STORAGE_KEY);
49      if (stored) {
50        const parsed = JSON.parse(stored) as LastUsedLogin[];
51        // Filter out expired entries
52        const now = Date.now();
53        const valid = parsed.filter(
54          (login) =>
55            now - login.timestamp < EXPIRATION_DAYS * 24 * 60 * 60 * 1000,
56        );
57        setLogins(valid);
58      }
59    } catch (error) {
60      console.error("Failed to load last used logins:", error);
61    }
62  }, []);
UI HOOK
+ STORAGE LOGIC
...
59  if (valid.length !== parsed.length) {
60    localStorage.setItem(STORAGE_KEY, JSON.stringify(valid));
61  }
67  }, []);
AFTER
Clean separation
New Modulefeatures/auth/storage.ts
45  export function loadLastUsedLogins(): LastUsedLogin[] {
46    const stored = safeGetJsonCLastUsedLogin[0](
47      localStorage,
48      LAST_USED_STORAGE_KEY,
49    );
50  
51    // Filter expired, update storage...
52  
62    return loaded;
63  }
UI HOOK ONLY
40  export const useLastUsedLogin = () => {
41    const [logins, setLogins] = useStateLastUsedLogin[0]();
42  
43    useEffect(() => {
44      const loaded = loadLastUsedLogins();
45      setLogins(loaded);
46    }, []);
...
59    return { logins, setLogins };
60  };
Better Separation of Concerns
Storage logic is now testable independently. The hook is simpler and focused on UI state management.

Ready to transform your code?

Start using Command Center today and experience research-backed refactoring

Back to Home