Sunday, December 27, 2009

What are the benefits of making data private in Object Oriented programming?

My teacher wants to know 4 out of the 6 benefits of it but i cant seem to find them in the book or around the webz at all.





Can anybody help? It should be related to pseudocode or any other form of programming.





thankz babezzWhat are the benefits of making data private in Object Oriented programming?
1 : stops other classes directly accessing and interfering with data from that class.





2 : restricts accidental access





3 : it enables a structure of data hierarchy





4 : restricts inheritance and aggregationWhat are the benefits of making data private in Object Oriented programming?
1. Reduces coupling - Your code may break if other code's implementation changes.





e.g.





class Bar { int size; }


class Foo { void method() { new Bar().size; } }





Your code will break if the member ';size'; is removed from bar. You should use accessor methods. Now, take for example





class Bar { private int size; public int getSize(){return size;}}


class Foo { void method() { new Bar().getSize(); } }





Now you can do whatever you want to ';Bar'; as long as it doesn't remove getSize(). Ultimately, by making your members private your forced to use accessor methods and your code will be more maintainable when your forced to make implementation changes.





2. Encapsulation - Programmers can't see implementation details. Hackers can easily break your code.They might be able to find a loop hole in your code.


Consider the following code:





class Example {


public static void main(String[] args) {


Outer.Inner in = new Outer().new Inner();


in.changePrivateMember();


}


}





class Outer {


private int member;


class Inner {


void changePrivateMember() {


member = -1;


}


}





}





The inner class or its method should have been private.





3. Enforces data integrity - Programmers can change your data freely.
Declaring some of the object's fields private prevents them from being modified directly by code using the object. Private fields can only be modified by the object's methods. This gives you the freedom to change how the object stores its data later on and still maintain compatibility with existing code.

No comments:

Post a Comment