Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discouraged method, not deprecated

Some java classes need to have private properties with a public getter and setter in order to function properly. For example JSF beans and JPA entities need them. If it wasn't for those libraries, there are probably some properties which should not have any getters and definitely not setters. Also empty constructors are oftenly discouraged for use by custom code. For example

@Entity
public class MyEntity implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    public MyEntity() {}

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}

In this class the method setId should never be called by manual code. The method is not deprecated though, so an @Deprecated annotation would be wrong.

Is there another way than @Deprecated to tell a method should not be used?

like image 549
Remco Haszing Avatar asked Mar 07 '13 18:03

Remco Haszing


1 Answers

JPA entities don't need public getters and setters. Values are set using reflection (at least when using EclipseLink or Hibernate which you're probably using).

In this particular example you could simply leave the setter out, I have made a habit out of it and never had a problem with it. Note: Stick to Java naming conventions when it comes to properties and getters/setters. Some libraries/frameworks (wrongly imo) depend on this.

As for the global concept of the question, I am surprised I didn't see a suggestion that includes documentation. Documentation has, is, and will probably always be your greatest communication to users of your code.

/**
 * WARNING! DO NOT USE THIS UNLESS YOU ARE GOD!
 * This will probably break stuff unless...
 * ....
 */
public void doEvilHackishThings()
{
    // Stuff happens here.
}

If you document your code properly, developers know when they're likely to break stuff. Make sure you don't apply voodoo code etc. Good documentation describes in some detail what it does and how it does it. No developer in his right mind will touch the example method without understanding why it is evil.

like image 187
siebz0r Avatar answered Nov 11 '22 06:11

siebz0r