# Code Smell 228 - Multiple Classes per File

> 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

[Gist Url]: # (https://gist.github.com/mcsee/ac8b6a8e3680a3083b1a74419973b12a)
```php
<?

namespace MyNamespace;

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

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

## Right

[Gist Url]: # (https://gist.github.com/mcsee/4b950a826ccb43b3309fa11a0cee13bd)
```php
<?

namespace MyNamespace;

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

[Gist Url]: # (https://gist.github.com/mcsee/e55306d421eb33c7f70ddb77869f0ba2)
```php
<?

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

%[https://maximilianocontieri.com/code-smell-48-code-without-standards]

# More Info

%[https://en.wikipedia.org/wiki/Namespace]

%[https://rules.sonarsource.com/java/RSPEC-1996/]

# Disclaimer

Code Smells are my [opinion](https://maximilianocontieri.com/i-wrote-more-than-90-articles-on-2021-here-is-what-i-learned).

# Credits

Photo by [Marjan Blan](https://unsplash.com/@marjan_blan) on [Unsplash](https://unsplash.com/photos/jZrundu19Hw)
    
* * *

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

_Louis Srygley_
 
%[https://maximilianocontieri.com/software-engineering-great-quotes]

* * *

This article is part of the CodeSmell Series.

%[https://maximilianocontieri.com/how-to-find-the-stinky-parts-of-your-code]
