Solved

Theory Question

Posted on 2015-02-12
3
121 Views
Last Modified: 2015-02-12
Greetings,

I am working through someone else's code and learning as I go.  I came across this pice of code and I wonder why would I write this?

private static int EXPECTED_LENGTH_OF_BYTE_ARRAY = 998;
        public static int expectedLengthOfBHMConfigurationArray
        {
            get
            {
                return EXPECTED_LENGTH_OF_BYTE_ARRAY;
            }
        }

Instead of calling expectedLengthOfBHMConfigurationArray and having a 998 returned would it not be more efficient to reference the variable EXPECTED_LENGTH_OF_BYTE_ARRAY directly?
0
Comment
Question by:RonWensley
3 Comments
 
LVL 44

Assisted Solution

by:AndyAinscow
AndyAinscow earned 250 total points
ID: 40605255
For reading - yes.
BUT if you look very carefully there is no way an external can modify this value.  If it was a public variable then other parts of the program could modify the value with possibly disastrous effects.
0
 
LVL 43

Accepted Solution

by:
Chris Stanyon earned 250 total points
ID: 40605337
One of the key principles of Object Oriented code is encapsulation. As Microsoft puts it:

This principle states that data stored inside an object should be accessible only to that object.

Your EXPECTED_LENGTH_OF_BYTE_ARRAY variable is a private field and is only accessible inside the class. It is then exposed to the outside world via a public property - expectedLengthOfBHMConfigurationArray in your case.

This means that consumers of your class will get to the value via a public property. You have the flexibility to change the implementation of that property within your class without breaking the code of the consumers.
0
 

Author Closing Comment

by:RonWensley
ID: 40605676
Both answer were informative thank you for them.
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
"Disruption" is the most feared word for C-level executives these days. They agonize over their industry being disturbed by another player - most likely by startups.
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

825 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question