The Three-Tier pattern divides an application into three distinct layers: data, logic, and presentation. This structure helps keep code organized, easier to maintain, and more scalable as the application grows.
In many applications, data handling, business logic, and user interfaces are mixed together. This can make the code hard to manage, test, or update. The Three-Tier pattern solves this by assigning each responsibility to its own layer, allowing you to change one part without affecting the others.
Use this pattern when:
Avoid this pattern if:
The application is divided into three layers:
Each layer communicates only with its neighboring layer, promoting clean separation of responsibilities.
Think of a restaurant:
Each part does its job without needing full knowledge of the others.
Here’s a basic example in Python:
# Data Layer
_data = []
def save(item):
_data.append(item)
def fetch():
return list(_data)
# Logic Layer
def add(item):
if item:
save(item)
else:
raise ValueError("Item cannot be empty.")
def get_all():
return fetch()
# Presentation Layer
while True:
print("\n=== Menu ===")
print("1. Add Item")
print("2. View Items")
choice = input("Choose an option: ")
if choice == "1":
item = input("Enter the item: ")
try:
add(item)
print("Item added.")
except ValueError as e:
print(f"Error: {e}")
elif choice == "2":
items = get_all()
if not items:
print("No items found.")
else:
for i, item in enumerate(items, 1):
print(f"{i}. {item}")
This example separates storage, processing, and user interaction into three simple layers, each with a single responsibility.
View the full implementation in Python here: Three-Tier Pattern on GitHub