I have a doubt about which option would be a better one in order to have a more understandable code. I have a variable that will be used just inside one method but, as this variable is a configuration variable, I think that it would be nice that this would be a global one. So I have created it on the top of the class as:
private final int VARIABLE = 5000;
But then, as this variable is used just once, the Android Studio launches a warning that says "Field can be converted to a local variable". Do you think that is better to keep this variable as a global one (in order to be more clear for the future) or it is better to set it as a local variable?
Thanks in advance!
Keep all your variables which are not going to change, for example base url strings etc in a separate java file in a separate package like Utils. Place all your variable there and make them static so that you can directly access them by using the class name.
Related
Is there a way to get values of local variables in one class and show that in jsp page?
For example,
public class a {
public method b() {
String c;
I want to use the String c and show it in jsp page.
${c}
1) Is there a way to use a local variable of a class from outside of that class?
2) if not, just make the variable global, and use it? ( What I mean by global is using static. I looked it up and Java doesn't have global variable)
3) if so, in JSP page, can you tell me some ways to show that value?
${class.variable name} <--- Would this work as well?
1) No. A local variable is not visible from outside the block where it is defined.
2) + 3) Theoretically, yes. Anyway, I would not recommend this unless you really know what you are doing. Solutions like the one in the link should be very exceptional, because they go against the best practices.
I am programming in Java. I know it probably doesn't matter much on modern, fast computers, but when you create an object from a class used multiple times, is it preferable to declare method-specific variables within the methods, where it will be declared every time the program is run, or within the class?
Method-specific variables (variables which using is bounded by one method only) should be without any doubts declared within the method where they are used. It basically has nothing with the performance, but it's all about design, readability and OOP principles according to which you should not expose details of your implementation.
I suggest you show the code you are writing, otherwise trying to guess is error prone, and you are going to be hugely downvoted.
If a separate copy of the variable is needed for each instance, then it should be an instance variable. An example might be creating a separate copy of length and width variable within the Rectangle class.
If you are creating a variable that is not tied to an instance, it can be a local variable (method variable). The swap method is a good example. If you are swapping two indexes in an array a temporary variable can be created to hold the value of first index.
I just want to see what you guys might think the difference (in terms of usage, efficiency, or even good practice) with regard to android development.
If I use a static variable in one of my base activity (so its single instance and be access everywhere), as opposed to using a non static variable in my application subclass (which is a single application class for all the activities).
Both will achieve the same end results if you try to use a global variable.
I was using the static one then I moved to use the application subclass (in case you guys wonder "what is it I am using for", I wanted to play background music and control it from everywhere and I don't wish to use service for certain reasons).
Any help clarifying the best way to ?
It depends on use also, suppose if you are using
android:process
for some reason in your Activity or anything else in your Manifest file your static value will be reset and you will get the initial value assigned to static variable. In that case you can use SharedPreference or Application class.
Because if you use android:process for any particular Activity then that Activity will run in another process and as we know that in Android every Application runs in its own process.
Other than this I don't see there is much issue using static. But, personally I would prefer Application class as Android has it for global variables.
During the execution of a program, each variable has its own time within which it can be accessed. This is called the lifetime of the variable.
Instance variables:
Instance variables are class members. Every time you create an object from a class, a brand new copy of these instance variables is created for this object. Actually, creating an object from a class means, partially, creating copies of instance variables for that object. So each object has its own copy of instance variables which exist as long as the object they belong to exists. The values of these variables constitute what we call: the state of the object.
Static variables:
Static variables are also members of a class but can't belong to any object created from that class. So created objects from the class don't get their own copies of static variables. Therefore static variables are created only when the class is loaded at runtime. The existence of static variables is dependent only on the class itself. As a result, a static variable exists as long as its class exists.
One of main difference between these two variable is that when you are calling System.gc(); your instance variable is set to null while static variable will never set to null by calling gc.
I have a global boolean variable which I use to disable all trading in my financial trading system.
I disable trading if there is any uncaught exception or a variety of other conditions (e.g. no money in account).
Should this variable be static or an instance variable? If its an instance I will need to add it to constructors of loads of classes...Not sure if its worth the hassle.
Thxs.
If it's an instance, then you probably want it to be a Singleton, and you'll provide a public static getter (or a factory, or DI if you care about testing).
If you access it from multiple threads, then it'd better be an AtomicBoolean in both cases.
Throughout your entire career, the number of times that you will have a valid use for a global variable will be countable in the fingers of one hand. So, any given time you are faced with a "to global or not to global" decision, most chances (by far) are that the correct answer is NOT. As a matter of fact, unless you are writing operating system kernels and the like, the rule of thumb should be "do not, under any circumstances, make any variable whatsoever, anywhere, anytime, global."
Note that wrapping access to a global variable in a global (static) method is just fooling yourself: it is still just a global variable. Global methods are only okay if they are stateless.
The link provided by #HermantMetalia is a good read: Why are static variables considered evil.
In your case, what you need is probably some kind of "Manager" object, a reference to which you pass as a construction time parameter to all of your major logic objects, which, among other things, contains a property called "isTradingAllowed" or something like that, so that anyone interested in this piece of information can query it.
I'd put it in a static field. But prefer to make it an AtomicBoolean to prevent threading issues :-)
public class TradeMaster {
private static final AtomicBoolean TRADING_ALLOWED = new AtomicBoolean(true);
public static void stopTrading() {
TRADING_ALLOWED.set(false);
}
public static boolean isTradingAllowed() {
return TRADING_ALLOWED.get();
}
}
Static Pros:
No need to pass references to instance to every class which will be using this
Static Cons:
May lead to difficult in testing - I think it should be fairly easy to test a static variable if you set the state of the variable before and after the test (assuming the tests are not running concurrently).
Conclusion:
I think the choice here depends on what your view of testing static variables is...For this simple case of one variable managing the state I really cant see the problem with using static. On the otherhand...its not really that hard to pass an instance to the constructors of the dependent classes so you dont really have any downside when using the instance approach.
It should be static since it will be shared by all the instances of
this class.
It should be static since you dont want to have a separate variable for all the objects.
Given that I would suggest that you read some good resources for static variable usage they work like charm unless you mess them..
If you want to make a variable constant for the class irrespective of how many instances are creted then use static method. But if the variable may change depending on the use by different instance of class then use instance variable.
Example
*
Here is an example that might clarify the situation. Imagine that you
are creating a game based on the movie 101 Dalmations. As part of that
project, you create a Dalmation class to handle animating the various
Dalmations. The class would need instance (non-static) variables to
keep track of data that is specific to each Dalmation: what its name
is, how many spots it has, etc..
*
But you also need to be able to keep track of how many Dalmations have
been created so you don't go over 101. That can't be an instance
variable because it has to be independent of specific Dalmations. For
example, if you haven't created any Dalmations, then this variable has
to be able to store zero. Only static variables exist before objects
are created. That is what static variables are for - data that applies
to something that is beyond the scope of a specific instance of the
class.
I read that Java provides default values to class properties, but not to local variables. Is that correct?
If so, what is the reason behind this? When you are doing something good, why not do it all the way?
Standard local variables are stored on the stack and aren't actually created until they are initialized. If a local variable isn't used, it doesn't go on the stack. Member variables, however, are allocated in the heap, and thusly have a default placeholder (null reference or default primitive).
The non-technical reason behind may also be the following one:
If you declare a local variable, you do this in order to use it. And usage is connected with assigning a value. Therefore, accessing a declared, but not initialized, variable does not make that much sense - the programmer might simply have forgotten to initialize the variable.
Fields, however, might only be used until or after a specified point in the object's lifetime. Forcing the programmer to initialize them all would not be good.