Memos About Salesforce

Salesforceにハマってたこと!

メソッドの返り値 必要あるパターンと必要ないパターン

自分が開発する時に

基本的に1メソッド1目的を意識して

書く。

大体、引数で処理結果を渡すなど

今回、メソッドの返り値がいるかどうか

についてその気づきを共有します。

欲しけりゃくれてやる・・・。

探せ!

この世の全てをそこに置いてきた〜笑

目次

サンプルコード

public with sharing class TryMethod {
    private Account acc;
    // コンストラクタ
    public TryMethod(){
        //パターンA
        this.acc = new Account();
        System.debug('=================');
        System.debug('名前設定前:' + this.acc.Name);
        setAcc(this.acc);
        System.debug('名前設定後:' + this.acc.Name);
        System.debug('=================');
        //パターンB
        String test;
        System.debug('=================');
        
        System.debug('1---文字列設定前:' + test);
        //return なしのメソッド使用
        setStringNone(test);
        System.debug('1---文字列設定後:' + test);
        
        
        System.debug('2---文字列設定前:' + test);
        //return あるメソッド使用
        test = setStringHas(test);
        System.debug('2---文字列設定後:' + test);
        System.debug('=================');
    }
    
    //returnなし引数で処理本体を渡すだけ
    private void setAcc(Account acc){
    	acc.Name = 'XXX株式会社';
    }
    
    // returnなし引数で処理本体を渡すだけ
    private void setStringNone(String test){
        test = 'this is test setting A';
    }
    
    // returnあり引数で処理本体を渡すだけ
    private String setStringHas(String test){
        test = 'this is test setting B';
        return test;
    }
}

実行結果

f:id:jude2016:20180727002910p:plain

結論

トリガのようなクラスでは、

オブジェクト変数を引数に渡すだけ、項目の設定

を行える、returnがなくても使える。