Monday, July 22, 2013

Is Reflection breaks Encapsulation

"Today, I learn a big lesion  that what ever we know isnt surely only truth. We may know what is true but there may be other true that are different from what we know. And sometime no one tells us that what is truth either because they dont know them selves or we might be not a level to understand that."

Whatever i write down above is just what i felt about knowing that we can call or access private members of class regardless of that can break the concept of encapsulation.

So as i told you reflection can used to access private members.Let assume we have a class Cat.
For eg.

 public class Cat
    {

        private int NoOfLegs = 4;
    }

now we will use to reset the value of NoOfLegs using reflection.

   Cat c = new Cat();
            Type  t= typeof(Cat);

            t.GetField("NoOfLegs", BindingFlags.Instance | BindingFlags.NonPublic)
         .SetValue(c,567);
            Console.Write(t.GetField("NoOfLegs", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(c));
            Console.ReadLine();

So myth creaked  that reflection cant access private members.

"So If some is saying that private members aren't accessible by outside you can prove him/her wrong".

As explained above encapsulation is a design technique to make design clean and structured. If some wants to take full responsibility by changing private members he is on risk of getting exception.
For eg someone can set value to null using reflection so our job as developer is to make sure we are handling null and throwing exception. As we cannt trust on other developers or user of providing expected inputs.
This solution is provided because we may need to test private member of our class.

Dynamic:

Somehow Dynamic datatype is popular as alternative of reflection but it isnt. Dynamic datatype allows as to check property and fields are runtime. Some rules remain unbreakable like object of a class can access only public members of class.
So if someone is thinking to do something similar we did with reflection then he must be ready to get unhandled exception like RuntimeBinderException With msg"'RefdynEncApp.Cat.NoOfLegs' is inaccessible due to its protection level ".


Happy Living...
Happy Coding....
Happy Concepts...





No comments:

Post a Comment