Quick tips to junior developers to write elegant code

Your code should read like a good article. Think of your classes/files as headings, and your methods as paragraphs. Sentences are the statements in your code. Here are some of the characteristics of clean code. Code should be clean, elegant, focused and it should pass the test.

1.      Use consistent formatting & indentation

To make your code clear and easy to read, make sure the indentation, line breaks, and formatting are consistent.

Example of the bad code:

function getEmployee (Empid) { 
     if (Empid!== null) \
{ 
        get_the_employee (); 
     } else 
        { 
                Exit (); 
             } 
        }

Example of the Good code:

function getEmployee (Empid) { 
     if (Empid!== null) { 
        get_the_employee (); 
     } else { 
        Exit (); 
     } 
}

2.      Use clear variable name:

Use variable names clear and meaningful. Like empID not like id or i.

3.      Use clear method names:

Same as variable use method name meaningful and clear. For ex. Use method name as SaveEmployee() rather than just Save().

One more thing to remember if you can’t name your function then that function is doing too much. You need to break that method into smaller functions.

For ex. function updateEmployeeAndSave(), create 2 methods updateEmployee() and saveEmployee().

4.      Use comments where necessary:

This is true that code should be self-explanatory, and we should not use too much comments. Your code should read well enough reducing the need for comments but still the coding is not always perfect, so comments are necessary.

Clarification comments are necessary and can be useful for anyone who reads your code and for you too in future.

5.      DRY (Don’t repeat yourself):

Every piece of code must have a single and authoritative representation within a system. This basically means that you should aim to reduce the amount of duplicated code that exists.

6.    Don’t “over clean” your code:

Be careful not to try and clean your code too much, as it can have the opposite effect, and actually make your code harder to read and maintain. It can also have an impact on productivity, if a developer has to constantly jump between many files/methods in order to make a simple change.




Ravi K S.

Solution Architect (.NET & Cloud)

5 年

Nice article for all category developers, but I have a question here, If we have an employee repository for CRUD operations then what should be the name of method SaveEmployee Or Save?

要查看或添加评论,请登录

Gaurav Jain的更多文章

社区洞察

其他会员也浏览了