A Story of Refactoring in JAPAN AI STUDIO Development

⭐️This is Day 18 of the JAPAN AI Advent Calendar 2025⭐️
I'm Eiki Sugai, an engineer developing on the STUDIO team at JAPAN AI.
Recently, I've been obsessed with a card game called Flesh and Blood, and when I'm not working, I'm constantly thinking about FaB or playing at stores.
I usually develop features for the JAPAN AI STUDIO platform. I mainly work on the frontend, but sometimes I implement backend features as well.
JAPAN AI STUDIOjapan-ai.co.jpSTUDIO has many features, and team members each developed different functionalities. I also developed one feature, but this time I won't talk about the feature itself. Instead, I'll write about some refactoring-like work I did during STUDIO development.
What’s Refactoring?
As we progressed with STUDIO development, we wanted to use the settings screens and features from JAPAN AI Chat, which we normally use, within STUDIO as well.
Normally, we could simply call the components used in existing settings screens in the new STUDIO settings screen. However, all the logic for displaying settings was implemented within UI components, making it impossible to reuse the same components in other parts as-is.
Therefore, it was difficult to reuse them in STUDIO settings pages, so I worked on separating logic and UI parts to make them easier to use in other areas.
Fundamentals/Technical Explanation
What is Refactoring?
I'll skip the strict definition of refactoring. For this article, think of it as separating UI and logic to extract smaller components that can be called from other files.
For those who want to learn more about refactoring, I recommend this book. (It was recommended by my supervisor shortly after joining the company. While AI now assists with coding, I think it's important to know the principles of human-readable code.)
リファクタリング(第2版): 既存のコードを安全に改善する (OBJECT TECHNOLOGY SERIES)www.amazon.co.jp改訂新版 良いコード/悪いコードで学ぶ設計入門 ―保守しやすい 成長し続けるコードの書き方www.amazon.co.jpI'd like to share what I focused on when refactoring.
First and foremost, when refactoring, you're changing code that's currently working, so if changes cause bugs in existing features, it's better not to touch it. Therefore, careful handling is necessary.
When changing code, I always confirmed which existing features would be affected and made changes accordingly.
Fortunately, this time it was a modification to use the main settings screen within STUDIO, so the impact wasn't too significant. Still, since we're touching working code, being overly cautious is just right. Even if development speed slows down somewhat, not breaking existing features is important.
Next, it's necessary to call from separate files and ensure each settings page behaves as expected.
Naturally, even if you extract components, they can't be used in new settings screens as-is. Therefore, you need to make them usable in both existing and new settings.
Here, like the first point, you need to focus on not breaking existing features. When components were extracted from existing parts, they worked, but if supporting new functionality results in existing settings screens not working properly, it's meaningless.
What requires attention here is not to hastily commonize similar features. If you're going to use many conditional branches internally for different behaviors, implementing separate components from the start improves maintainability.
As a standard for commonization, the principle "consider commonization if you write the same code twice or more" (DRY principle) is helpful.
Even if slightly different, if they're doing roughly the same thing, you can probably handle it well with arguments.
For more details, the "Refactoring" book mentioned at the beginning and "Design Introduction Learning from Good/Bad Code" are helpful references.
To summarize important points during refactoring:
- Don't break existing features
- Be careful about what to commonize
These are basic things, but focusing on these two points will significantly reduce bugs.
Application Examples
Based on the fundamental explanation, I'll introduce what specific refactoring was performed with concrete code examples.
Let's look at the process of refactoring to separate UI and logic using a user profile editing screen as an example. This example is a simplified version of the settings screen refactoring actually performed in STUDIO development.
Before: Everything crammed into one component
The pre-refactoring code had all processing crammed into a 67-line component as follows:
// Before/UserProfile.tsx
import { useState, useEffect } from 'react';
export const UserProfile = () => {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [loading, setLoading] = useState(false);
const [errors, setErrors] = useState<{ name?: string; email?: string }>({});
// Data fetching
useEffect(() => {
const fetchProfile = async () => {
setLoading(true);
try {
const response = await fetch('/api/user/profile');
const data = await response.json();
setName(data.name);
setEmail(data.email);
} catch (error) {
console.error('Failed to fetch profile:', error);
} finally {
setLoading(false);
}
};
fetchProfile();
}, []);
// Validation
const validate = () => {
const newErrors: { name?: string; email?: string } = {};
if (!name.trim()) {
newErrors.name = 'Please enter your name';
}
if (!email.trim()) {
newErrors.email = 'Please enter your email address';
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
newErrors.email = 'Please enter a valid email address';
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
// Save Processing
const handleSave = async () => {
if (!validate()) return;
setLoading(true);
try {
await fetch('/api/user/profile', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, email }),
});
alert('Save successfully');
} catch (error) {
console.error('Failed to save profile:', error);
alert('Faild to save');
} finally {
setLoading(false);
}
};
if (loading) return <div>Loading...</div>;
return (
<div>
<h2>Profile settings</h2>
<div>
<label>Name</label>
<input value={name} onChange={(e) => setName(e.target.value)} />
{errors.name && <span style={{ color: 'red' }}>{errors.name}</span>}
</div>
<div>
<label>Email Address</label>
<input value={email} onChange={(e) => setEmail(e.target.value)} />
{errors.email && <span style={{ color: 'red' }}>{errors.email}</span>}
</div>
<button onClick={handleSave} disabled={loading}>
save
</button>
</div>
);
};This code has the following problems:
- Data fetching, validation, save processing, and UI are all mixed in one component
- We want to use the same UI on the STUDIO side, but it can't be reused (due to different API endpoints)
- When writing tests, everything needs to be tested together (logic and UI aren't separated)
The particular problem was that we wanted to use the same profile editing UI for both JAPAN AI Chat and STUDIO, but due to different API endpoints, we could only copy and paste the code.
After: Separated by responsibility
After refactoring, we separated responsibilities into three parts:
1. Custom Hook (useUserProfile.ts) - Data fetching and state management
First, we extracted data fetching and state management into a custom hook:
// After/hooks/useUserProfile.ts
import { useState, useEffect } from 'react';
interface UserProfile {
name: string;
email: string;
}
export const useUserProfile = (apiEndpoint: string) => {
const [profile, setProfile] = useState<UserProfile>({ name: '', email: '' });
const [loading, setLoading] = useState(false);
useEffect(() => {
const fetchProfile = async () => {
setLoading(true);
try {
const response = await fetch(apiEndpoint);
const data = await response.json();
setProfile(data);
} catch (error) {
console.error('Failed to fetch profile:', error);
} finally {
setLoading(false);
}
};
fetchProfile();
}, [apiEndpoint]);
const saveProfile = async (data: UserProfile) => {
setLoading(true);
try {
await fetch(apiEndpoint, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
setProfile(data);
return true;
} catch (error) {
console.error('Failed to save profile:', error);
return false;
} finally {
setLoading(false);
}
};
return { profile, loading, saveProfile };
};By receiving the API endpoint as an argument, we can reuse the same hook for both Chat and STUDIO.
2. Validation Function (validation.ts) - Business Logic
Next, we extracted validation logic as an independent function:
// After/utils/validation.ts
export interface ValidationErrors {
name?: string;
email?: string;
}
export const validateUserProfile = (name: string, email: string): ValidationErrors => {
const errors: ValidationErrors = {};
if (!name.trim()) {
errors.name = 'Please enter your name';
}
if (!email.trim()) {
errors.email = 'Please enter your email address';
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
errors.email = 'Please enter a valid email address';
}
return errors;
};By extracting it as a pure function, unit testing became very easy. You don't need to mount React components and can test just input and output.
3. UI Component (UserProfileForm.tsx) - Focus only on display
Finally, we made the UI component focus only on display:
// After/components/UserProfileForm.tsx
import { useState } from 'react';
import { validateUserProfile, ValidationErrors } from '../utils/validation';
interface UserProfileFormProps {
initialName: string;
initialEmail: string;
onSave: (name: string, email: string) => Promise<boolean>;
loading: boolean;
}
export const UserProfileForm = ({
initialName,
initialEmail,
onSave,
loading,
}: UserProfileFormProps) => {
const [name, setName] = useState(initialName);
const [email, setEmail] = useState(initialEmail);
const [errors, setErrors] = useState<ValidationErrors>({});
const handleSave = async () => {
const validationErrors = validateUserProfile(name, email);
setErrors(validationErrors);
if (Object.keys(validationErrors).length === 0) {
const success = await onSave(name, email);
if (success) {
alert('Saved successfully');
} else {
alert('Failed to save');
}
}
};
return (
<div>
<div>
<label>Name</label>
<input value={name} onChange={(e) => setName(e.target.value)} />
{errors.name && <span style={{ color: 'red' }}>{errors.name}</span>}
</div>
<div>
<label>Email Address</label>
<input value={email} onChange={(e) => setEmail(e.target.value)} />
{errors.email && <span style={{ color: 'red' }}>{errors.email}</span>}
</div>
<button onClick={handleSave} disabled={loading}>
Save
</button>
</div>
);
};Since this component controls behavior through props, it can be reused in various situations. It doesn't need to know about data fetching or saving methods.
Actual Usage Example: Reusing the same component in Chat and STUDIO
This separation enabled us to use the same UI component in both JAPAN AI Chat and STUDIO.
JAPAN AI Chat Settings Screen:
// After/pages/StudioUserProfile.tsx
import { useUserProfile } from '../hooks/useUserProfile';
import { UserProfileForm } from '../components/UserProfileForm';
export const StudioUserProfile = () => {
const { profile, loading, saveProfile } = useUserProfile('/api/studio/user/profile');
const handleSave = async (name: string, email: string) => {
return await saveProfile({ name, email });
};
if (loading && !profile.name) {
return <div>Loading...</div>;
}
return (
<div>
<h2>STUDIOプロフィール設定</h2>
<p>STUDIO専用のプロフィール情報を編集できます</p>
<UserProfileForm
initialName={profile.name}
initialEmail={profile.email}
onSave={handleSave}
loading={loading}
/>
</div>
);
};JAPAN AI STUDIO Settings Screen:
// After/pages/StudioUserProfile.tsx
import { useUserProfile } from '../hooks/useUserProfile';
import { UserProfileForm } from '../components/UserProfileForm';
export const StudioUserProfile = () => {
const { profile, loading, saveProfile } = useUserProfile('/api/studio/user/profile');
const handleSave = async (name: string, email: string) => {
return await saveProfile({ name, email });
};
if (loading && !profile.name) {
return <div>Loading...</div>;
}
return (
<div>
<h2>STUDIO Profile Settings</h2>
<p>You can edit STUDIO-specific profile information</p>
<UserProfileForm
initialName={profile.name}
initialEmail={profile.email}
onSave={handleSave}
loading={loading}
/>
</div>
);
};The only differences are the API endpoint and description text, with UI logic completely commonized. This means when UI modifications are needed, modifying just the UserProfileForm component in one place reflects changes in both Chat and STUDIO.
Effects Gained from Refactoring
This refactoring achieved the following effects:
1. Improved Reusability
- Same UI component can be used in two different screens
- When adding new screens, just combine existing components
2. Easier Testing
- Validation functions are pure functions, so unit tests are easy to write
- Custom hooks can also be tested independently
- UI components can be tested just by passing props
3. Improved Maintainability
- Clear modification points (for validation logic changes, only validation.ts)
- Limited impact scope (UI changes don't affect logic)
- Better code visibility, easier for new members to understand
4. Improved Development Efficiency
- When adding new settings screens, just combine existing components
- Bug fixes in one place eliminate missed fixes
In this refactoring, we divided a component where UI and logic were together into multiple files separated by responsibility.
While the number of files increased, each file now has only one responsibility, improving code visibility and making tests easier to write. Most importantly, we could add new functionality (STUDIO settings screen) without breaking existing features.
Refactoring isn't about "making code clean" but about making future changes easier. Like this time, when requirements like "we want to use the same UI in STUDIO" emerge, having a flexible design that can respond immediately is important.
AI-Assisted Refactoring
Code like the examples can probably be easily extracted by humans. However, very large components of 300 or 500 lines would take a lot of time. So let's have AI handle time-consuming tasks.
However, without proper instructions, separation might not be done correctly, or in some cases, code might stop working. By focusing on the following three points, you can have AI do the work and get appropriate output even in a short time.
1. Don't blindly trust AI suggestions
AI provides excellent suggestions, but it doesn't understand product-specific context. For example:
- Internal coding standards
- Existing error handling policies
- Performance requirements
These need human judgment.
2. Apply gradually (most important)
Even if AI suggests "refactor everything at once," always proceed gradually:
- First try with one component
- Verify operation
- If no problems, apply to other components
Making large changes at once makes it difficult to identify causes when problems occur.
Practical Tips: Working on multiple components together results in incomplete work or destroys existing code. Including phrases like "Please work Step by Step" in prompts and specifying components one by one works well.
3. Always verify operation
I've repeated this many times, but always verify operation even with AI-generated code. AI can generate syntactically correct code, but doesn't guarantee runtime behavior.
AI is a powerful support tool for making refactoring more efficient. However, AI is just "support," and final judgment must be made by humans. Especially:
- Confirming existing features aren't broken
- Conforming to product-specific requirements
- Judging whether refactoring should be done now
Only humans can do these.
Using AI tools as "thinking partners" while taking final responsibility yourself. This attitude leads to safe and effective refactoring.
Understanding the principles of the "Refactoring" book introduced at the beginning and utilizing AI allows you to write more efficient, safer, and higher-quality code.
Conclusion
I've explained from various perspectives, but the most important thing is not breaking existing working features.
When changing code, always perform operation verification within the impact scope without fail. Just by properly verifying operation, you can significantly reduce critical bugs. Don't skip operation verification because "there were no problems in code review." Even if troublesome, writing test code or actually verifying operation on screen can prevent critical bugs.
Final Thoughts
As emphasized in many books, when changing existing code, be conscious that you're modifying code of a currently running product.
If refactoring "for the future" results in stopping the product due to bugs, it's better not to touch working code.
I wrote at length about refactoring-like topics, but I experienced various failures in my first year and learned much from them. I wrote this article with self-reflection, hoping to reduce people making the same mistakes.
For interns and students, I'd like you to read not just this article but also the recommended books.
Thank you for reading to the end. I hope this was somewhat helpful.
【JAPAN AI】バックエンドエンジニア | 株式会社ジーニーhrmos.co