Writing the ‘straight’ codes

The most prominent mistake which is made during coding is calling with nested functions. For instance look at the following codes:

//bad codes
function getBooks(){
 return getAuhtors(books);
}
function getAuthors(books){
  books.authors = SomeQuery;
}
function main(){
 let booksWithAuthor = getBooks();
}

Problem with the above code is, they are nested and when you call getBooks() – you are not aware that it will bring authors as well. Let us try again by renaming the function.

//bad codes
function getBooksWithAuthors(){
 return getAuthors(books);
}
function getAuthors(books = []){
  books.authors = SomeQuery;
  return books
}
function main(){
 let booksWithAuthor = getBooksWithAuthors();
}

After the change, there is not any longer function which only takes the Books i.e. Books without authors and it is still sort of nested right? Lets further modify the codes and turn them into sequential

// Good Codes
function getBooks(){
 return books;
}
function getAuthors(books = []){
 return authors;
}
function getBooksWithAuthors(){
 books = getBooks();
 books.authors = getAuthors(books);
}

The function calls in getBooksWithAuthors now do not have nested function calls but a sequential call which combines both of the data i.e. books and authors

Advantages

  1. Codes are more readable – you know that getBooksWithAuthors will get you both.
  2. Codes will lead to isolated functions – getBooks and getAuthors are isolated functions and can be called by any other function.
  3. Codes don’t have side-effects – Here sequential call ensures that it is called where it is intended. For instance, if you want to get only books, you would call getBooks()
  4. Improve Unit Test coverage – There will be more coverage of tests as they are all isolated functions.
Writing the ‘straight’ codes

5 thoughts on “Writing the ‘straight’ codes

  1. Most of the times amatures write less codes – less and less to avoid a lot of codes in the name of DRY! Truth is straight codes and unique functions inside each class plays far better role in leaving bugs out than a massive function with hundred thousand if conditions.

  2. Leaving programming language aside, you can start writing functional programming to avoid the multi chains on an object.

  3. In frameworks, you can use Events to avoid complexity of keeping straight codes in mind. No matter what devs do, they will end up making it wrong!

  4. You can create child functions in each model and live with that. It is even better than what you have proposed in most of the cases.

Leave a Reply to Tania Cancel reply

Your email address will not be published. Required fields are marked *

Scroll to top