Why SonarLint thinks this is the same result?

14 views Asked by At

Here is the sample code and SonarLint shows alert: Refactor this method to not always return the same value. And the reason is those 2 returns are the same value. It seems like Sonar thinks the MessageDao method always returns Optional.empty()? I'm a little bit confused. Could someone help to tell me what is the problem and how to refactor this method? Thanks.

/* Some method which calls MessageDao */
@Override
  public Optional<Long> createMessage(Data data, String reason, String detail) {
    try {
      DbMessage dbMessage = getDbMessage(data, reason, detail);
      return messageDao.insert(dbMessage);
    } catch (Exception e) {
      LOG.error(
          "something is wrong", e);
    }

    return Optional.empty();
  }

/* MessageDao */
public Optional<Long> insert(DbMessage message) {
    return jdbi.withHandle(handle ->
        handle.createQuery(SQL_INSERT_MESSAGE)
            .bindBean(message)
            .mapTo(Long.class)
            .findOne()
    );
  }


I define a Optional local variable, and assign the result of dao method to it, and return it at last. Now the alert disappeared, but this looks stupid.

0

There are 0 answers