简体   繁体   中英

Java/Android OOP style for randomizer

This is a basic coding style question as I'm trying to be super accurate on best practices. I've browsed around and pieced together some Java code for generating a random string from a list and adding it to an existing string in my Android App.

On investigation I found two approaches, one was to use a single line of code to generate the random string by selecting an item from a list, another was to call a routine to do basically the same thing. I know it can be good to break the code up into smaller chunks, but in this case would one method be generally preferred over the other? Note that the first option is commented out in the code.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Get the message from the intent
    Intent intent = getIntent();
    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

    //Add a random day to the string
    List<String> list = new ArrayList<>();
    list.add("Monday");
    list.add("Tuesday");
    list.add("Wednesday");
    list.add("Thursday");
    list.add("Friday");
    list.add("Saturday");
    list.add("Saturday");

    //Random rand = new Random();
    //String random = list.get(rand.nextInt(list.size()));

    String random = getRandom(list);

    message += " " + random;

    // Create the text view
    TextView textView = new TextView(this);
    textView.setTextSize(40);
    textView.setText(message);

    // Set the text view as the activity layout
    setContentView(textView);
}


static public <T> T getRandom(List<T> list){
    Random rand = new Random();
    if(list == null || list.isEmpty()){
        return null;
    }else{
        return list.get(rand.nextInt(list.size()));
    }
}

Here in this case a good idea can be moving the code in to a routine. Though the function call may slow down the app(invisibly) this will be a best approach for code reuse. Consider you need the same functionality in another activity, you can simply call this function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM