Tuesday, August 26, 2008

Shallow Copy vs Deep Copy in .NET

hi Developers ,

in that post, i am describing the difference between shallow and deep copy by the use of C# language.

shallow and deep copy are used for copying data between objects.

Shallow Copy:

creating a new object, and then copying the nonstatic fields of the current object to the new object.

If a field is a value type --> a bit-by-bit copy of the field is performed

If a field is a reference type --> the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object.

in C# and VB.NET, shallow copy is done by the object method MemberwiseClone()

Example:

the following are clsShallow class to be cloned which include value types (like Age) and ref types (like EmpSalary is a class)

public class clsShallow
{
public static string CompanyName = "My Company";
public int Age;
public string EmployeeName;
public clsRefSalary EmpSalary;

public clsShallow CreateShallowCopy(clsShallow inputcls)
{
return (clsShallow)inputcls.MemberwiseClone();
}
}
public class clsRefSalary
{
public clsRefSalary(int _salary)
{
Salary = _salary;
}
public int Salary;
}

now, let us debug and trace the outputs to do the shallow copy by the use of CreateShallowCopy() method

first, use the following code to call the CreateShallowCopy method from other classes

// Creates an instance of clsShallow and assign values to its fields.
clsShallow objshallow = new clsShallow();
objshallow.Age = 25;
objshallow.EmployeeName = "Ahmed Eid";

// add the ref value to the objshallow
clsRefSalary clsref = new clsRefSalary(1000);
objshallow.EmpSalary = clsref;

// Performs a shallow copy of m1 and assign it to m2.
clsShallow m2 = objshallow.CreateShallowCopy(objshallow);

// then modify the clsref salary value to be 2000
clsref.Salary = 2000;

// so the m1 object salary value become 2000
int EmpSalary = objshallow.EmpSalary.Salary;

After assigning the values (value and ref types ones) to the object objShallow and before doing the shallow copy
the values are : (for the current object value)
Age : 25 (value type)
EmpSalry: has salary value of 1000 (ref type)

shal1

then do the shallow copy and modify the value of clsref.salary ,reference field type, then check the values of m2 , new created object. (ref and value fields) again

shal2

the values are : (for the new created object)
Age : 25 (value type) a new copy of the objShallow object
EmpSalry: has salary value of 2000 (ref type) a refernce to objShallow.EmpSalry object, which is also referenced to the clsref object.

Note: values of m2.EmpSalry and clsref are the same after modifying the clsref values. (reference type concept)

Deep Copy:
creating a new object, and then copying the nonstatic fields of the current object to the new object.

If a field is a value type --> a bit-by-bit copy of the field is performed
If a field is a reference type --> a new copy of the referred object is performed.

Note: the classes to be cloned must be flagged as [Serializable]

Example:

the following are clsDeep class to be cloned which include value types (like Age) and ref types (like EmpSalary is a class)

[Serializable]
// serialize the classes in case of deep copy
public class clsDeep
{
public static string CompanyName = "My Company";
public int Age;
public string EmployeeName;
public clsRefSalary EmpSalary;
public clsDeep CreateDeepCopy(clsDeep inputcls)
{
MemoryStream m = new MemoryStream();
BinaryFormatter b = new BinaryFormatter();
b.Serialize(m, inputcls);
m.Position = 0;
return (clsDeep)b.Deserialize(m);
}
}

[Serializable]
public class clsRefSalary
{
public clsRefSalary(int _salary)
{
Salary = _salary;
}
public int Salary;
}

now, let us debug and trace the outputs to do the deep copy by the use of CreateDeepCopy() method

first, use the following code to call the CreateDeepCopy method from other classes

// Creates an instance of clsDeep and assign values to its fields.
clsDeep objdeep = new clsDeep();
objdeep.Age = 25;
objdeep.EmployeeName = "Ahmed Eid";

// add the ref value
clsRefSalary clsref = new clsRefSalary(1000);
objdeep.EmpSalary = clsref;

// Performs a shallow copy of m1 and assign it to m2.
clsDeep m2 = objdeep.CreateDeepCopy(objdeep);

// then modify the clsref salary value to be 2000
clsref.Salary = 2000;

// so the m1 object salary value become 2000
int EmpSalary = objdeep.EmpSalary.Salary;

After assigning the values (value and ref types ones) to the object objDeep and before doing the deep copy

the values are : (for the current object value)
Age : 25 (value type)
EmpSalry: has salary value of 1000 (ref type)

deep1

then do the deep copy and modify the value of clsref.salary ,reference field type, then check the values of m2 , new created object. (ref and value fields) again

deep2

