Build Functions In The Most Maintainable Way— Clean Code Part 3

case 1 vs case 2

Functions should be Small

Blocks and Indenting

Do One Thing

functions should do one thing. they should do it well. they should do it only.

“So much complexity in software comes from trying to make one thing do two things.” — Ryan Singer

One Level Of Abstraction Per Function

Reading Code from Top to Bottom (Stepdown Rule)

SWITCH STATEMENTS

  1. do more one thing.
  2. has more than one reason to change violates SRP.
  3. not open for extended violates OCP.
  4. complex and long function structure.

polymorphism

double calculatePay(Employee e) {
switch (e.type) {
case COMMISSIONED:
return calculateCommissionedPay(e);
case HOURLY:
return calculateHourlyPay(e);
case SALARIED:
return calculateSalariedPay(e);
}
}
  1. crate the interface
public class Payment{double pay(Employee){// default case
}
}
public class CommissionedPayment extends Payment{@overwrite
double pay(Employee e){
}
}
public class HourlyPayment extends Payment{@overwrite
double pay(Employee e){
}
}
public class SalariedPayment extends Payment{@overwrite
double pay(Employee e){
}
}
Employee employee = new Employee();Payment commissionedPayment = new CommissionedPayment();
commissionedPaymen.pay(employee);
Payment hourlyPayment = new HourlyPayment();
hourlyPayment.pay(employee);
Payment salariedPayment = new SalariedPayment();
salariedPayment.pay(employee);

Use Descriptive Names

FUNCTION ARGUMENTS

  • Zero Arguments (niladic), the ideal number of arguments.
  • One Argument (monadic).
  • Two Arguments (dyadic).
  • Three Arguments (triadic).
  • More than three (polyadic), shouldn’t be used, It shouldn’t be used unless necessary.

Dyadic and Triadic Functions

Argument Objects

Don’t use inputs as outputs

Have no side effects

Error Handling

Single-Entry -> Single-Exit Rule.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store