Alternative to delcare global variables in Java [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
After reading global-variables-in-java, I found it's not suggested to declare global
variables. However, what's a better approach if I want to declare constant variables viewed by all methods in all classes. How to make those variables' scope global? How and why, thank you!

if I want to declare constant variables viewed by all methods in all classes
If those are really constants, then public static final fields are perfectly fine.
What kind of data is this? Does it need to externally configurable (at run time or build time)? Does it need to computed at application startup? Does that computation require external resources (such as files or networks) that may be unavailable or slow?
Well, the variables are indicating the state, in different drawing state(draw, erase...).
Not sure I understand what that means exactly, but maybe you want to define an enum?
I don't want to pass lots of parameter each time
That is a bad argument to use global variables.
Maybe you want to combine multiple arguments in a holder object?
Or have stateful objects with methods (as opposed to stateless functions that take many parameters).
But I still have to new a class containing these constants.
No. You can do
public final class MyConstants{
public static final String MY_OAUTH_KEY = "ABCDEFGH";
// maybe this should come from pom.xml
public static final String APP_VERSION = "0.0.1";
}
and then use it from anywhere in your code
System.out.format("You are running version %s%n", MyConstants.APP_VERSION);

Related

Static methods or empty constructor [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
As someone who is learning Java I find it hard to pick whether I should create class with empty constructor or making all her methods statics.
If I’m having a class without properties that read files and doing operations on the data and Being called only one’s shout it be static or have empty constructor.
Because I need to call only one method from the class (and he calls the rest) should I make all methods static or should I call her by creating empty object ?
Actually it would be a private constructor, not empty as you don't want to instantiate the class. But here are a couple guidelines.
Create static methods that don't require accessing instance fields but do some computation. An excellent example of this is the Math.class
Instance methods are used when accessing instance fields and possibly changing then. Getters and setters are good examples. Sometimes private helper methods can be declared static.
But don't use static methods as the fundamental type or because they are easier to use (i.e. work in static or non-static context). They are contrary to the concept of OOP.

Issues related to declaration of private constructor in a class [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm new to Java.
I was reading about Encapsulation concept in Object Oriented Programming.
While reading, I saw a line telling that :
If constructor of a class is declared as private, it will cause some
problems.
But it didn't tell what kind of problems could occur.
Can anyone tell what kind of problems are there with private constructor ?
When you declare a constructor of a class as 'private', you will not be able to create new instances "objects" of that class.
This is a problem if you do want to create new instances of the class, but this implementation is useful when making a Singleton Design Pattern.
If you are interested in knowing more about design patterns, I can share some resources with you.
Here is a book by Carlos E. Otero that covers the topic of design patterns:
https://books.google.com.tr/books?id=IL6FBLJn69UC&printsec=frontcover&redir_esc=y#v=onepage&q&f=false
Simple words, object or instance can't be created for that class.
As soon as, you write this statement below. For example
SomeClass c = new SomeClass(); // this will give an exception.
Basically, private constructors are used for making singleton classes.
On declaring a constructor as private you can't instantiate the class using default constructor. So, you need to create a constructor with public to access it outside.

Why Not Use Instance Objects Instead of ThreadLocal in Java? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I was reading this article about ThreadLocal objects in Java in an attempt to understand why and when they would be used. In the article, I came across an example meant to demonstrate how to use ThreadLocal. It was a class that was supposed to be a transaction manager, and it used a static transactionID variable that was used throughout the class. In order to make the class thread safe, it used a ThreadLocal for the transactionID:
public class TransactionManager {
private static final ThreadLocal<String> context = new
ThreadLocal<String();
public static void startTransaction() {
//logic to start a transaction
//...
context.set(generatedId);
}
public static String getTransactionId() {
return context.get();
}
public static void endTransaction() {
//logic to end a transaction
//…
context.remove();
}
}
My question is, why not just make the transactionID an instance variable instead of making it static in the first place? That way you wouldn't need to use a ThreadLocal variable.
The difference would change on some scenarios, but let's try some things:
I will assume the outline of the example is something like "We are executing several steps in some process and we want to generate a transactionID to identify one execution of the process. All those steps run in the same thread for any given execution"
In this case, the difference would be that if you make it an instance variable (yes, you can do it), you will have to create your transactionId and propagate the TransactionManager instance across all the layers and classes you might need it as a parameter, making your methods signature dirtier than need to be (Imagine you have one StepExecution interface and all steps implements that interface, but not all steps might need to access the transactionID, you will then have one useless parameter mixed in your method signature)
Not only that, ThreadLocal will guarantee you that the value you are accessing is the one you generated on the same thread, preventing "leaks" of information among threads making it perfectly thread safe.
...and it used a static transactionID variable that was used throughout the class. In order to make the class thread safe, it used a ThreadLocal for the transactionID
That basically is the use-case for ThreadLocal in a nutshell: You have some body of non-thread aware code that you want to make thread-safe, but it uses one or more static variables. If it makes sense for each thread to have its own independent copy of the static variable, then you just pop in a ThreadLocal, and problem solved!

Why is ClassLoader created from specific class when holds global information? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I just came to realise that this will sometimes return null (print null in console):
package myproject;
public class A {
public static void main(String[] args) throws Exception
{
System.out.println(A.class.getClassLoader().getResource("A.class"));
}
}
Even though the ClassLoader is created from A.class it has nothing to do with it. It will load resources from the currently running classpath.
I realised this when I was running Maven test classes which run, by default, in project/target/test-classes while the normal classes, like A above, are in project/target/classes/.
I think this is very confusing. Why don't we get something like Class.getClassLoader to make it obvious that this is a global thing? Also, since ClassLoader is useless, what do developers use to load resources relative to their projects? If you include .jar dependency it works, resources included.
First of all: two different classes can be loaded by different class loaders. So, when you do:
ClassLoader forA = A.class.getClassLoader();
ClassLoader forB = B.class.getClassLoader();
it is very much possible that
if (forA.equals(forB)) {
print equal
} else {
print not equal
}
will print not equal!
Therefore your idea of using a single global Class.getClassLoader() breaks immediately: as there isn't a single entity that this method call could possibly return.
And for the other part - about access resources ... have a look at this SO question.
Each class is associated with the class loader that loaded the class. It makes perfect sense to let Class have an getClassLoader instance method.
It's nothing "wrong" with having multiple different objects return the same object through a get method.
It's like having, say person.getAddress(). All persons in a family may return the same address, but that doesn't mean it makes sense to have a static Person.getAddress.

is there anything called global variable in java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
According to this post Global variables in Java it describes how to define a global variables in java by using static
public class Example {
public static int a;
public static int b;
}
But at same time in other post Why are there no global variables in Java? this question contradicts .
So my question is what exactly is global variable ?
Do java supports global variables ?if yes ,how?
if no ,why?
and how java global variables(if there are any) are different from c++ global variables?
I think that we can argue that there is no global keyword in java but your example can be treated like a global.
In most languages where you can define a global variable the problem is that they pollute the global namespace and name clashes can occur (like in php). In this regard there are no globals in java since there is no global namespace: variables are always in a class.
So the main thing is: there is no explicit globan in java and there is no globan namespace in java. This frees you from name clashes and accidental overwrites which is a good thing.
But there is nothing stopping you from creating a Global class with a lot of public static fields in it.
Please note that most guys (including me) would break both of your hands for doing so. :)
a gloabal variable is used by many functions without need to enter it in the input of these functions.
Expert advice to don't use them.
A global variable is a variable which can be accessed from anywhere (from any part of the program). Thus a public static variable in any Java class is global.

Categories

Resources