Worst Java practice found in your experience? [closed]

Similar to this question...

What are the worst practices you actually found in Java code?

Mine are:

  • using instance variables in servlets (it's not just bad practice but bug, actually)
  • using Collection implementations like HashMap, and not using the appropriate interfaces
  • using seemingly cryptic class names like SmsMaker (SmsFactory) or CommEnvironment (CommunicationContext)

Asked by: Justin807 | Posted: 21-01-2022

Answer 1

I had to maintain java code, where most of the Exception handling was like:

catch( Exception e ) {}

Answered by: Aston808 | Posted: 22-02-2022

Answer 2

Once I encountered 'singleton' exception:

class Singletons {
    public static final MyException myException = new MyException();

class Test {
    public void doSomething() throws MyException {
        throw Singletons.myException;

Same instance of exception was thrown each time ... with exact same stacktrace, which had nothing to do with real code flow :-(

Answered by: Paul973 | Posted: 22-02-2022

Answer 3

Six really bad examples;

  • Instead of error reporting, just System.exit without warning. e.g.
    if(properties.size()>10000) System.exit(0); buried deep in a library.
  • Using string constants as locks. e.g. synchronized("one") { }.
  • Locking on a mutable field. e.g. synchronized(object) { object = ...; }.
  • Initializing static fields in the constructor.
  • Triggering an exception just to get a stack trace. e.g. try { Integer i = null; i.intValue(); } catch(NullPointerException e) { e.printStackTrace(); }.
  • Pointless object creation e.g. new Integer(text).intValue() or worse new Integer(0).getClass()

Answered by: Emma754 | Posted: 22-02-2022

Answer 4


Answered by: Julian819 | Posted: 22-02-2022

Answer 5

I hate it when people create interfaces just for hanging a set of constants on:

public interface InterfaceAntiPattern {
  boolean BAD_IDEA = true;
  int THIS_SUCKS = 1;

—Interfaces are for specifying behavioural contracts, not a convenience mechanism for including constants.

Answered by: Aston655 | Posted: 22-02-2022

Answer 6

Not related strictly to Java, but calling an expensive function over and over instead of storing the result, when you know it won't change. Example:

if (expensiveFunction() > aVar)
    aVar = expensiveFunction();
for (int i=0; i < expensiveFunction(); ++i)

Answered by: Lily807 | Posted: 22-02-2022

Answer 7

Ridiculous OO mania with class hierachies 10+ levels deep.

This is where names like DefaultConcreteMutableAbstractWhizzBangImpl come from. Just try debugging that kind of code - you'll be whizzing up and down the class tree for hours.

Answered by: Tess228 | Posted: 22-02-2022

Answer 8

The worst Java practice that encompasses almost all others: Global mutable state.

Answered by: Patrick387 | Posted: 22-02-2022

Answer 9

Subclassing when you're not supposed to, e.g. instead of using composition, aggregation, etc.

Edit: This is a special case of the hammer.

Answered by: Melanie357 | Posted: 22-02-2022

Answer 10

Our intern used static modifier to store currently logged user in Seam application.

 class Identity{
    public static User user; 

 class foo{

    void bar(){


Of course it worked when he tested it :)

Answered by: Daniel976 | Posted: 22-02-2022

Answer 11

saw something like this:

public static boolean isNull(int value) {
    Integer integer = new Integer(value);

    if(integer == null) {
        return true;
    } else {
        return false;

They had a similar method for longs.

I presume they had originally done something like

if(value == null) {

and got a compile error and still didn't realise that primitive values couldn't be null.

Answered by: Caroline988 | Posted: 22-02-2022

Answer 12

I once had to investigate a web application where ALL state was kept in the web page sent to the client, and no state in the web server.

Scales well though :)

Answered by: Freddie148 | Posted: 22-02-2022

Answer 13

Not closing database connections, file handles etc in a finally{}

Answered by: Adelaide168 | Posted: 22-02-2022

Answer 14

Abstracting functionality out into a library class which will never be re-used as it's so specific to the original problem being solved. Hence ending up with a gazillion library classes which no-one will ever use and which completely obscure the two useful utilities you actually do have (i.e. CollectionUtils and IOUtils).

...pauses for breath...

Answered by: Byron613 | Posted: 22-02-2022

Answer 15

An API that requires the caller to do:

Foobar f = new Foobar(foobar_id);
f = f.retrieve();

Any of the following would have been better:

Foobar f = Foobar.retrieve(foobar_id);


Foobar f = new Foobar(foobar_id); // implicit retrieve


Foobar f = new Foobar();
f.retrieve(foobar_id); // but not f = ...

Answered by: Catherine211 | Posted: 22-02-2022

Answer 16

Creating acessors and mutators for all private variables, without stopping to think, sometimes automatically.

Encapsulation was invented for a reason.

Answered by: Daisy762 | Posted: 22-02-2022

Answer 17

Not thinking like a programmer should.

After prolonged exposure, Java does that to some people.

Why? My opinion is that it's because there's too much Intellisense and no sense. It lets you do stupid things so quickly that people don't stop to think.

Example 1:

boolean negate( boolean shouldNegate, boolean value ) {
  return (shouldNegate?(!value):value;

which, of course is the same as value ^ shouldNegate, a simple XOR.

Example 2: (I swear I'm not making this up)

boolean isNotNull( Object o ) {
  return o != null;

Both with additional 4-6 lines of Javadoc, explaining what those methods did.

Example 3:


An empty Javadoc, to make those annoying Eclipse "missing Javadoc" warnings go away.

Example 3b:

* A constructor. Takes no parameters and creates a new instance of MyClass.
public MyClass() {

Answered by: Emma630 | Posted: 22-02-2022

Answer 18

Overkill abstraction of object oriented design (Deleted so 10k only).

Same answer on a similar thread (applies to all languages which permit object oriented design).

Answered by: Sophia165 | Posted: 22-02-2022

Answer 19

My favorite sorting algorithm, courtesy of the gray beard brigade:

List needsToBeSorted = new List ();
...blah blah blah...

Set sorted = new TreeSet ();
for (int i = 0; i < needsToBeSorted; i++)
  sorted.add (needsToBeSorted.get (i));

needsToBeSorted.clear ();
for (Iterator i = sorted.iterator (); i.hasNext ();)
  needsToBeSorted.add (i.next ());

Admittedly it worked but eventually I prevailed upon him that perhaps Collections.sort would be a lot easier.

Answered by: Michael618 | Posted: 22-02-2022

Answer 20

@madlep Exactly! Parts of the Java community really goes overboard with extreme abstractions and crazily deep class hierarchies. Steve Yegge had a good blog post about it a couple of years back: Execution in the Kingdom of Nouns.

Answered by: Lana106 | Posted: 22-02-2022

Answer 21

Defining the logic using exceptions where a for-loop or any form of loop would suffice.


while(i < MAX_VALUE)
         array[j] = //some operation on the array;

   catch(Exception e)
      j = 0;

Serious, I know the guy who wrote this code. I reviewed it and corrected the code :)

Answered by: Catherine403 | Posted: 22-02-2022

Answer 22

I saw this line a couple of minutes ago:

Short result = new Short(new Integer(new Double(d).intValue()).shortValue());

Answered by: Sawyer192 | Posted: 22-02-2022

Answer 23

In File I/O: incorrect use of try-catch block.

try {
   /* open file */
catch(Exception e) {

try {
   /* read file content */
catch (Exception e) {

try {
   /* close the file */
catch (Exception e) {

Answered by: John272 | Posted: 22-02-2022

Answer 24

Similar to yours, but taken a step further:

Use of class (static) variables when a request scoped variable was the correct thing to do in a Struts action. :O

This was actually deployed in production for a few months, and no one ever noticed a thing until I was reviewing the code one day.

Answered by: Nicole466 | Posted: 22-02-2022

Answer 25

Excesive focuse on re-using objects that leads to static things everywhere. (Said re-using can be very helpfull in some situation).

Java has GC build-in, if you need an object, create a new one.

Answered by: Fiona246 | Posted: 22-02-2022

Answer 26

Here is a cropped sample from an actual applet i was to maintain it took me forever to realize what is was doing.

int sval, eval, stepv, i;
double d;
                if (/*someCondition*/)
                    sval = 360;//(all values multiplied by 20)
                    eval = -271;
                    stepv = -10;
                else if (/*someCondition*/)
                    sval = 320;
                    eval = -601;
                    stepv = -10;
                else if (/*someCondition*/)
                    sval = 0;
                    eval = -311;
                    stepv = -10;

                    sval = 360;
                    eval = -601;
                    stepv = -10;
                for (i = sval; i > eval; i = i + stepv)
                    d = i;
                    d = d / 20.0;
                    //do some more stuff in loop

turns out he wanted to iterate by .5 over the loop and thats not a pasting error, that is the indentation scheme

Answered by: Victoria869 | Posted: 22-02-2022

Answer 27

AbstractSpringBeanFactoryFactoryFacadeMutatorBeanFactory. I can't stand this over-engineered, incomprehensible BS. Benji Smith puts it a bit more elegantly.

Answered by: John454 | Posted: 22-02-2022

Answer 28

Huge Class names. I remember: AbstractTableComponentListeningBehaviourPanel.java and other similar monsters.

The worst part is, even though the naming convention was crazy detailed, I still had to pick apart the files to work out their purpose.

Answered by: Dainton750 | Posted: 22-02-2022

Answer 29

A mistake made by junior programmers: unnecessarily using member variables instead of local variables.

A Java EE example:

Starting threads in servlets or EJBs (for example to start asynchronous processing tasks).

This breaks the scalability of your Java EE app. You're not supposed to mess with threading in Java EE components, because the app server is supposed to manage that for you.

We refactored this by having the servlet put a message on a JMS queue and writing a message-driven bean to handle the asynchronous processing task.

Answered by: Maddie579 | Posted: 22-02-2022

Answer 30

I think this one for me must be a record. A class is used for building a complex data model for the front end involving filtering. so the method that returns the list of objects goes something like this:

    public DataObjectList (GenerateList (massive signature involving 14 parameters, three of which are collections and one is a collection of collections) 
try { 

250 lines of code to retrieve the data which calls a stored proc that parses some of it and basically contains GUI logic

 } catch (Exception e) {
            return new DataObjectList(e, filterFields);

So I got here because I was wondering how come the following calling method was failing and I couldn't see where the Exception field was being set.

DataObjectList dataObjectList= EntireSystemObject.getDataObjectList Generator().generateDataObjectList (viewAsUserCode, processedDataRowHandler, folderQuery, pageNumber, listCount, sortColumns, sortDirections, groupField, filters, firstRun, false, false, resetView);


if (dataObjectList.getErrorException() == null) {

do stuff for GUI, I think, put lots of things into maps ... 250 lines or so

            return dataObjectList;
        } else {

put a blank version into the GUI and then  

            throw new DWRErrorException("List failed due to list generation error", "list failed due to list generation error for folder: " + folderID + ", column: " + columnID, List.getErrorException(), ListInfo);

All with me so far?

Well at least they did tell us in the front end that something did actually go wrong!

Answered by: Cherry748 | Posted: 22-02-2022

Similar questions

Anyone here have any experience using gcj's CNI for java external libraries?

I've been interested in doing some work on a desktop application for while now and my most proficient language is Java. Due to wanting to be able to compile down to a native executable, does anyone have any experience they would like to share about using gcj to compile, and CNI for libraries? I was hoping to use of of the native toolkits, not just Swing/SWT.

java - What is a good way to provide a different user experience based on the visitor type?

I am looking for a way to allow a Web application to provide a different user experience based on the type of visitor. For example, the same set of data should be presented differently to a child versus an adult. This is for a Java Web app. Just wanted to provide more clarification. What I am hoping for is any best practice for handling all facets for providing a different user experience for different types of v...

java - C# on Linux - Anyone got an opinion based on experience using mono?

Is it worthwhile learning C# if you are a Linux user? There is Mono but it seems destined to always be behind the curve with the constant threat of MS action if they start to lose money. Currently I am leaning more towards Java as its is fully GPLed and there are no major threats of software patents. It already has a big oss community behind it and has a solid reputation on the server whereas C# still needs to prov...

java - What is your experience with ARM Jazelle?

I'm evaluating between open source and closed source JVM for ARM. In particular, the closed source JVM can make use of Jazelle (java acceleration for newer ARMs). Do you have any experice with this technology? (And BTW, which OS do you use with it?)

java - What is your experience with GWT?

Do you find the Google Web Toolkit to be a useful project? Are there licensing issues?

java - What's your experience with adding SSL to Tomcat 6?

Over the weekend we added SSL security to a Tomcat 6 instance that has been running for awhile without error. This morning, after the number of sessions increased on the machine, Tomcat began throwing 500 errors to users. I checked the logs and found an instance of OutOfMemory, followed by dozens of errors related to Google Guice attempting to start new threads. I can only image that with the addition of SSL, more memor...

java - Any real world experience with H2 database?

java - Experience with Drools Flow and/or OSWorkflow?

I'm looking for a straightforward Java workflow engine that: can handle both automated and manual (GUI-based) steps within a workflow supports long-running, asynchronous tasks provides support for restarting workflows in the event of a server crash stores a full audit history of previously executed workflows provides easy access to this audit history data Pos...

java - What experience do you have using nginx and memcached to optimize a web site?

Closed. This question is opinion-based. It is not c...

migration - Experience migrating legacy Cobol/PL1 to Java

ORIGINAL Q: I'm wondering if anyone has had experience of migrating a large Cobol/PL1 codebase to Java? How automated was the process and how maintainable was the output? How did the move from transactional to OO work out? Any lessons learned along the way or resources/white papers that may be of benefit would be appreciated. EDIT 7/7: Certainly the...

Still can't find your answer? Check out these amazing Java communities for help...

Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)