# Code Smell 60 - Global Classes

*Classes are handy. We can call them and invoke them at any time. Is this good?*

> TL;DR: Don't use your classes as a global point of access.

# Problems

*   Coupling
    
*   Classes are global unless we use Namespaces.
    
*   Name polluting
    
*   Static Methods
    
*   Static Constants
    
*   Singletons
    

# Solutions

1.  Use namespaces, module qualifiers or similar
    
2.  Avoid namespace polluting, keep the Global names as short as possible.
    
3.  Class single Responsibility is to create instances.
    

# Sample Code

## Wrong

```php
<?

final class StringUtilHelper {
    static function reformatYYYYDDMMtoYYYYMMDD($date) {
    }
}

class Singleton {

}

final class DatabaseAccessor extends Singleton {

}
```

## Right

```php
<?

namespace Date;

final class DateFormatter {

    function reformatYYYYDDMMtoYYYYMMDD(Date $date) {
    }
    //function is not static since class single responsibility is to create instances and not be a library of utils

}

namespace OracleDatabase;

class DatabaseAccessor {
    //Database is not a singleton and it is namespace scoped
}
```

# Detection

We can use almost any linter or create dependency rules searching for bad class references.

# Tags

*   Globals
    

# Conclusion

We should restrict our classes to small domains and expose just facades to the outside. This greatly reduces coupling.

# Relations

%[https://maximilianocontieri.com/code-smell-18-static-functions] 

%[https://maximilianocontieri.com/code-smell-17-global-functions] 

# More info

%[https://maximilianocontieri.com/singleton-the-root-of-all-evil] 

%[https://maximilianocontieri.com/coupling-the-one-and-only-software-design-problem] 

# Credits

Photo by [Alfons Morales](https://unsplash.com/@alfonsmc10) on [Unsplash](https://unsplash.com/s/photos/large-library)

* * *

> Write shy code — modules that don't reveal anything unnecessary to other modules and that don't rely on other modules' implementations.

*Dave Thomas*

* * *

%[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]
