Accessing static variables in a test package - java

I am working on a project in NetBeans and my project is made using JavaFX,Java and mysql. I have a controller class for every display page(fxml file) that has some static variables. When I try to access those static variables anywhere within the source package I successfully get their current values but when I try doing so from the test package it returns a null value or zero value. I am writing some junit tests and I need those current values of the static variables as the tests test those values.What should I do? Any suggestion would be helpful.
To be specific I have two display pages that calculate salary of an employee -one takes input from the user such as basic salary, other allowances and it's controller class stores those values in static variables accessed in the second page controller class to calculate net salary. The variable basicsalary shows zero value in the junit test class at the same time shows the correct value when accessed in salary2 class(the display page controller). I wish to access it's current value in the test class as well.

You could copy the static values in your tests also. This will make your code more safe (for example if someone modified a static constant without wanting that, the test will fail).
That being said, you should have access to static variables in test classes as long as code compiles. Are the values assigned in another context? (like system variables, server startup...)

Related

Get the static variable values of a class

I have a spring application deployed in tomcat. The application has a class (ClassWithStaticFields)with some static fields. I need to get the values of these static fields either from heap dump or from another external class(by manually placing the new class in the path of ClassWithStaticFields)
The external class when it tries to access the static field a null value is shown. I think this is because the process which started and loaded the static fields and the new class process are different.
The heap dump doesn't have any information about the class itself.
SELECT s.#staticFields FROM "com.ClassWithStaticFields" s
gives Your Query did not yield any result.
I am expecting to get/view the value of static field of a class which is deployed in tomcat. I do not want answer to suggest to put a logger/sysout/print statements.
If you need to know the static fields value in a class, first you need to know the class name. If you know the class name it would be easy then. ClassName.StaticField will give you the result.

Getting static values from class in android

Static variables or static method can be called without creating its class instance. Which means its values are same for all objects or any reference to that class. Does it mean we can get static values from class anywhere in our project.
In my case when user login I get all of the profile information and assign it to static variables in UserProfile.java class. Can these values be accessed anywhere in my project.
I don't want to use Shared-preferences or SQlite for storing this data.
Yes, static variables can be accessed directly from the class' name (MyClass.myVariable), as long as their access policy permits it.
Static variables are accessible directly from class without creating an object of class.
Variables you want to access must be public
you can simply access them like
YourClass.yourVariable
If those static values are public then you can access them from wherever you can access your class.
However, you cannot access classes across different modules, so to make that happen , you have to add compile project(':project_name') in your dependencies inside your gradle file.

Field to local or global variable

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.

static variables Vs application variables

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.

Static vs Instance for Global state variable

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.

Categories

Resources