DEV Community

Cover image for Code Smell 181 - Nested Classes
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

6

Code Smell 181 - Nested Classes

Nested or Pseudo-Private Classes seem great for hiding implementation details.

TL;DR: Don't use nested classes

Problems

Solutions

  1. Make the class public

  2. Keep the public class under your own namespace/module.

  3. Use a Facade to the external world to hide it.

Context

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.

Sample Code

Wrong

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 "Adress: Doha"
//
// If we change privacy to 'private class City' 
//
// We get an error " Address.City has private access in Address"
Enter fullscreen mode Exit fullscreen mode

Right

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 "Adress: Doha"
//
// Now we can reuse and test City concept
Enter fullscreen mode Exit fullscreen mode

Detection

[X] Automatic

Since this is a language feature, we can detect it and avoid its usage.

Tags

  • Hierarchies

Conclusion

Many features are bloated with complex features.

We seldom need these new pop culture features.

We need to keep a minimal set of concepts.

More Info

Disclaimer

Code Smells are just my opinion.

Credits

Photo by Dana Ward on Unsplash


Developers are drawn to complexity like moths to a flame, frequently with the same result.

Neal Ford


This article is part of the CodeSmell Series.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay