Wednesday, June 27, 2012

Learning Ruby on Rails for beginners

Well it has been a long time since I posted something here. Actually these days I'm pretty much occupied in gearing up for upcoming responsibilities. Soon, probably after a month, I would be back to student life from this hectic corporate job. I will be pursuing Masters in Computer Science with specialization in Programming Languages and Software Engineering. So that explains my inactivity from blog.

Meanwhile I would like to recommend/suggest a website to all fellow beginners who are looking for stuff to get start with learning Ruby , Rails programming languages.

Just go to Learn Ruby online. Even I'm learning the same.

Cheers !!

Wednesday, June 13, 2012

Naming your variables, methods guidelines (CS: Part 1)

We name variables, properties, methods, arguments, classes, namespaces, folders, files. Here are some simple naming guidelines:

1. Use Intention-Revealing names: The name of anything should answer all the big questions. It should reveal why it exists, what it does and how it should be used. If a name requires a comment then the name does not reveal its intent. e.g you should not use something like int a; // users count. instead use something like int currentUserCount; No comment required.
Also it is a good practice to create constant variables whenever you're using constant in methods. Such as instead of using condition like if(currentUserCount == 100) use if(currentUserCount == MAX_USER_COUNT) and create a constant MAX_USER_COUNT with 100 value.

2. Make Meaningful Distinctions: Sometimes you try to give same name to refer to two different things in the same scope but as compiler won't allow you to do it you try to do it by adding number series, noise words, misspelling just to satisfy compiler. But this is not a good practice. If names must be different then they should also mean something different.

3. Use Pronounceable Names: Coding in a team is like a social activity and you need to discuss your issues, approach with your colleagues. You should use pronounceable names in your code just in order to have a healthy discussion. Just imaging telling someone that "slcctrlct is incorrect in this module" instead of "switchlegControllerCount is incorrect in this module". This will surely help you instead of being part of a joke.

4. Use Searchable Names: Single-letter names and numeric constants have a particular problem in that they are not easy to locate across a body of text. One might easily find MAX_USER_COUNT instead of searching 100 everywhere in class. Likewise the name i is a poor choice for any variable for which a programmer might need to search. It is the most common letter and likely to show up in every passage of text.
The length of a name should correspond to the size of the scope
5. Avoid Hungarian Notation: Earlier we used to name our variable in hungarian notation like phoneString : a variable for phone of type string. But suppose we later change its type from string to PhoneNumber (which can be done very easily and quickly by IDE) then variable name would be same. Thus it would be
PhoneNumber phoneString; which has misleading information. So avoid these type of notations.

6. Naming Interfaces and their implementation: Consider you are creating a factory class which will provide you an object of particular type of instance. This factory will be an interface and will be implemented by a concrete class. So what should you name them? IObjectFactory or ObjectFactory. Well, it would be better to leave interfaces unadorned here. The preceding, I , so common in today's legacy wads, is a distraction at best and too much information at worst. We don't need to show users that we are using Interface for our factory class.

7. Class Names: Classes and objects should have noun or noun phrase names like customer, wikipage. Avoid words like Manager, Processor, Data or Info in the name of a class. A class name should not be a verb.

8. Method Names: Methods should have verb or verb phrase names like postUserClick, deletePage.

9. One word per concept: Avoid using the same word for two purposes. If you follow the "one word per concept" rule, you could end up with many classes that have, for example, an add method. As long as the parameter lists and return values of the various add methods are semantically equivalent, all is well.

10 Don't add gratuitous context. Say there is a particular feature developed by a developer named Ram then don't create any class like RamDiscoveringDevice.cs. Shorter names are generally better than longer ones, so long as they are clear. Add no more context to a name than is necessary.

Credits: Clean Code ebook

What is clean code, good code? (Coding skills)

Before starting lets check out why do we need clean code or in fact what is bad code which in turn necessitates clean code.

