In class we usually declare global variables and local variables. I have most of the time seen declaring global variables, setters ,getters. Are these essential everytime?Is it ok if I can implement it without using those things?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Generally you should always try to reduce the scope of visibility of variables, methods, classes etc.
So, if you need some variable that is used in one call sequence use local variable and method arguments to pass its value from method to method.
For example I have 2 methods
foo()andbar()whilefoocallsbar:Let’s say both work on the same string appending to it some suffixes. You can use local variable as in the following example:
Or class level variable:
The first way is better because:
The second implementation is not encapsulated: one can add code that changes the object state and affects on the next call of
foo(). You have to go back and forward in you class to understand both algorithm and what variables are affected by algorithm. It is not thread-safe. Two concurrent threads running the same code may compete on changing the same variable.