DEV Community


Discussion on: Python vs Java

tobiassn profile image
Tobias SN

Makes sense. What I was referring to was how Java is mainly an OOP language while Python is more diverse in how you structure your code.

Thread Thread
codemouse92 profile image
Jason C. McDonald • Edited

I lost count of how many times I've had to help interns ditch bad OOP habits that Java's "best practice" taught them, and which were harming them when working in literally any other language, including C++. Here's six of the most important things that Java practice does not teach:

  • Not everything needs to be a class. If a single class can't be justified as a data type, it isn't worthy of being a class at all. Use other namespacing tools for organizing functions and/or arbitrary (static) data together.

  • If all your getters and setters are doing is blindly relaying the contents of a member, expose the variable as public. (IntelliJ literally gives you this anti-pattern in a snippet. Stop it.)

  • Side-effects are evil. Write pure functions as much as possible, even for class members. The only thing that a member function should mutate is its own instance.

  • Creating a workaround to a poorly designed API does not justify writing a class. (Looking at you, Integer class!)

  • Never, never, never blindly trust abstractions. If you don't have any idea what's going on under the hood, you lack a proper understanding of your code, and likely of the problem you're solving. (Modern C++ std library is often guilty of this too, though to a lesser extent.)

  • Use the right data type for storing your data, based on what you actually need, not what gives you the most arbitrary freedom. (Using double every time you need a floating-point number to two decimal places is an obscene waste of memory. "I might need to eventually store up to nineteen places!" Great. Refactor when you get there.)

I could go on like this for some time, but you get the picture. ;)

Thread Thread
siy profile image
Sergiy Yevtushenko

Java has great 'final' keyword and once you make field final, even Idea does not propose to create setter for it.
You missed the whole point of Integer and other relevant classes. They are immutable by design. And, frankly, boxing/unboxing works transparently so nobody actually cares. All cases where difference is sensible (for example, large collections), already covered by various libraries.
Java "best practices" described in "Effective Java" and they are quite close to what you're promoting. Unfortunately for Java there also Spring, which definitely promotes a number of very bad practices, including mutable beans and using exceptions as part of business logic.