[英]Java/Android OOP style for randomizer
这是一个基本的编码风格问题,因为我正在努力使最佳实践变得非常准确。 我四处浏览并拼凑了一些Java代码,这些代码用于从列表中生成随机字符串,并将其添加到Android App中的现有字符串中。
在调查中,我发现了两种方法,一种方法是使用一行代码通过从列表中选择一项来生成随机字符串,另一种方法是调用例程以执行基本相同的操作。 我知道将代码分成较小的块可能会很好,但是在这种情况下,一种方法通常会比另一种方法更受青睐吗? 请注意,第一个选项在代码中已被注释掉。
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()));
}
}
在这种情况下,可以将代码移入例程。 尽管函数调用可能会(缓慢地)降低应用程序运行速度,但这将是代码重用的最佳方法。 考虑到您在另一个活动中需要相同的功能,可以简单地调用此功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.