Every so often a programmer notices that he has very similar code in several places. Say there are examples of similar code here. (This is an example of toys for clarity. In the wild, this anti-pattern is usually not found on code quite simply)
function showLoginError(){
let msg = "Login Error";
logAtLevel(WARNING, msg);
displayInPopup(msg);
}
function showDbError(){
let msg = "Could not access DB";
logAtLevel(ERROR, msg);
displayInPopup(msg);
notify("db-admin@foo.com");
}
function showUnknownError(){
let msg = "Something has gone wrong";
logAtLevel(ERROR, msg);
displayInPopup(msg);
notify("general-admin@foo.com");
}
An experienced programmer can reorganize something like this, and now it can be reused and understood quite trivially.
function showError(logLevel, msg, notifyEmail){
logAtLevel(logLevel, msg);
displayInPopup(msg);
if(notifyEmail){
notify(notifyEmail);
}
}
function showLoginError(){
showError(WARNING, "Login Error");
}
function showDbError(){
showError(ERROR, "Could not access DB", "db-admin@foo.com");
}
function showUnknownError(){
showError(ERROR, "Something has gone wrong", "general-admin@foo.com");
}
but with less experienced programmers, I often see something like
function showError(errorType){
let msg;
let logLevel = ERROR;
if(errorType == "LOGIN"){
msg = "Could not access DB";
level = WARNING;
}else if(errorType == "DB"){
msg = "Could not access DB";
}else if(errorType == "UNKNOWN"){
msg = "Something has gone wrong";
}
logAtLevel(logLevel, msg);
displayInPopup(msg);
if(errorType != "LOGIN"){
notify(errorType == "DB" ? "db-admin@foo.com" : "general-admin@foo.com")
}
}
function showLoginError(){
showError("LOGIN");
}
function showDbError(){
showError("DB");
}
function showUnknownError(){
showError("UNKNOWN");
}
They should have a function of the individual parts that modify and extract them from the function, but instead they perform the function with “modes” (or sometimes with Boolean flags).
, / , . , .
, , .
P.S. - , " ", , 3 , .