Breaking up methods/functions to do one thing only is considered a good practice as it leads to more maintainable and readable code but it increase time complexity in many cases . How to achieve both ie. optimum time complexity while still keeping readability/maintainability ?
As illustrated in this dummy example . I want to find count of J
s in a string but also want to check if addition of all positive integers is even
or odd
. Two separate methods for these 2 different tasks leads to excellent readability but increases time complexity . Combining them in a method leads to very low readability but decreases time complexity.
class UserText{
constructor(userProvidedText){
this.content = userProvidedText;
}
_findCharCount(char){
let count = 0;
for (let i = 0; i < this.content.length; i++) {
if (this.content[i] === char) {
count++;
}
}
return count
}
_isDigit(char) {
return !isNaN(parseInt(char));
}
// Excellent Readability and maintainability
findJs(){
return this._findCharCount("J")
}
// Excellent Readability and maintainability
CheckIfDigitsAdditionEven(){
let count = 0;
for (let i = 0; i < this.content.length; i++) {
console.log(this.content[i])
if (!this._isDigit(this.content[i])){
continue
}
count+=parseInt(this.content[i]);
}
if (count % 2 === 0){
return true
}
return false
}
// Combining functionalities in 1 function . Not readable. Not maintainable But time complexity is decreased.
CheckIfDigitsAdditionEvenAndCountJs(char){
let count1 = 0;
let count2 = 0;
let res1 = false;
for (let i = 0; i < this.content.length; i++) {
if (this.content[i] === char) {
count2++;
}
if (this._isDigit(this.content[i])){
count1+=parseInt(this.content[i]);
}
}
if (count1 % 2 === 0){
res1 = true
}
return [res1, count2]
}
}
ut = new UserText("SOME..STRING..12311.HHIIJJJJKKKLL ")
/*
Breaking up functions and using them one at a time . One method , one purpose..
Maintainable and readable but time complexity is O(2n) .
*/
JCount=ut.findJs() // Time complexity O(n)
evenCheck=ut.CheckIfDigitsAdditionEven() //Time complexity O(n)
/*
Using 1 function for the task . One method , multi-purposed..
Maintainable and readable is very low but time complexity is O(n) .
*/
cr=ut.CheckIfDigitsAdditionEvenAndCountJs("J") //Time complexity O(n)
// Some custom logic here .
console.log(JCount, evenCheck)
console.log(cr)