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.

Worth Sharing?

How to write good “If” statements?

Writing a good code is an art and it can be useful in so trivial things that most developers often ignore. Usually, amateurs are programmed to write an ‘if’ statement which is always accompanied by an ‘else’ . However, it is important to realize that code quality can significantly be improved if else is omitted. For instance, consider this code.


function getUser($id){
  if($id < 1){
   $user = [];
  }else{
   //some big codes
  }
  return $user
}

Here some big codes can be so big that it will return statement will be lost in it. Better would be:


function getUser($id){
  if($id < 1){
   return [];
  }
  //some big codes
  return $user
}

Worth Sharing?