cover-img

Code Smell 228 - Multiple Classes per File

More than one class is a mess

21 October, 2023

0

0

0

TL;DR: Follow the separation of concerns principle and file organization

Problems

  • Code Organization
  • Coupling
  • Autoloading problems
  • Debugging
  • Version control and merge conflicts

Solutions

  1. Declare a single class per file
  2. Use name scoping

Context

In languages that declare classes using a file system, having one class per file is generally considered a best practice.

This approach helps improve code organization and maintainability and reduces potential issues.

You can organize namespaces into separate directories within your project structure.

This way, you can maintain a logical and efficient codebase while avoiding the issues of declaring multiple classes in a single file.

Sample Code

Wrong

<?

namespace MyNamespace;

class Class1 {
public function sayHello() {
echo "Hello from Class1!\n";
}
}

class Class2 {
public function sayHello() {
echo "Hello from Class2!\n";
}
}

Right

<?

namespace MyNamespace;

class Class1 {
public function sayHello() {
echo "Hello from Class1!\n";
}
}
<?

namespace MyNamespace;

class Class2 {
public function sayHello() {
echo "Hello from Class2!\n";
}
}

Detection

[X] Automatic

Many standards enforce this rule

Tags

  • Coupling

Conclusion

Keep your code organized and follow known standards

Relations

Code Smell 48 - Code Without Standards

More Info

Wikipedia Namespaces

Sonar Source

Disclaimer

Code Smells are my opinion.

Credits

Photo by Marjan Blan on Unsplash


Without requirements or design, programming is the art of adding bugs to an empty text file.

Louis Srygley

Software Engineering Great Quotes


This article is part of the CodeSmell Series.

How to Find the Stinky Parts of your Code

0

0

0

Maxi Contieri

Buenos Aires, Argentina

🎓Learn something new every day.📆 💻CS software engineer 👷coding👨🏽‍🏫teaching ✍🏾writing 🎨Software Design 🏢SOLID 🌉TDD 👴Legacy 💩Code Smells

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2024. Showcase Creators Inc. All rights reserved.