0
votes

public class DoSomething { private static final Logger logger = LoggerFactory.getLogger(DoSomething.class);

private final AtomicBoolean Flag = new AtomicBoolean(false);

LogMessage logMessage= new LogMessage(); // Creating an object to call a method in it

public static final String ERROR_MAP = "ERROR_MAP";
public static final String errorJsonString = System.getenv("RESTART_ERROR_MAP");

I tried to create an object of LogMessage. And use it inside a method of DoSomething class. Is this fine or should I move that line inside the method?

1
Where do you want it to be accessible/usable? Inside only that method or inside every method of the class?Caius Jard
Actually I am using inside that method. But is it too bad to create the object at this level even though I use it only within the method ?jayachsi
If you only need use it within the method, create it in the method. If you want some state of it to persist between multiple calls of the method, or it's expensive to create and will be used a lot, then that's another good reason to declare at class level - to minimize efforts of creation versus use.. As it is, we can't really give objective advice on what to do, because you haven't told us anything about the contextCaius Jard

1 Answers

1
votes

You haven't told us much about your LogMessage class. However, in general:

  • you should try to declare variables as close as possible to where they're first used.
  • you should try to instantiate class instances when you declare the class variable.
  • you should try to restrict the visibility of a variable to only that area of the code wehre it's used.

If you're only using LogMessage inside a method ... and if you're not going to re-use that instance across different method invocations ... I'd suggest you declare and initialize it inside the method.