Bad Code: If you're a programmer then I'm sure you must have seen a piece of code in your application with a huge mess and gradually more and more features are added to that same piece and eventually code got worse and worse until code simply gets unmanageable.  We always try to find our way, hoping for some hint, some clue. of what is going on just to let things work as required but all we see is more and more senseless code. This is what known as bad code. We all feel the relief of seeing our messy program work and deciding that a working mess is better than nothing. At that moment we generally think we will come back to this piece and clean it up but according to LeBlanc's law :Later equals never. :)

Ironically we ourselves are the father of this bad code and we generally try to bemoan this thing to excuse like short deadline, managers, marketers, requirement changes etc. But do consider this:
The managers and marketers look to developers for the information they need to make promises and commitments. The users look to developers to validate the way the requirements will fit into the system. The project managers look to developers to help work out the schedule. The developers are deeply complicit in the planning of the project and share a great deal of the responsibility for any failures; especially if those failures have to do with bad code!! Most managers want good code, even when they are obsessing about the schedule. They may defend the schedule and requirements with passion; but that's their job. It's developer's job to defend the code with equal passion. Thus it is unprofessional for programmers to bend to the will of managers who don't understand the risks of making messes.
Clean Code:
Bjarne Stroustrup - "I like my code to be elegant and efficient. The logic should be straightforward to make it hard for bugs to hide, the dependencies minimal to ease maintenance, error handling complete according to an articulated strategy, and performance close to optimal so as not to tempt people to make the code messy with unprincipled optimization. Clean code does one thing well."

Beck's rules of simple code:
1. Runs all the tests.
2. Contains no duplication.
3. Expresses all the design ideas that are in the system.
4. Minimizes the number of entities such as classes, methods, functions.

"You know you are working on clean code when each routine you read turns out to be pretty much what you expected. You can call it beautiful code when the code also makes it look like the language was made for the problem."

The Boy Scout Rule: It is not enough to write the code well. The code has to be kept clean over time. We've all seen code rot and degrade as time passes. So we must take an active role in preventing this degradation. There is very simple rule:
Leave the campground cleaner than you found it.
If we all checked-in our code a little cleaner than when we checked it out, the code simply could not rot. The cleanup does not have to be something big. Change one variable name for the better, break up on one function that's a little too large or doing more than one thing, clean up one composite if statement. This practice will be very fruitful for the project over the time and eventually your application would be in very much stable instead of all pieces of crap every where.

In upcoming posts I'll brief about how you can make your code clean i.e. good coding practices. 

Tuesday, June 5, 2012

Good coding practices and guidelines, C#

While working on fixing FxCop errors I came across good code practices and guidelines, some of which I know earlier but would like to sum up here:

1. Do not declare visible instance fields
The primary use of a field should be as an implementation detail. Fields should be private or internal and should be exposed by using properties. Accessing a property is as easy as accessing a field and the code in a property's accessors can change as the type's features expand without introducing breaking changes. Properties that just return the value of a private or internal field are optimized to perform on par with accessing a field; there is very little performance gain associated with using externally visible fields over properties.Externally visible refers to public, protected, and protected internal accessibility levels.

2. Mark members as static
Members that do not access instance data or call instance methods can be marked as static. After you mark the methods as static, the compiler will emit non-virtual call sites to these members. Emitting non-virtual call sites will prevent a check at runtime for each call that ensures that the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue

3. Do not decrease inherited member visibility 
You should not change the access modifier for inherited members. Changing an inherited member to private does not prevent callers from accessing the base class implementation of the method. If the member is made private and the type is unsealed, inheriting types can call the last public implementation of the method in the inheritance hierarchy. If you must change the access modifier, either the method should be marked final or its type should be sealed to prevent the method from being overridden.

4. Do not expose generic lists
System.Collections.Generic.List<T> is a generic collection designed for performance not inheritance. System.Collections.Generic.List<T> does not contain virtual members that make it easier to implement new behaviors. The following generic collections are designed for inheritance and should be exposed instead of System.Collections.Generic.List<T>.
  1. System.Collections.ObjectModel.Collection<T>
  2. System.Collections.ObjectModel.ReadOnlyCollection<T>
  3. System.Collections.ObjectModel.KeyedCollection<TKey, TItem>

