Formatting multiple arguments passed to a function in Java

后端 未结 6 1022
广开言路
广开言路 2021-02-13 21:18

Often the number of arguments passed to a function can be large. Consider the following case:

calculate(dataManager.getLastUpdate().getNumberOfChildren(),
               


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-13 21:50

    I'll put my little sand grain here, long time ago some developer named Esteban suggested me this kind of formatting, which I 1st thought it was ugly after a while no other way of doing it is enough pleasent for me:

    final int result = calculate (
         dataManager.getLastUpdate().getNumberOfChildren()
         , dataManager.getLastUpdate().getNumberOfParents()
         , dataManager.getLastUpdate().getNumberOfGrandChildren()
         , long milliseconds
         , int somethingelse
         );
    

    I find this really clear, very easy to add/delete new arguments, the # of arguments clear, only one argument per line, method call end really clear, etc...

    Similar pattern for defining the method too

    public int calculate(
        final int numberOfChildren
        , final int numberOfParents
        , final int numberOfGrandChildren
        , final long milliseconds
        , final int somethingelse
        ) throws CalucalteExceptio {
    
         // MyCode
    
        }
    

    And finally same pattern for nested calls, StringBuilder typicall sequence

       StringBuilder sb = new StringBuilder()
           .append('Children #').append(numberOfChildren).append(NL)
           .append('Parents #').append(numberOfParents).append(NL)
           .append('GrandChildren #').append(numberOfGrandChildren).append(NL)
           ;
    

    The only problem I found is that IDE formatters never allow this 'comma at the beginning' approach which is really interesting, and a lot more readable than any other I've tried.

    Hope it adds something interesting

提交回复
热议问题