I am having a discussion on code style, and it's starting to sound like a "matter of taste". I strongly believe otherwise, so I'm writing this to get your opinion and learn from your arguments for and against.
The issue is that of hiding complexity by replacing a bunch of lines of code with a method. This discussion is unrelated to reusable functions, and I'm trying to make the argument for simple code organization, not for factoring out common functionality.
So, take this example in loose java:
public void purchase(Customer customer, Set<Item> items, Warehouse warehouse){
int credit = customer.getCredit();
int orderPrice;
for(Item item: items){
orderPrice+=items.getPrice();
}
if(orderPrice + customer.getPendingPayments() > customer.getCredit()) {
warehouse.reserveStock(items);
transportCenter.allocateTransport();
customer.bill(items, orderPrice);
}
}
As opposed to this:
public boolean isCreditOk(Customer customer, Set<Item> items){
int credit = customer.getCredit();
int orderPrice;
for(Item item: items){
orderPrice+=items.getPrice();
}
return orderPrice + customer.getPendingPayments() > customer.getCredit();
}
public void purchase(Customer customer, Set<Item> items, Warehouse warehouse){
if(isCreditOk(customer, items)){
warehouse.reserveStock(items);
transportCenter.allocateTransport();
customer.bill(items, orderPrice);
}
}
The whole discussion now is: would you have created the isCreditOk
method or would you have left if inline? When do you do one or the other? does it depend, in a general case, on:
- The length of the function to extract
- How many sub-functions and sub-subfunctions isCreditOk will end up having
Again, this is not done because isCreditOk
will be used often, but because it makes the code easier to read (in my opinion).
Can I have your comments? Thanks!
Note: I have found this question to be related: Is there such a thing as having too many private functions/methods?