Chapter 03 - Methods
Chapter 03 - Methods
Clean Code:
A Handbook of
Agile Software Craftsmanship
Methods play an important role in code; they define a class's behavior. You might have
encountered methods
− with more than 100 lines
− managing multiple of tasks
− dealing with excessive arguments
− returning values calculated from mathematical operations.
Such methods are listed as dirty code. However, there are some points to consider that
makes methods way too clean.
Rules of clean methods:
• Rule #3: The Fewer The Arguments, The Cleaner The Method
Having too many arguments for a method confuses the reader and makes it more
difficult to understand the method’s behavior. It also complicates writing coverable
tests. Best kind of method has no arguments. Although we can have method
arguments, but it's not recommended to have more than with 3 arguments. One way to
decrease the number of arguments is to gather similar ones in a single object.
3) The Less The Arguments, The Cleaner The Method
Rules of clean methods:
// BAD CODE
public User createNewUser() {
User newUser;
if (isPasswordConfirmed)
newUser = new User();
else
newUser = null;
return newUser;
}
// GOOD CODE
public User createNewUser() {
User newUser;
if (isPasswordConfirmed)
newUser = new User();
else
throw new PasswordNotConfirmedException();
return newUser;
}
Rules of clean methods:
// BAD CODE
public Value getSomeValue() {
if (condition)
return value1;
else
return value2;
}
// GOOD CODE
public Value getSomeValue() {
Value result;
if (condition)
result = value1;
else
result = value2;
return result;
}
Rules of clean methods:
// BAD CODE
public void doSomething() {
if (condition) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// Commands
}
}
}
}
// GOOD CODE
public void doSomething() {
if (condition) {
for (int i = 0; i < n; i++) {
executeCommands();
}
}
}
Rules of clean methods:
// BAD CODE
private String openDocumentButtonPushed() {
// Codes That Open And Read The Document
try {
// Code With Possibility Of An Exception
} catch (SomeException exception) {
showMessageBox(“An error occurred while opening the document”);
}
// GOOD CODE
private void openDocumentButtonPushed() {
try {
openDocument();
} catch (NullPointerException | IOException e) {
showMessageBox(“An error occurred while opening the file”);
}
}