0

I have an Android project with more that 50 global variables and I would like to collapse them so that the project is cleaner.

Is there a way to do that?

This:

public class MainActivity extends Activity {

    private TextView texView1;
    private int value1;
    ...
    x50

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }
}

to this:

public class MainActivity extends Activity {

    globalVariables();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    private void globalVariables() {
        private TextView texView1;
        private int value1;
        ...
        x50
    }
}
user3593157
  • 47
  • 2
  • 9
  • Short answer no. Why on earth do you have 50? –  Apr 06 '17 at 17:30
  • I need to have them for my project. – user3593157 Apr 06 '17 at 17:31
  • You can create a 'Constants' class where you make the global variables static and reference them ```Constants.globalVar1```. It would be cleaner, but you should really limit the scope of each variable as much as possible if you can. Having that many global variables can make code very hard to read. – Ivan Apr 06 '17 at 17:32
  • It depends on what do you mean by `collapse`. If you mean to *group* tem, then the answer is **YES**, you can: use **enum**s. – Phantômaxx Apr 06 '17 at 17:36
  • maybe this source will help you: http://stackoverflow.com/questions/2344524/java-equivalent-to-region-in-c-sharp – EtherPaul Apr 06 '17 at 17:39

2 Answers2

2

You can make something like this:

public class MyClass extends AppCompatActivity {

    private MyVariables variables;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        variables = new MyVariables();
        variables.texView1 = (TextView) findViewById(R.id.my_text_view);
        variables.value1 = 10;
    }

    private static class MyVariables {
        TextView texView1;
        int value1;
    }
}

However, if you have more than 50 global variables, something is wrong with your code.

Ravers
  • 988
  • 2
  • 14
  • 45
1

Step 1 Define region in any java class as follows:

//region GLOBAL_VARIABLES

put your 50 global variables inside this region
//endregion

Step 2 Auto fold/collapse regions using:

Go to File -> Settings -> Editor -> General -> Code Folding and then Check 'Custom Folding regions'

Cheers.

PEHLAJ
  • 9,980
  • 9
  • 41
  • 53