哪一段代码更好?

时间:2016-10-27 21:57:04

标签: java performance optimization

我正在写一些代码,但我不确定哪个更好。在某种程度上,它更容易阅读正在发生的事情,但我有更多的代码。 换句话说,你的代码行数较少,但我认为更难理解。

String imp = importance.getSelectedItem().toString();
String title_str = title.getText().toString();
String body_str = body.getText().toString();
String location_str = location.getText().toString();
int day = date.getDayOfMonth();
int month = date.getMonth()+1;
int year = date.getYear();
int hh = time.getCurrentHour();
int mm = time.getCurrentMinute();
String date_str = year+"/"+month+"/"+day+" " + hh+":"+mm +":00"; // yyyy/MM/dd HH:mm:ss
long dateMilliseconds = new Timeconversion().timeConversion(date_str);

Conference conference = ConferenceBuilder.conference()
        .id(idConf)
        .importance(Double.parseDouble(imp))
        .title(title_str)
        .body(body_str)
        .location(location_str)
        .timeInMilliseconds(dateMilliseconds)
        .build();
  

Conference conference2 = ConferenceBuilder.conference()
                                .id(idConf)
                                .importance(Double.parseDouble(importance.getSelectedItem().toString()))
                                .title(title.getText().toString())
                                .body(body.getText().toString())
                                .location(location.getText().toString())
                                // yyyy/MM/dd HH:mm:ss
                                .timeInMilliseconds(new Timeconversion().timeConversion(date.getYear()+"/"+date.getMonth()+1+"/"+date.getDayOfMonth()+" " + time.getCurrentHour()+":"+time.getCurrentMinute() +":00"))
                                .build();

1 个答案:

答案 0 :(得分:1)

分开差异。我会做这样的事情:

Conference conference2 = ConferenceBuilder.conference()
            .id(idConf)
            .importance(Double.parseDouble(importance.getSelectedItem().toString()))
            .title(title.getText().toString())
            .body(body.getText().toString())
            .location(location.getText().toString())
            // yyyy/MM/dd HH:mm:ss
            .timeInMilliseconds(getTimeInMillis(datePicker, timePicker))
            .build();
}

private long getTimeInMillis(DatePicker datePicker, TimePicker timePicker) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(), 
    timePicker.getCurrentHour(), timePicker.getCurrentMinute(), 0);
    return calendar.getTimeInMillis();
}

我不认为从文本视图中提取String对象会使事情变得更具可读性,因为您的文本视图的名称非常明确。