nus-cs2113-AY2021S1 / forum

8 stars 0 forks source link

Method parameters and testability #97

Closed NeilBaner closed 3 years ago

NeilBaner commented 3 years ago

Suppose I have a class defined as follows:

public class Notebook() {
    private String title;
    private String content;

    // method 1: using parameters
    private void printNotebookWithTitleParameters(String notebookTitle, String notebookContent) {
        // print it with both notebookTitle and notebookContent
    }

    private void printNotebookParameters(String notebookContent) { 
        // print the notebookContent
    }

    // method 2: using the instance members defined
    private void printNotebookWithTitleNoParameters() {
        // print this.title, this.content
    }

    private void printNotebookNoParameters() {
        // print this.content
    }
    ...
    public void print(boolean withTitle) {
        if (withTitle) {
            // method 1:
            printNotebookWithTitleParameters(title, content);
            // method 2:
            printNotebookWithTitleNoParameters();
        } else { 
            // method 1: 
            printNotebookParameters(content);
            // method 2:
            printNotebookNoParameters();
        }
     }
}

Which of the two methods (1 or 2) is preferred for elegance and testability? @longngng argues that method 1 is better, because it makes the methods more general, and easier to test because they do not depend on the instance variables. I argue that method 2 is better, because in unit testing, we would have to instantiate the class anyway to test the methods, and using the parameters causes unnecessary redundancy and increased coupling.

Great day, everyone :D

hughjazzman commented 3 years ago

In this particular example, I agree with you. There shouldn't be any case where a Notebook is printing a title of another Notebook; that other Notebook should call its own method, especially since the methods in question are private, not public. Perhaps if you are talking about public methods using method 1 could be better.

NeilBaner commented 3 years ago

Thanks for your input :) I think we'll go for method 1 then for now, because it's a bit cleaner too.