What Makes A Good Clean Elegant Code?

This is my very first Blog Post So take it easy on me 😀 i hope you like it. 

If you’re a developer, then there probably have been times when you’ve written code and, after a few days, weeks, or months, you looked back at it and said to yourself “What does this piece of code do?” The answer to that question might have been “I really don’t know!” In that case, the only thing you can do is going through the code from start to finish, trying to understand what you were thinking when you wrote it.

In some ways, clean code — like beauty — is in the eye of the beholder. Experienced programmers can look at a program’s source code and tell whether it’s readable or not. They also quickly develop an opinion of whether the code is efficient, whether it’s well structured and even elegant in its simplicity. All of these characteristics are hard to define, but you usually get agreement among software developers when you present them with code as to whether it is clean or not.

 

Good elegant code is simple, concise but clear 

There is a balance in the code – a rhythm in the definition and structure of conditionals and the loops. The intent of each function shines through the code – a pattern in the creation and interaction of the classes and methods in classes that combines the code into a coherent and beautiful unit

There are many things that contribute to clean code. Some are universal and apply to any type of programming language or problem domain for which you are developing software. Some of the properties of clean code depend upon the specific programming language.

 

 

Why would we want to write elegant code?  400_F_36706865_nr03IQvO3EDn95ST0aPS7WlNUCZXohBR

  • Improve software quality: Well-known practices on your code will (with high probability) make software more stable and usable. 

  • Software Readability: Most software applications are not the sole creation of an individual. Working with teams is always a challenge; code metrics allows teams to standardize the way they work together and read more easily each other’s code.

    • Code flexibility: Applications with a good balance of complexity and design patterns are more malleable and adaptable to small and big changes in requirements and business rules.

Reduce future maintenance needs: Most applications need some sort of review or improvement on their lifetime. Coming back to code written a year ago will be easier if the code have good metrics.  😀

 

Now let’s Discuss 

Best Practices For Writing High Performance Elegant Code 

 

1 – Avoid boxing and unboxing
Boxing/unboxing enables value types to be treated as objects which is stored on the garbage collected heap. Boxing is the packaging of the value type in an instance of the object reference type and unboxing is the extraction of the value type from the reference type. Where possible this should be avoided as it is a major drain on performance.

Screenshot (180)

 

  • Avoid Finalize
    the .NET garbage collector automatically handles the disposable of unused items, using Finalize the explicitly destroy an object requires invoking an instance of the garbage collector which is un-necessary and is a drain on performance.    

Read Values from Objects Only Once
Reading values from objects is not as fast as assessing the value of a simple variable. For example, a loop through an array’s contents should not access the array’s Length property on each iteration of the loop, instead copy the Length property to an Integer and then access this value on each iteration.
This applies to any classes you create as well, read all properties into a simple string or integer type if possible and then access that type multiple times.

Use The String Builder – Wisely!
Concatenating large strings in a loop is a performance drain and the String builder’s Append method is much more efficient. However don’t go overboard on this, the String builder is object requires a lot more memory than a String and it is not efficient for concatenating a small number of times – only use the String builder if more than four concatenations are required.

Minimize Exceptions
catching and throwing exceptions is very expensive and should be avoided where possible. Exception blocks should never be used to catch an error caused by attempting to access a null object, instead use a statement to test if the object is null before accessing it: 

Screenshot (181)

 

Avoid Depth of Nesting

  • Measures the nesting levels in a procedure.
  • The deeper the nesting, the more complex the procedure is. Deep nesting levels often leads to errors and oversights in the program logic.
  • Avoid having too many nested logic cases, look for alternate solutions to deep if then else for foreach switch statements; they lose logic sense in the context of a method when they run too deep.

 

Depth of Inheritance (DIT)

  • Measures the number of classes that extend to the root of the class hierarchy at each level.
  • Classes that are located too deep in the inheritance tree are relatively complex to develop and maintain. The more of those you have the more complex and hard to maintain your code will be.
  • Avoid too many classes at deeper levels of inheritance. Avoid deep inheritance trees in general.

 

 

Design Patterns

  • Design Patterns play an extremely important role in the architecture of complex software systems. Patterns are proven solutions to problems that repeat over and over again in software engineering. They provide the general arrangement of elements and communication to solve such problems without doing the same twice.
  • Depending on the needs of the problem, applying proven design patterns like Observer, Command and Singleton patterns will greatly improve the quality, readability, scalability and maintainability of your code.

 

For Instead of Foreach
Foreach can simplify the code in a for loop but it is a heavy object and is slower than a loop written using For.

  • Use Sealed Classes
    Classes that do not need to be inherited from should be marked as sealed. Sealed classed remove the inheritance features of a class and allows the .NET framework to make several run-time optimizations

Use Strongly Typed Arrays
strongly typed arrays avoids the type conversion or boxing associated with using object arrays to store types.

Object[] array = new Object[10]

 arr[0] = 2+3; //boxing occurs here

Avoid the boxing overhead by declaring a strongly typed array:

1

2

 int [] test= new int [10];

 test[0] = 2+3;

  • Use string.Empty

This is not so much a performance improvement as it is a readability improvement, but it still counts as code optimization. Try to replace lines like:

if (str == “”)

with:

if (str == string.Empty)

 

that’s some useful practices to embrace your code efficiency 😉

catch you In the next blog 😉 

Resources: 

http://weblogs.asp.net/psteele/archive/2004/01/27/63416.aspx

http://wlodarek.com/news/C–readonly-vs-const.aspx

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemTextStringBuilderClassTopic.asp

http://msdn2.microsoft.com/en-us/library/yz2be5wk.aspx

http://msdn.microsoft.com/vcsharp/programming/language/

http://blogs.msdn.com/csharpfaq/archive/2004/03/12/88420.aspx

 

 

Â