0

i have a question about preconditions. I have this code.

public class NetModel() {
    private Net net = null;
    
    public NetModel() {}
    
    public void setNet(Net net) {
        this.net = net;
    }
    /**
     * @param netName the name of the net
     * preconditions : netName is not null
     */
    public void workWithNet(String netName) {
        net.setName(netName);
    }
}

The Net class has a method to set a name for nets. I want to assure the user that if he passes a non-null string, the method will work fine. So, my question is, have I to include in the precondition that the class variable 'net' has to point to an instance of a net? Like this

/**
 * @param netName the name of the net
 * preconditions : netName is not null and class variable 'net' has to be initialized by the 
 *                 user with the method 'setNet(Net net)'
 */
 public void workWithNet(String netName) {
     net.setName(netName);
 }

Or is not the user that has to handle it? How I have to handle possible problems with class variables preconditions in a contract with the user? Thank you.

Stefano
  • 13
  • 5
  • You could use @NotNull annotation like `@NotNull String netName`. – Aditya Arora Jan 29 '22 at 11:22
  • 3
    If `NetModel` only works when `net` has been provided, you should make that a constructor parameter, so that `NetModel` instances are always in a valid state. – tgdavies Jan 29 '22 at 11:22
  • @AdityaArora yes, but that's irrelevant. It's about setting rules for the using classes, putting the responsibility to the calling method instead of this one. – Stultuske Jan 29 '22 at 11:23
  • @Stefano pretty much. If you don't, it can be called on an instance created withe the default constructor and crash – Stultuske Jan 29 '22 at 11:24
  • @tgdavies not really. the preconditions are about putting the responsibility with the using/calling class. I agree that if these are the only methods in the class, it makes no sense to have a default constructor, but for all we know, in the actual code there are more methods that don't need that variable – Stultuske Jan 29 '22 at 11:36
  • @Stultuske if so, perhaps `NetModel` should be split into two classes, one of which always has a `Net` and one which doesn't. – tgdavies Jan 29 '22 at 11:43
  • @Stultuske You are right. I have methods that work on other variables. – Stefano Jan 29 '22 at 11:44

0 Answers0