the values are : (for the new created object)
Age : 25 (value type) a new copy of the objDeep object
EmpSalry: has salary value of 1000, a new copy of the objDeep object

Note: values of m2.EmpSalry and objDeep.EmpSalary are not the same as deep copy creates a new object of the reference type (objDeep.EmpSalary) in m2.EmpSalry. but clsref and objDeep.EmpSalary are the same (Refernce type concept)

With the help of Google I found a very smart method for performing deep copy. Its performance is good than the one i used on that post.


/// <summary>
/// Using generics will solve some performance issues
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="item"></param>
/// <returns></returns>
public static T DeepCopy<T>(T item)
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, item);
stream.Seek(0, SeekOrigin.Begin);
T result = (T)formatter.Deserialize(stream);
stream.Close();
return result;
}

i hope that post help you to deeply understand the difference b/w shallw and deep copy in .NET

Ahmed Eid

Sunday, August 24, 2008

Code Review Checklist

By the use of coding standards as i disscussed here View , developers can review their tasks using the following check list:

.NET Coding Standards

Hi .NET developers and team leaders,

According to my practical work on Microsoft Visual Studio.NET, it were obligated to use standards for coding, design and implementation. I readed carefully about standards and naming conventions from multiple sources and summarized it then added some modifications to unify our .NET development among the team.

This topic defines some of the standards related to the formatting, naming conventions, and organization for any code written for software development.

All developers implementing HTML, Active Server Pages (ASP) and .NET application should comply with the standards outlined below. Also, each Development manager should strictly enforce these standards during all phases of application development. This document should be used as a guiding principle during all source code reviews and sign-off.

the following are some headlines of our coding standards to be discussed here:

  1. Documentation
  2. Naming Conventions
  3. Hints and Remarks

OK, lets start describing the following items:

  1. Documentation

You should know that work on a team and may be you leave them for another company, so you should document your work task by task. I followed a lot of problems to understand friends' code on my team after moving to another company. Story

I were working on Human resource management system on my company, and after movement of some colleagues to another company i faced difficulty to understand their codes especially the ones which are not documented. so i asked from my team leader to re-implement some works of it and he approved my point.

///////////////////////////////////////
/// creator name: Ahmed Eid
/// creation date: 1 jan 2008
/// description : Handles the submittion of Adduser.aspx
/// edited By : Hany Mohamed
/// updated date: 2 feb 2003
/// reason for update: fixing number over flow bug
///////////////////////////////////////

Note: if developers use visual source safe or TFS , it will be easy to track the changes of file modifications.

  • In line Comments developers should document methods and each line code need to documented within classes.

    Method documentation:
/// <summary>
/// Here is the description of method functionality
/// </summary>
/// <param name="Param1">describe each param usage</param>
/// <param name="Param2">describe each param usage</param>
/// <param name="Param3">describe each param usage</param>
public void DoSomeThing(int Param1,string Param2,out int Param3)
{
// do somethiong method
}

Note: if you finished method signature, only write /// on the line above your method to prepare the documentation as above.

Inline documentation:

if the code lines need to be described, you must do to be reference for all of reviewing that code ( may be you return back to your code but you could not understand it smile_regular )

2. Naming Conventions

visual studio.NET

    • Files Name Files should be named a descriptive name and they should not be named with numbers for example: submitorder1.asp , submitorder2.asp … Descriptive file name samples:


    • adduser.aspx
    • viewUserDetails.aspx
    • viewAccoutStatus.aspx
    • reportUsersPerCountry.aspx
    • For shadow pages(pages that execute code on the server and redirects the user) acAdduser.aspx (ac is for action)reGenerateAccessXML.aspx

According to the use of DNN we will add a prefix [ mod_ ] to user controls names if this UC will be defined as DNN module Ex. Mod_ adduser.ascx

    • Files Structure A well structure should always be in place; the files should not all be under one folder. Structure can be defined according to factors:
      • Based on application business purpose normally for public site
    • / (Root)

      • Product-X
        • Admin
          AddUser.aspx
          • EditUser.aspx
          • ....
        • Registeration
          • Register.aspx
          • Confirm.aspx
          • EditUser.aspx
          • ....
      • Product-Y
        • ...
      • Component-X (may be other .NET application added to solution)
        • ...
      • Reports
        • ...
      • ...etc

    • Class Name: Class Names should be Nouns and the First letter of the class name should be Caps and the rest of the name should be small.

Samples:

  • Connection (good old ADO connection)
  • User
  • Product This class names shows that a class is an entity that performs an action. Not the action itself.

Hence class names like these

  • ManageUsers
  • DbFunctions

