https://github.com/samarjiit/loose_tight_coupling
https://github.com/samarjiit/loose_tight_coupling
Last synced: 11 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/samarjiit/loose_tight_coupling
- Owner: Samarjiit
- Created: 2025-08-10T17:23:06.000Z (12 months ago)
- Default Branch: master
- Last Pushed: 2025-08-10T17:44:14.000Z (12 months ago)
- Last Synced: 2025-08-10T19:22:28.158Z (12 months ago)
- Language: Java
- Size: 4.88 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Tight Coupling vs Loose Coupling β Java Example
This project demonstrates the difference between **tight coupling** and **loose coupling** in Java using a simple example of fetching user details from a data source.
---
## π Tight Coupling
In tight coupling:
Classes are directly dependent on each otherβs concrete implementations.
Example:
UserManager creates an instance of UserDatabase directly and calls its methods.
java
Copy
Edit
private UserDatabase userDatabase = new UserDatabase();
Problem: If the data source changes (e.g., switch from MySQL to MongoDB or Web Service), you must modify the UserManager code.
Impact:
Low flexibility
Hard to maintain
Not easily scalable
## π Loose Coupling
In loose coupling:
Classes depend on abstractions (interfaces/abstract classes), not concrete implementations.
Example:
UserDataProvider interface defines a contract for fetching user details.
Different implementations:
UserDatabaseProvider β Fetches data from a database.
WebServiceDataProvider β Fetches data from a web service.
NewDatabaseProvider β Example for adding another data source.
UserManager depends on UserDataProvider:
java
Copy
Edit
private UserDataProvider userDataProvider;
public UserManager(UserDataProvider provider) {
this.userDataProvider = provider;
}
Benefit: Adding a new data source only requires:
Creating a new class that implements UserDataProvider.
Passing it to UserManager at runtime.
Impact:
High flexibility
Easier to maintain
Scales without modifying existing code
## π Key Takeaways
Tight coupling makes systems rigid and hard to change.
Loose coupling promotes flexibility, maintainability, and scalability.
Use interfaces or abstract classes to decouple components.