DEV Community

Tejaswini
Tejaswini

Posted on

Good code Practices

Recently I learned a few best code practices, and I want to share them.

  • When you are writing a function multiple times that may cause buffer overflow. So the better practice is to store the function value and reuse it again.

Example:

int main()
{
    int size;
    cin>>size;
    vector<int> arr(size);
    for(int i=0;i<arr.size();i++)
    cin>>arr[i];
    for(int i=0;i<arr.size();i++)
    {
      if(arr[i]==*max_element(arr.begin(),arr.end()))
      {
        max_index=i;
        break;
      }
    }
}
Enter fullscreen mode Exit fullscreen mode
  • In the above code instead of using the function arr.size() and max_element we can just store them in a variable and use it.
  • The naming of variables and functions:

So while you are naming any variable or function, use a name in such a way that others who see your code will understand what it is doing without prior knowledge of that language. I think many companies also follow this rule from what I heard.

  • Don't write complicated code. Make use of other alternative ways that are simple and easy to understand.

  • Use separate functions for different issues so that we can enhance the code reusability factor of object-oriented programming instead of writing all the functionality in the main function.

  • Object oriented programming principles are best ones to follow so that the code can be modified or extended by others later.

  • At the end but most important is to write efficient code in terms of time and space by using appropriate algorithms and data structures.

Note: I collected these from various sources, Feel free to add more in the comments so that others can learn! Happy Learning

Top comments (0)