Remco Haszing
Remco Haszing

Reputation: 7809

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?

Upvotes: 7

Views: 1859

Answers (2)

siebz0r
siebz0r

Reputation: 20359

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.

Upvotes: 3

SpaceTrucker
SpaceTrucker

Reputation: 13556

You could hide getters and setters by using an interface that is backed by that concrete class. This would also encourage Tell, don't ask, because there aren't any getters you could use on the interface. The constructor usage can also be hidden in factories.

Upvotes: 0

Related Questions