亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

采取更實用的方法

采取更實用的方法

慕標琳琳 2022-07-14 09:02:06
我目前有這個方法(這個基本上是真的,我只是重命名了變量和對象)private void myMethod(      final InputMessage inputMessage,      final String id) {    try {        final Map<String, String> result =              jdbcTemplate.query(                  QUERY /* sql */,                   ROW_EXTRACTOR /* ResultSetExtractor */,                   id /* args */              );        if (result != null) {            inputMessage.setParam1(result.get("param1"));            inputMessage.setId(result.get("description")); // Insert description            return;        }    } catch (final Exception e) {        logger.error(...);    }    final String param1 = ...    inputMessage.setParam1(param1);    inputMessage.setId(id); // Insert the ID}我想為此采取更實用的方法。只是想嘗試一下。我堅持不同的解決方案,但沒有一個能夠保持相同的邏輯。你會怎么做?有可能嗎?我在Java 8,但你可以在Java 11必要時加入類和方法。沒有必要“轉換”整個方法,我對result提取后的部分更感興趣。然而,它與try - catch塊緊密耦合。
查看完整描述

3 回答

?
四季花海

TA貢獻1811條經驗 獲得超5個贊

我寧愿InputMessage從方法返回一個新的,而不是將其作為參數傳遞。假設您有InputMessage帶有 2 個參數的構造函數,它將如下所示:

return Optional.ofNullable(result)
    .map(map -> new InputMessage(map.get("param1"), map.get("description")))
    .orElse(new InputMessage("id", "param1"));


查看完整回答
反對 回復 2022-07-14
?
天涯盡頭無女友

TA貢獻1831條經驗 獲得超9個贊

關于什么:


private void myMethod(final InputMessage inputMessage, final String id) { 

    final Map<String, String> result = null;

    try {

        result = jdbcTemplate.query(

             QUERY /* sql */, 

             ROW_EXTRACTOR /* ResultSetExtractor */, 

             id /* args */

        );

    } catch (final Exception e) {

        logger.error(...);

    }


    if (result != null)

        setParams(inputMessage, result.get("param1"), result.get("description")) 

    else

        setParams(inputMessage, param1, id);

}


public void setParams(final InputMessage inputMessage, String param1, String param2) {

    inputMessage.setParam1(param1);

    inputMessage.setId(param2);

}


查看完整回答
反對 回復 2022-07-14
?
瀟瀟雨雨

TA貢獻1833條經驗 獲得超4個贊

在查詢數據庫結果時,您應該使用 Java 中的 Optional 類以避免 NullPointerExceptions。(https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html這里是一些進一步的文檔)。


例如,下面的一段代碼:


final Map<String, String> result =

          jdbcTemplate.query(

              QUERY /* sql */, 

              ROW_EXTRACTOR /* ResultSetExtractor */, 

              id /* args */

          );

不應該返回 null 而是返回一個Optional<Map<String,String>>,那么您將能夠以這樣的功能方式編寫代碼:


result.ifPresent(res -> {

            inputMessage.setParam1(res.get("param1"));

            inputMessage.setId(res.get("description")); // Insert description

        });

這也將幫助您去掉這里不需要的 try-catch 語句。


此外,將數據獲取功能分離到 DAO 層并在服務層中對獲取的對象進行操作也是一種很好的做法。請在此處找到更多相關文檔:https ://www.baeldung.com/java-dao-pattern


查看完整回答
反對 回復 2022-07-14
  • 3 回答
  • 0 關注
  • 123 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號