Refactoring Examples - Command Center | Command Center
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')
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
10 class AdminRequiredMixin(LoginRequiredMixin):
11 """Mixin to require admin status."""
13 def dispatch(self, request, *args, **kwargs):
14 try:
15 player = Player.objects.get(user=request.user)
16 except Player.DoesNotExist:
17 return HttpResponseForbidden("...")
19 if not player.is_admin:
20 return HttpResponseForbidden("...")
21 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...
Source: github.com/jkoppel/django-battleships/pull/1
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 />
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.
Source: github.com/jkoppel/langfuse/pull/2
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] = useState<LastUsedLogin[]>(0);
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 }, []);
AFTER
Clean separation
New Module: features/auth/storage.ts
45 export function loadLastUsedLogins(): LastUsedLogin[] {
46 const stored = safeGetJson<LastUsedLogin[]>(
47 localStorage,
48 LAST_USED_STORAGE_KEY,
49 );
51 // Filter expired, update storage...
62 return loaded;
63 }
UI HOOK ONLY
40 export const useLastUsedLogin = () => {
41 const [logins, setLogins] = useState<LastUsedLogin[]>(0);
42 useEffect(() => {
43 const loaded = loadLastUsedLogins();
44 setLogins(loaded);
45 }, []);
...
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.
Source: github.com/jkoppel/langfuse/pull/2
Ready to transform your code?
Start using Command Center today and experience research-backed refactoring.