Domanda

Let's assume we have a simple class:

public class Person {

    private String name;
    private int age;

    public Person()
    {
        this.age = 0;
        this.name = "Default Name";
    }

    public Person(String name, int age)
    {
        this.name = name;
        this.age = age;
    }
}

In an application which direcly(from another class) uses the second constructor, and indirecly(any other way than calling it from another class) uses the first one.

Is it OK to suppress unused warnings on the first constructor?

These are the two points of view:

  • Suppress the warnings - it hasn't got clearly visible usages and suppressing warnings doesn't produce any errors anyway..

  • Suppressing warnings is redundant and it shouldn't be done because it's unclear if a public method is used from a different point in an application

I am especially interested in info about empty constructors, which are used a lot in Enterprise Java.

Which is more correct? Thanks

È stato utile?

Soluzione

I'd say it is nonsense to even raise an "unused" warning on any kind of public member of a class. I always configure my IDEs not to raise warnings in such situations.

In my opinion, it's useless to place @SuppressWarnings("unused") on any kind of public member, as such warnings shouldn't exist.

If it's public, this means that it's part of that class's contract, so any client of your class (or, extensively, of your API) may use it. So how can one detect if it's used or not in the entire Java world?

Altri suggerimenti

No, it is not Ok to suppress the warning you get in the first contructor. It is better to fix the issue that it pin-points. What you want to do is rather:

public Person()
{
    name = "Default Name";
    age = 0;
}

and the warning "The allocated object is never used" is fixed.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top