To fix a violation of this rule, change the System.Collections.Generic.List<T> type to one of the generic collections designed for inheritance.

5. Do not ignore method results
Issues: Either one of following comes under this issue category
1. A new object is created but never used.
2. A method that creates and returns a new string is called and the new string is never used.
3. A COM or P/Invoke method that returns an HRESULT or error code that is never used.

Why these are considered as issues: It makes you aware of circumstances such as:
1. Unnecessary object creation and the associated garbage collection of the unused object degrade performance.
2. Strings are immutable. Methods such as ToUpper return a new instance of a string instead of modifying the instance of the string in the calling method.
3. Ignoring an HRESULT or error code can lead to unexpected behavior in error conditions or to low-resource conditions.

How to fix: (Fixes mentioned in order to issue description)
1. If method A creates a new instance of B object that is never used, pass the instance as an argument to another method or assign the instance to a variable. If the object creation is unnecessary, remove it.
2. Method A calls method B but does not use the new string instance that method B returns. Pass the instance as an argument to another method, assign the instance to a variable, or remove the call if it is unnecessary.
3. Method A calls method B but does not use the HRESULT or error code that the method returns. Use the result in a conditional statement, assign the result to a variable, or pass it as an argument to another method.


Monday, June 4, 2012

Do not initialize unnecessarily, C#

The common language runtime initializes all fields to their default values before running the constructor. In most cases, initializing a field to its default value in a constructor is redundant, which degrades performance and adds to maintenance costs. One case where it is not redundant occurs when the constructor calls another constructor of the same class or a base class constructor and that constructor initializes the field to a non-default value. In this case, changing the value of the field back to its default value can be appropriate.

Collection properties should be read-only, C#

It is recommended that your collection property should be read only i.e. they should not contain setter. A writable collection property allows a user to replace the collection with a completely different collection. A read-only property stops the collection from being replaced but still allows the individual members to be modified.

If you actually want to replace the collection then the preferred design pattern is to include a method to remove all the elements from the collection and a method to re-populate the collection. Instead of setter property use Clear and Add methods of collection in order to replace the complete collection.

This error is reported by code validation tools like FxCop.

Sources: MSDN Collection properties should be readonly.

Friday, June 1, 2012

SuppressMessage attribute not working, FxCop

FxCop 1.35+ versions have the ability to suppress messages in code using ‘SuppressMessage’ attribute. This attribute Suppresses reporting of a specific static analysis tool rule violation, allowing multiple suppressions on a single code artifact.

For example: Suppose you have a class

public class UtilityFunctions
       [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
       public string GetMachineCurrentLocation()
          // logic to fetch location using GetUserGeoID & GetUserDefaultLCID etc
           return machineLocation;
In the above example, we've suppressed the UsePropertiesWhereAppropriate violation for the GetMachineCurrentLocation method so that FxCop no longer will raise it. Some advantages of using this:
1. Other developers in your team can quickly see that an obvious violation has been suppressed.
2. Unlike in-project suppressions, changes to the namespace, type or signature of a member (ie name, return type, etc) do not require the SuppressMessage attribute to be updated.

Issue: Using Suppress Message first time won't work in fxcop. Even after adding suppress message, violation errors are still logged in FxCop.

Fix: While using in-code violation suppression first time, it can be confusing as to why FxCop seems to ignore these attributes. The SuppressMessage attribute is what is called a 'conditional' attribute. A conditional attribute is an attribute that is only included in metadata of your assembly if a certain compilation symbol is defined at compile time. 
The SuppressMessage attribute itself requires the CODE_ANALYSIS symbol to be present and by default, this is not included in non-team system projects. That's why FxCop continues to report errors.

To define this symbol, do the following in Visual Studio:
  1. In Solution Explorer, right-click your project and choose Properties.
  2. In the Properties window, choose the Build tab.
  3. In the Conditional compilation symbols text box, enter CODE_ANALYSIS

Hope this will fix your issue.