Results 1 to 3 of 3
  1. #1
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    286
    Rep Power
    6

    Default Should we write a separate function for the initialization of variables?

    I just came across an example in which a few (2 actually) of variables are initialized in a method, and they have written a separate method for the initialization of those variables, like this

    Java Code:
    public void onCreate() {
      ...
      initializeVariables();
      ...
    }
    
    private void initializeVariables() {
      textView = (TextView) findViewById(R.id.blablah);
      seekBar = (SeelBar) findViewById(R.id.blablah);
    }
    Should we break down our code into methods for such small tasks as well? I understand that this style would make the code more readable if there were, say, 50 initializations, but is there any reason other than that? Is it the right coding practice?

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,423
    Blog Entries
    7
    Rep Power
    27

    Default Re: Should we write a separate function for the initialization of variables?

    Assuming the 'onCreate()' method has other things to do as well, I like the separation of concerns: 'do one thing and do it well' fits nicely here and another benefit is: if you always do it like this, you don't need to think where the variables are initialized in your code ...

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  3. #3
    Zarah is offline Senior Member
    Join Date
    Mar 2014
    Posts
    286
    Rep Power
    6

    Default Re: Should we write a separate function for the initialization of variables?

    @Jos OK I'll follow this style. Thank you.

Similar Threads

  1. initialization of variables at class level
    By madhuri in forum New To Java
    Replies: 2
    Last Post: 02-11-2014, 09:59 AM
  2. Atomatically make new variables with function?
    By dr_duckrat in forum Java Applets
    Replies: 7
    Last Post: 01-13-2014, 03:59 PM
  3. Replies: 11
    Last Post: 11-04-2012, 09:26 PM
  4. instance variables initialization
    By ghostrider in forum New To Java
    Replies: 6
    Last Post: 08-27-2012, 07:00 AM
  5. Replies: 1
    Last Post: 11-17-2008, 09:32 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •