Nested or Pseudo-Private Classes seem great for hiding implementation details.
TL;DR: Don't use nested classes
-
Bijection fault to real-world concepts.
-
Lack of testability
-
Lack of reuse
-
Scopes and namespaces complexity
-
Make the class public
-
Keep the public class under your own namespace/module.
-
Use a Facade to the external world to hide it.
Some languages allow us to create private concepts that only live inside a more significant idea.
These classes are harder to test, harder to debug, and reuse.
class Address {
String description = "Address: ";
public class City {
String name = "Doha";
}
}
public class Main {
public static void main(String[] args) {
Address homeAddress = new Address();
Address.City homeCity = homeAddress.new City();
System.out.println(homeAddress.description + homeCity.name);
}
}
// The output is "Address: Doha"
//
// If you change privacy to 'private class City'
//
// you will get an error " Address.City has private access in Address"
class Address {
String description = "Address: ";
}
class City {
String name = "Doha";
}
public class Main {
public static void main(String[] args) {
Address homeAddress = new Address();
City homeCity = new City();
System.out.println(homeAddress.description + homeCity.name);
}
}
// The output is "Address: Doha"
//
// Now you can reuse and test the City concept
[X] Automatic
Since this is a language feature, we can detect it and avoid its usage.
- Hierarchies
Many features are bloated with complex features.
We seldom need these new pop culture features.
We need to keep a minimal set of concepts.
Code Smells are just my opinion.
Photo by Dana Ward on Unsplash
Developers are drawn to complexity like moths to a flame, frequently with the same result.
Neal Ford
Software Engineering Great Quotes
This article is part of the CodeSmell Series.