Naming above gives the idea of something wrong in the design/implementation itself.
Correct naming is:

  • Users or UserManagement
  • DbAccessLayer

This case pplies on everything (almost) except for the static classes like those who has global functionality. And supports other class

    • Methods Names Methods Names should be verbs and it should be written with the Camel Naming convention system which is to write every first letter of the name with CAPS and the rest small without the verb itself example: GetUserInfo(), GetUserPassword()
    • Variables

    ° Variables name should never be x , y, z or i or any other chars that are not descriptive.

    ° Variables names should consists of the first letter of the variable type and the rest should be the use of the variable

    ° Variables name should be written using the Camel Naming convention system. Example: iUserId, sUserName

    ° Boolean Variables should be Positive sense Names example: isEmpty, isActive

    integer --> iUserId
    double --> dBasicSalary
    string --> sName
    float --> fPercent
    ..... and so on

    Note: you can customize your naming conventions as you like you must keep that standard among team. you may write string as strName

    • Control Names The following list of Control Names is to be used when creating names for HTML elements, Control names. When naming an element, the prefix is concatenated with a unique name for the element.

      Label --> LblCountryName
      TextBox --> txtCountryName
      CheckBox --> chkCountry
      Optionbox --> optCountry
      drobdownlist --> ddlCountry
      Combobox --> cmbCountry
      ListBox --> lstCountry
      Button --> btnCountry
      TreeView--> trvCountry
      ListView --> lstvCountry
      Progressbar --> pbCountry
      DataGrid --> dgCountry
      Repeater --> rptCountry
      DataList --> dlCountry
      Image --> imgCountr
  • Database
  • Tables

    - Tables’ names will not start with any initials but rather with the name right away.
    For example: Customers instead of [Database prefix]_TableName. like : hr_ Employees - Tables’ names should not contain any spaces whatsoever (all spaces should be replaced with underscores).
    - Tables’ names should be plural when applicable. For example: Users not User, Customers not Customer. · All tables’ names should be descriptive.
  1. Table Fields
    • pfk = primary foreign key & lfk = logical foreign key
    • All fields’ names should be descriptive
    • For the identity it will be AutoId For the foreign key it will be prefix_fieldName
      • The foreign key from another table of the current database will be pfk_CustomerId

      • The foreign key from another database table or external file structure like XML,..etc will be lfk_userI
    • Fields names should not contain any spaces whatsoever (all spaces should be replaced with underscores)
  2. Views
    • All views’ names should be descriptive
    • All views names should start with database prefix For example: hrvw_Employee
  3. Stored Procedures
    • All stored procedures’ names should be descriptive
    • All stored procedure names should start with a database prefix instead of SP since system stored procedures start with sp. For example: hr_AddEmployee

    and so on .....

    3. Hints and Remarks

    • Avoid Late Binding
    • Use StringBuilder class for string manipulation (don’t use string class)
    • Web Development should also Cache there Page
    • Developer has to use the .NET field validation for each of the following validation
      • Mandatory
      • Email format
      • Phone Format
      • Range like the age range
      • Password and password confirmation Comparison
    • Errors messages:
      • Should be spell checked
      • Should be in a proper and consistent format
      • Correct messages are displayed for each condition
      • Messages useful & meaningful for the user (e.g. “Driver error 80004005” will not be understood by a normal user)
      • Different errors are handled by different messages (invalid data types & entry length can not have the same message)
      • All Javascripts and VB scripts should be in one block in the beginning or the end of the file
      • All HTML tags should be small letters
      • Any developer using .NET should use regions when ever possible to have a better and easier look at his code

these are some coding standards we use on .NET environment development. so you could follow them or customize it to match your case.

if you have any inquiry about that topic, please don't hesitate to contact me at aes_fci@hotmail.com

Thanks

ANTIQR26
By: Favoshots
Views: 0
ANTIQR27
By: Favoshots
Views: 0
ANTIQR29
By: Favoshots
Views: 0
ANTIQR31
By: Favoshots
Views: 0
ANTIQR32
By: Favoshots
Views: 0
ANTIQR33
By: Favoshots
Views: 0
ANTIQR34
By: Favoshots
Views: 0
ANTIQR37
By: Favoshots
Views: 1
ANTIQR38
By: Favoshots
Views: 1
ANTIQR40
By: Favoshots
Views: 1
ANTIQR41
By: Favoshots
Views: 1
ANTIQRA
By: Favoshots
Views: 1
ANTIQRA2
By: Favoshots
Views: 1
ANTIQRA3
By: Favoshots
Views: 1
ANTIQRA4
By: Favoshots
Views: 1
ANTIQRA5
By: Favoshots
Views: 1