https://blog.stackademic.com/frontend-masters-feature-sliced-design-fsd-pattern-81416088b006
Imagine a delicious pizza as your complex project. To understand how feature slicing works, let’s break it down slice by slice: easy to manage and delicious (to maintain)! 🍕
I will repeat what I said in my previous medium stories. This will be a long (because why not 😇) and maybe a little difficult to understand article. But once you read it and understand it perfectly, you will now be a 10x frontend developer. 😎 Let’s take your coffee. ☕️ If you don’t drink enough coffee, it will take you longer to become a 10x developer. 😅
I like to simplify web and mobile applications by dividing them into smaller parts called feature sets. Each feature set has its own user interface, business logic, and data layer, making it easier to handle. This method, called Feature-Sliced Design (FSD), shares advantages with component-based approaches. What stands out to me about FSD is its ability to break down web and mobile applications into more manageable pieces, especially focusing on user-centric features.
Structure
FSD methodology is built on three abstraction levels: layers, slices, and segments.
Layers and Slices
Imagine your app as a delicious pizza. 🍕 (As a developer working at Domino’s, it is my natural right to use the pizza analogy. 😎)
1. Shared Layer (The Pantry):
- Ingredients for everyone: Holds reusable components, utilities, hooks, and services that multiple slices can access. (Think of it as the shared kitchen where everyone can grab common ingredients and tools.)
- Examples:
- Common UI elements like buttons, forms, modals and navigation bars (think of them as pre-cut veggies and cheese)
- Utility functions for data formatting or validation (like a sharp pizza cutter)
- Global state management solutions like Redux, Zustand, Tanstack Query (the recipe book for consistency)
2. Processes Layer (The Kitchen Staff):
- The hardworking chefs: Handles background tasks and data fetching, keeping the pizza kitchen running smoothly. (Think of them as the pizza chefs who prepare the dough, sauce, and toppings, and coordinate the baking process.)
- Examples:
- Fetching pizza orders from the online system
- Sending notifications when pizzas are ready
- Syncing data with the delivery drivers
3. Features Layer (The Pizza Slices):
- Independent and self-contained: Each slice encapsulates a specific feature, with its own UI, logic, and data, like individual pizza slices with their toppings.
- Examples:
- “Order Pizza” slice: Handles pizza selection, customization, and checkout (pepperoni, mushrooms, extra cheese, sucuk -sausage- you name it!)
- “Track Order” slice: Displays order status and estimated delivery time (like a pizza tracker)
- “Review Pizza” slice: Allows customers to rate and comment on their experience (a feedback form for the chef)
4. App Layer (The Pizza Chef):
- The head chef: Oversees the entire pizza-making operation, deciding which slices to bake and how to present them to customers. (Think of it as the master chef who designs the menu, creates new recipes, and ensures each pizza is cooked to perfection.)
5. Pages Layer (The Pizza Display):
- Arranges the slices: Composes slices into meaningful page layouts, like arranging pizza slices on a platter or delivery carton box.
- Examples:
- Homepage: Combines “Featured Pizzas” and “Order History” slices
- My Account: Includes “Personal Information” and “Order Preferences” slices
6. Widgets Layer (The Spices):
- Optional flavor enhancers: Small, reusable UI components that can be sprinkled across slices or pages/screens, like adding extra seasoning to your pizza.
- Examples:
- Search bar (for finding your favorite pizza quickly)
- User notification panel (alerting you when your pizza is ready)
- Modal dialogs (for special requests or confirmations)
5. Entities Layer (The Raw Ingredients):
- Building blocks of data: Represents core business entities, like the flour, yeast, and toppings in a pizza.
- Examples:
- User entity (storing customer details)
- Pizza entity (defining pizza types and ingredients)
- Order entity (tracking order information)
Key points to remember:
- Each layer has a clear responsibility and dependency direction.
- Slices can communicate with each other using well-defined contracts, like pizza slices sharing a common crust.
- The goal is to create modular, independent, and easily testable slices, making your “pizza” codebase more manageable and delicious!
Additional pizza analogy notes:
- The kitchen staff (processes) work behind the scenes, preparing ingredients and ensuring a smooth pizza-making process.
- The pizza chef (app) is the mastermind, orchestrating the creation of different pizzas (features) and deciding how to serve them up (pages).
- The raw ingredients (entities) are essential for any pizza, but they’re not always visible to the customer — they’re the foundation that makes everything else possible.
Segments (The Toppings):
- The ingredients within a slice: While a slice is a complete feature, it’s often made up of smaller parts, called segments. These are like the individual toppings that make up a pizza slice.
- Focused on specific tasks: Each segment has a clear responsibility within its slice, like handling a particular UI element, data operation, or piece of logic.
- Examples:
- Within the “Order Pizza” slice:
- “Pizza Menu” segment: Displays available pizza options and prices.
- “Topping Selector” segment: Allows customers to choose their desired toppings.
- “Checkout Form” segment: Collects payment and delivery information.
With a more React way:
Each slice is split into one or more of the following segments:
- ui/: User Interface components and UI related logic
- model/: Business logic (store, actions, effects, reducers, etc.)
- lib/: Infrastructure logic (utils/helpers)
- config/: Local configuration (constants, enums, meta information)
- api/: Logic of API requests (api instances, requests, etc.)
Key points to remember:
- Slices are larger, self-contained features, while segments are smaller, focused parts within a slice.
- Each slice can have multiple segments, just like a pizza slice can have various toppings.
- The goal is to create well-organized, modular code that’s easy to understand, develop, and maintain — like making a pizza with beautifully arranged toppings, each adding its unique flavor to the whole pie!
How about exemplifying what we have read so far in code?
1. Folder Structure (The Pizza Kitchen Organization):
2. Order Pizza Slice (The Extravaganzza):
// features/order-pizza/slice.tsx
import React from 'react';
interface OrderPizzaSliceProps {
// ... slice props
}
const OrderPizzaSlice: React.FC<OrderPizzaSliceProps> = ({ /* ...props */ }) => {
// ... slice logic and state management
return (
<div>
<PizzaMenu />
<ToppingSelector />
<CheckoutForm />
</div>
);
};
export default OrderPizzaSlice;
3. Pizza Menu Segment (The Dough Base):
// features/order-pizza/components/PizzaMenu.tsx
import React from 'react';
interface PizzaMenuProps {
// ... pizza options
}
const PizzaMenu: React.FC<PizzaMenuProps> = ({ /* ...props */ }) => {
// ... fetch pizza options and display them
return (
<ul>
{/* List of pizza options */}
</ul>
);
};
export default PizzaMenu;
4. Homepage (The Pizza Display Counter):
Feature-Sliced Design (FSD) is like slicing that pizza into neat, individual pieces, each with its own toppings and flavor. Here’s the good and not-so-good of this approach:
// pages/HomePage.tsx
import React from 'react';
import OrderPizzaSlice from '../features/order-pizza/slice';
const HomePage: React.FC = () => {
return (
<div>
<h1>Welcome to Domino's Pizza!</h1>
<OrderPizzaSlice />
</div>
);
};
export default HomePage;
Key takeaways from the code:
- Clear folder structure: Each slice has its own folder, keeping its components and logic organized.
- Independent slices: Each slice can be developed and tested independently, like a self-contained pizza.
- Reusable components: Shared components (buttons, inputs, etc.) can be used across slices for consistency and efficiency.
- Composition within pages: Pages combine slices to create meaningful layouts, like arranging pizza slices on a platter.
Remember: This is a simplified example. Real-world FSD involves more complex state management, data fetching, and communication between slices. However, this example demonstrates the core principles of organizing React apps using FSD.
The good stuff (slices):🍕
- Easy to manage: Like separate pizza slices, each feature is self-contained, making code easier to understand, fix, and update. No more domino effect when changing one part!
- Scales like crazy: Need more features? Just add more slices! FSD lets your app grow gracefully, adapting to new needs like adding pepperoni to your veggie delight.
- Faster cooking (development): Different teams can work on separate slices at the same time, speeding up development like having multiple chefs making pizzas.
- Clear ownership: Each slice has a designated “pizzaiolo,” making developers responsible for its quality and performance, similar to how each chef takes pride in their creation.
- Testing made simple: Testing becomes like checking each slice for doneness, making it more focused and efficient.
The not-so-good stuff (crusts):👎🏻
- Trickier planning: Slices need to work together seamlessly, like ensuring the cheese doesn’t spill over when joining them. Careful planning and communication are key to avoiding a pizza mess.
- Learning curve: Newcomers might be initially confused by the distributed nature of the “pizza,” like figuring out where to find the pineapple chunks. Good documentation is essential to help them navigate.
- Extra effort for teamwork: Ensuring communication and smooth connections between slices takes time and attention, like coordinating the chefs to build the perfect pizza together.
- Potential redundancy: Sometimes, two slices might have similar ingredients, like having both mozzarella and ricotta. Careful planning and shared resources can help avoid unnecessary duplication.
- Limited tools: FSD is still relatively new, so finding tools specifically designed for it might be like searching for a pizza cutter shaped like a unicorn. It might require some extra effort at first.
The decision:
FSD is like a great strategy for large and complex apps, but it’s not a one-size-fits-all recipe. Consider your project’s size, team, and development environment before diving in. Remember, even the most delicious pizza can be tricky to make if you don’t have the right skills and ingredients!
'프로그래밍 > Web' 카테고리의 다른 글
Classic ASP에서 GUID 생성 방법 (0) | 2024.08.30 |
---|---|
[HTML] sns 용 META tag (0) | 2024.03.18 |
[Chrome] 크롬 브라우저의 읽기 모드 (0) | 2023.08.03 |
PHP 프레임워크: 생산성 및 품질 향상. PHP는 그렇게 나쁘지 않은데 왜 싫어할까요? (0) | 2023.08.03 |
[HTML] details summary , jquery로 open 제어 (0) | 2023.07.14 |