Creating  a static method returning Logger Object inside class

Hello,
Instead of creating Logger Instance in every class , can i do like this way by creating a static method in some class returning a Logger object , and using that method for getting instance of Logger in another class through that method
Regards
Mayur Mitkari

On a related note, if you want to make it simpler, never do this:
if (a == true)Instead, just do if (a)It's pointless and cluttersome to use == or != with true or false.
// wrong
if (a == true)
if (a != false)
// right
if (a)
// wrong
if (a == false)
if (a != true)
// right
if (!a)Also, note that
if (x) {
  return true;
else {
  return false;
}can be simplified to return x;If you do that and change your variable to something a bit more meaningful, like trueCount or numTrue or something, your code would be
int trueCount = 0;
if (a) trueCount++;
if (b) trueCount++;
if (c) trueCount++;
return trueCount >= 2;which is about as simple and clear as it can get, IMHO. Using less code doesn't necessarily make the code simpler or clearer. The idea is that someone reading the code can easily understand what it does.
And note that the above can be easily generalized to "Are there at least M true values in this array/list of N booleans?" and still be concise and clear.

Similar Messages

  • JUNIT : how to call static methods through mock objects.

    Hi,
    I am writing unit test cases for an action class. The method which i want to test calls one static method of a helper class. Though I create mock of that helper class, but I am not able to call the static methods through the mock object as the methods are static. So the control of my test case goes to that static method and again that static method calls two or more different static methods. So by this I am testing the entire flow instead of testing the unit of code of the action class. So it can't be called as unit test ?
    Can any one suggest me that how can I call static methods through mock objects.

    The OP's problem is that the object under test calls a static method of a helper class, for which he wants to provide a mock class
    Hence, he must break the code under test to call the mock class instead of the regular helper class (because static methods are not polymorphic)
    that wouldn't have happened if this helper class had been coded to interfaces rather than static methods
    instead of :
    public class Helper() {
        public static void getSomeHelp();
    public class MockHelper() {
        public static void getSomeHelp();
    }do :
    public class ClassUnderTest {
        private Helper helper;
        public void methodUnderTest() {  // unchanged
            helper.getSomeHelp();
    public interface Helper {
        public void getSomeHelp();
    public class HelperImpl implements Helper {
        public void getSomeHelp() {
            // actual implementation
    public class MockHelper implements Helper {
        public void getSomeHelp() {
            // mock implementation
    }

  • Help with writing a static method in my test case class inside blue j

    I have this method that I have to test. below is the method I need to test and what I have to create inside my test case file to test it Im having big time problems getting going. Any help is appreciated.
    public String introduceSurprise ( String first, String last ) {
    int d1 = dieOne.getFace();
    Die.roll();
    if (d1 %4 == 2){
    return Emcee.introduce(first);
    else {
    return this.introduceSpy (first,last);
    So how do write tests to verify that every fourth call really does give a randomized answer? Write a static method showTests which
    creates an EmCee,
    calls introduceSurprise three times (doing nothing with the result (!)),
    and then calls it a fourth time, printing the result to the console window.
    Write this code inside your test class TestEmCee, not inside EmCee!

    hammer wrote:
    So how do write tests to verify that every fourth call really does give a randomized answer? Write a static method showTests which
    creates an EmCee,
    calls introduceSurprise three times (doing nothing with the result (!)),
    and then calls it a fourth time, printing the result to the console window.
    Write this code inside your test class TestEmCee, not inside EmCee!Those instructions couldn't be anymore straightforward. Make a class called TestEmCee. Have it create an EmCee object. Call introduceSurprise on that object 3 times. Then print the results of calling it a 4th time.

  • Static methods in Transfer Objects

    Hi all,
    I have a doubt about Transfer Object:
    Is it possible to have a static method (or field)
    inside a Transfer Object returned from
    a Session Bean to a Client ?
    Many thanks in advance,
    Moreno

    Static fields, yeah, they'd cause some interesting problems, so are not a good idea in TOs. You can do it, but YMMV (Your Mileage May Vary).
    Static method? I'd get rid of it and put it in a utility class or somewhere else. Static methods are pretty meaningless when applied to TOs. The idea is to encapsulate data and some behavior - not provide procedural functionality.

  • When a Method Returns an Object, does it return a copy or a pointer?

    When you have a method that returns an Object, is the Object returning a copy of the Object returned inside
    of the Method or is it an Actual pointer to the Object inside of the method's coresponding Object?
    so say you have an object ...
    Class Something {
    JLabel myLabel = new JLable("myLabel");
    public JLabel getLabel() {
    return myLabel;;
    Something something = new Something();
    JLable theLabel = something.getLabel()
    theLable.setString("theLable");
    so when I setString on the Object theLabel , am I going to change the value of myLabel inside of the Object something?

    Yes, it returns a pointer.

  • ServerMBean start and kill methods return unserializable objects

    The ServerMBean start and kill methods both return unserializable
    objects which makes them unusable from a JVM other than that on which
    the server runs.
    This is unfortunate, as one would expect these things to be fairly
    standard tasks for a JMX client.
    I noticed in 7.0 they have been deprecated along with stop() - is
    there a known workaround for the time being?
    Thanks,
    Andrew Rosenfeld.

    I can't really answer you final question yet, but I will add what I know at this time, and look into it later next week.
    The JNLPClassLoader extends SecureClassLoader, so as the doc you refer to implys (in it's chapter on SecureClassLoader), the PermissionCollection it grants to code is statically bound at the time a class's defineClass() is called. The JNLPClassLoader's getPermissions() method starts with super.getPermissions, so the current policy permissions are added to those granted by the jnlp client, but it is still unmodifyable after that.
    For local intrenet applications several configuration options have been added in 1.5.0 (J2SE 5.0) that may help.
    You can implement an enterprise wide system configuration that includes system or user level policy files.
    You can also configure pre-accepted certificates so all code signed by your company can be trusted without the users seeing a security warning dialog.
    /Dietz

  • Find(String pkey) method returns multiple object of the same row

    I'm not quite sure what i've done or havent done, but I've implemented updating a row using the em.persist(Object) method.....works great, but after i did that a few times the find(String pkey) method returns multiple copies of 1 row in the db
    here are two rows in the db
    personid(PK) firstName lastName
    1234 joe jones
    2345 rachel jones
    when i execute any query looking for people with the last name jones, ie
    select object(p) from Person p where p.lastName='jones'
    it returns multiple objects of each row ie
    1234 joe jones
    1234 joe jones
    1234 joe jones
    1234 joe jones
    2345 rachel jones
    2345 rachel jones
    2345 rachel jones
    2345 rachel jones
    There is only one row for both rachel and joe in the db, but why is the entity manager returning multiple objects of each, and how do i prevent that without using DISTINCT?
    Thanks for the help in advance

    Sorry, i forgot to mention i'm using ejb 3 and jboss

  • Creating a new method in an enhanced component class implemetation

    Hello Experts,
    I am trying to create a new method in the enhanced component(BT115IT_SLSO) implementation class ( ZL_BT115IT__ITEMS_IMPL)to run our custom functionality. But somehow when I put a breakpoint and debug while I add a product to the sales order the method doesnt get trigerred.
    Is there some thing which I have to do  get this trigerred ? I just added a ned method and placed some custom code in it. Do I have to invoke it anywhere ?
    Pls help me out. I am new to Web UI.
    Thanks

    Hi Mavrick,
    As you are performing some action like item addition , there you need a method called as " event handler " to handle the event and perform the required actions.
    Place a break point in DO_HANDLE_EVENT method , and you will know the exact event handler method which is getting triggered . or if you are defining a new event ( by adding any new button) you should create a event handler method using wizard giving the same name which is defined on_click field of the button as it is case sensitive.
    Regards,
    Nithish

  • Using HttpServletRequest object to share variables between static methods.

    Does anyone know of the overhead/performance implications of using the HttpServletRequest object to share variables between a static method and the calling code?
    First, let me explain why I am doing it.
    I have some pagination code that I would like to share across multiple servlets. So I pulled the pagination code out, and created a static method that these servlets could all use for their pagination.
    public class Pagination {
         public static void setPagination (HttpServletRequest request, Config conf, int totalRows) {
              int page = 0;
              if (request.getParameter("page") != null) {
                   page = new Integer(request.getParameter("page")).intValue();
              int articlesPerPage = conf.getArticlesPerPage();
              int pageBoundary = conf.getPageBoundary();
                int numOfPages = totalRows / articlesPerPage;  
                // Checks if the page variable is empty (not set)
                if (page == 0 || (page > numOfPages && (totalRows % articlesPerPage) == 0 && page < numOfPages + 1)) {    
                 page = 1;  // If it is empty, we're on page 1
              // Ex: (2 * 25) - 25 = 25 <- data starts at 25
             int startRow = page * articlesPerPage - (articlesPerPage);
             int endRow = startRow + (articlesPerPage);           
             // Set array of page numbers.
             int minDisplayPage = page - pageBoundary;
             if (minDisplayPage < 1) {
                  minDisplayPage = 1;     
             int maxDisplayPage = page + pageBoundary;
             if (maxDisplayPage > numOfPages) {
                  maxDisplayPage = numOfPages;     
             int arraySize = (maxDisplayPage - minDisplayPage) + 1;
             // Check if there is a remainder page (partially filled page).
             if ((totalRows % articlesPerPage) != 0) arraySize++;
             // Set array to correct size.
             int[] pages = new int[arraySize];
             // Fill the array.
             for (int i = 1; i <= pages.length; i++) {
                  pages[i - 1] = i;
             // Set pageNext and pagePrev variables.
             if (page != 1) {
                  int pagePrev = page - 1;
                  request.setAttribute("pagePrev", pagePrev);
             if ((totalRows - (articlesPerPage * page)) > 0) {
                 int pageNext = page + 1;
                 request.setAttribute("pageNext", pageNext);
             // These will be used by calling code for SQL query.
             request.setAttribute("startRow", startRow);
             request.setAttribute("endRow", endRow);
             // These will be used in JSP page.
             request.setAttribute("totalRows", totalRows);
             request.setAttribute("numOfPages", numOfPages);
             request.setAttribute("page", page);
             request.setAttribute("pages", pages);          
    }I need two parameters from this method (startrow and endrow) so I can perform my SQL queries. Since this is a multithreaded app, I do not want to use class variables that I will later retrieve through methods.
    So my solution was to just set the two parameters in the request and grab them later with the calling code like this:
    // Set pagination
    Pagination.setPagination(request, conf, tl.getTotalRows());
    // Grab variables set into request by static method
    int startRow = new Integer(request.getAttribute("startRow").toString());
    int endRow = new Integer(request.getAttribute("endRow").toString());
    // Use startRow and endRow for SQL query below...Does anyone see any problem with this from a resource/performance standpoint? Any idea on what the overhead is in using the HttpServletRequest object like this to pass variables around?
    Thanks for any thoughts.

    You could either
    - create instance vars in both controllers and set them accordingly to point to the same object (from the App Delegate) OR
    - create an instance variable on the App Delegate and access it from within the view controllers
    Hope this helps!

  • Meaning of factory method in abap objects

    Hi,
    Can anybody help me in understanding the meaning of factory method in abap object? what is the importance of this?
    Regards
    Sudhansu

    Hi Krish and Sudhansu,
    Design patterns are solutions which are already verified and known by many developers. That is why it is worth to use them. There is no need to reinvent the wheel in many cases.
    I would recommend book which is placed in the ABAP world:
    http://www.sap-press.com/products/Design-Patterns-in-Object%252dOriented-ABAP-(2nd-Edition).html
    Although Java language has intuitive syntax, there are some special things in ABAP development so it is better to check solutions adjusted for ABAP editor.
    The most common usage of factory pattern is to simplify object creation.
    - By one method call you provide required parameters and do all initializations, including dependent objects.
    - Class can have many factory methods, if you want to provide more ways of initialization.
    - Factory method is usually static in the class and they return initialized instance of object for this class.
    - There is naming convention to start factory method name with "create" - easy to recognize pattern.
    - If you set property of class to "private instantiation" then you force to use factory method for object creation. In this way it is really simple to find all places where object are created with given set of input parameters - find references of factory method.
    Factory pattern becomes even more powerful if we add inheritance. Factory method returns basic object (like ZCL_VEHICLE) but its implementation can return different subclass instance, depending on input parameter (ZCL_CAR, ZCL_TRAIN etc). Each instance can implement differently behavior (methods implementation), but these are object oriented techniques.
    Regards,
    Adam

  • Static methods in data access classes

    Are we getting any advantage by keeping functions of DAOs (to be accessed by Session Beans) static ?

    I prefer to have a class of static methods that
    require a Connection to do their work. Usually, there
    is a SessionBean that 'wraps' this DAO. The method
    signatures for the SSB are the same, minus the need
    for a Connection, which the SSB gets before delegating
    to the Static Class.Uggh, passing around a connection. I've had to refactor a bunch of code that used this pattern. We had classes in our system that took a class in their constructor simply because one of their methods created an object that needed the connection. Bad news--maintenance nightmare--highly inflexible.
    What we've done is create ConnectionFactory singletons that are used throughtout the application in order to get connections to the database. All connection factory implementations implement the same interface so they can be plugged in from other components at runtime.
    In my opinion, classes that use connections should manage them themselves to ensure proper cleanup and consistent state. By using a factory implementation, we simply provide the DAO classes the means by which they can retrieve connections to the database and even the name of the database that needs to be used that is pluggable. The DAO classes do their own connection management.
    For similar reasons, I eschew the static method concept. By using class methods, you make it difficult to plug in a new implementation at runtime. I much prefer the singleton pattern with an instance that implements a common interface instead of a class full of static methods.
    I recently needed to dynamically plug in new connection factory implementation so that we could use JNDI and DataSources within the context of the application server (pooled connections) but use direct connections via the Driver manager for unit testing (so the application server didn't need to be running). Because of the way this was coded, I simply changed the original factory to be an abstract factory and changed the getInstance() method to return a different implementation based on the environment (unit test vs live). This was painless and didn't require changing a single line of client code.
    If I had to do this using the previous code that I refactored, I would have had to change about 200 jsp pages and dozens of classes that were making calls to the static method of the previous factory or hacked in something ugly and hard to maintain.
    YMMV

  • Abstract class method returning unknown class

    Hi
    I have created an abstract class having one of the method returning an object of a class which is not present at the compiletime. surprisingly the compiler didn't check the availability of the returning class at compilation time. it gave exception of classnotfound when I tried to rum it.
    is there any explanation of it??

    Thanks for the replay. I got the reason.
    actually evenif I did not compile to class file, but I have kept my java file in the same directory. while compiling the abstract class the compiler automatically compiled the reffered class and generated the required class file.
    I got the error when I moved the java file to another dir
    the code is like
    <code>
    abstract class AbstractTest{
         CompleteClass method1(){
              System.out.println("inside method1 of abstract class");
              return new CompleteClass();
         ExtraClass method2(){
                   System.out.println("inside method2 of abstract class");
                   return new ExtraClass(); // this class was not compiled before
         } // only java file is there in the dir
         abstract void demoMethod();
    </code>

  • Polymorphism and static methods

    Say I have classes A and B:
    public class A {
         public static A newInstance() {
              return new A();
    public class B
    extends A {
    }How can I write the newInstance method in A so that:
    B.newInstance();returns an object of class B instead of A? I know I can override the method in B to make an object of the right type - but is there a way to write the A method so that the correct type is created by any subclasses?

    I suppose this is cheating...
    class A {
       public static A newInstance(Class c)
       throws InstantiationException, IllegalAccessException {
          return (A) c.newInstance();
    class B extends A {
    class Testx {
       public static void main(String[] args)
       throws InstantiationException, IllegalAccessException {
          B b = (B)B.newInstance(B.class);
          System.out.println(b.getClass().getName());  //B

  • How to get the class name  static method which exists in the parent class

    Hi,
    How to know the name of the class or reference to instance of the class with in the main/static method
    in the below example
    class AbstA
    public static void main(String[] args)
    System.out.println(getXXClass().getName());
    public class A extends AbstA
    public class B extends AbstA
    on compile all the class and run of
    java A
    should print A as the name
    java B
    should print B as the name
    Are there any suggestions to know the class name in the static method, which is in the parent class.
    Regards,
    Raja Nagendra Kumar

    Well, there's a hack you can use, but if you think you need it,Could you let me the hack solution for this..
    you probably have a design flaw and/or a misunderstanding about how to use Java.)May be, but my needs seems to be very genuine..of not repeat the main method contents in every inherited class..
    The need we have is this
    I have the test cases inheriting from common base class.
    When the main method of the test class is run, it is supposed to find all other test cases, which belong to same package and subpackages and create a entire suite and run the entire suite.
    In the above need of the logic we wrote in the main method could handle any class provided it knows what is the child class from which this main is called.
    I applicate your inputs on a better way to design without replicating the code..
    In my view getClass() should have been static as the instance it returns is one for all its instances of that class.
    I know there are complications the way compiler handles static vars and methods.. May be there is a need for OO principals to advance..
    Regards,
    Raja Nagendra Kumar
    Edited by: rajanag on Jul 26, 2009 6:03 PM

  • Static methods

    Is creating a static method frowned upon in OO development? Is it only a matter of convenience by not having to instantiate?
    Any insight is appreciated.
    --Gregory
    quote: Don't throw away the old bucket until you know whether the new one holds water.

    Regardless of how many objects you have created, there is only 1 copy of the static variables in the memory. Its not just a matter of convenience but is used in certain conditions based on some requirements. A good example would be Singleton. There already is a kind of Singleton class in the standard Java class libraries:
    the Math class. This is a class that is declared final and all methods are declared static, meaning that the class cannot be extended. The purpose of the Math class is to wrap a number of common mathematical functions such as sin and log in a class-like structure, since the Java language does not support functions that are not methods in a class. You can use the same approach to a Singleton pattern, making it a final class. You can�t create any instance of classes like Math, and can only call the static
    methods directly in the existing final class.
    Another approach, suggested by Design Patterns, is to create Singletons using a static method to issue and keep track of instances. To prevent instantiating the class more than once, we make the constructor private so an instance can only be created from within the static method of the class.
    Hope that helps
    &#9824

Maybe you are looking for

  • Document number....posted in T Code F-53 is not popping after saving

    Hi, I am posting outgoing payment in new fiscal year 1.4.2014, in F-53. After saving the document, I am not getting the pop up message: "Document number .... posted in T Code F-53. But when I check the GL line item in FBL3N, the document number is vi

  • Long story short i need to set up a password for my links...

    long story short i need to set up a password for my linksys wireless router... i tried go to linksys' website link  i went ahead and set up a password using instructions from the link above...went to http://192.168.1.1/...clicked on admin tab and set

  • Windows hijacks iPod and treats like flash drive.

    every time I connect my new ipod to my computer (vista) windows explorer opens up and shows an empty drive, so I close that and then iTunes opens and try's to sync, after 40 songs windows hijacks it, disconnects it, re-connects it and opens it again

  • Design forms for multiple users

    Dear sir I am developing new application for my company.I don't know how to desing the the tables for multiple users and how to give rights to users to access certain forms.This application will use in two differnet languages. how to switch one langu

  • My charger is blinking faintly

    My Macbook pro turned on, shut off.  so i turned it back on, it again shut off once i logged in.  the charger is Faintly blinking, and now my computer wont turn on.