【GitHub Copilot】GitHub Copilot的特点,使用Copilot Chat能够生成代码
大家知道,在最初我们安装GitHub Copilot的时候,我们安装了两个功能插件,其中有一个就是GitHub Copilot Chat
这个插件,就像ChatGPT,我们可以提问,然后GitHub Copilot Chat根据代码的上下文,给出最优的答案。
比如,我们有一个称DateUtility.cls的代码文件。
我们需要添加一个方法,这个方法能够返回日期参数dateInput的当前月份的最终日期。
public with sharing class DateUtility {
//月の最終日を取得
//dateInput:日付
public static Date getLastDateOfMonth(Date dateInput) {
Integer year = dateInput.year();
Integer month = dateInput.month();
Integer lastDay = Date.daysInMonth(year, month);
return Date.newInstance(year, month, lastDay);
}
//月の初日を取得
//dateInput:日付
public static Date getFirstDateOfMonth(Date dateInput) {
Integer year = dateInput.year();
Integer month = dateInput.month();
return Date.newInstance(year, month, 1);
}
//年の最初日を取得する
public static Date getFirstDateOfYear(Date dateInput) {
Integer year = dateInput.year();
return Date.newInstance(year, 1, 1);
}
}
提出问题,generate a method, which can return the last day of date type parameter .
使用Insert At Cursor按钮,或者按下Control·+Enter键
就能够把生成的代码,放到光标的位置中去。
在这里,有一些细节,我想提一下。
大家可能已经注意到了,生成的代码,符合作者的编程习惯。
参数的名称dateInput,和当前代码文件的上下文是一致的。 这很好。
当然,我们也可以使用ChatGPT,我们可以先上传这个DateUtility.cls代码文件,然后问相当的问题。
也能够得到类似的回答。
类似的方法,使用Gemini来实现
Gemeni能够生成如下代码,getLastDayOfMonth是我们需要的方法,
进一步的,还帮我们生成了getLastDayOfCurrentMonth方法。
/**
* @description Utility class for Date-related operations.
*/
public class DateUtils {
/**
* @description Returns the last day of the month for a given Date.
* @param inputDate The Date for which to find the last day of the month.
* If null, the method will return null.
* @return A Date object representing the last day of the month of the inputDate,
* or null if inputDate is null.
*
* @example
* Date myDate = Date.newInstance(2023, 10, 15); // October 15, 2023
* Date lastDayOfMonth = DateUtils.getLastDayOfMonth(myDate); // Returns Date.newInstance(2023, 10, 31)
*
* Date februaryDate = Date.newInstance(2024, 2, 1); // February 1, 2024 (leap year)
* Date lastDayFebruary = DateUtils.getLastDayOfMonth(februaryDate); // Returns Date.newInstance(2024, 2, 29)
*
* Date nullDate = null;
* Date resultNull = DateUtils.getLastDayOfMonth(nullDate); // Returns null
*/
public static Date getLastDayOfMonth(Date inputDate) {
if (inputDate == null) {
return null;
}
// Get the first day of the *next* month
Date firstDayOfNextMonth = inputDate.addMonths(1).toStartOfMonth();
// Subtract one day from the first day of the next month to get the last day of the current month
return firstDayOfNextMonth.addDays(-1);
}
/**
* @description (Optional) Overloaded method to get the last day of the current month.
* @return A Date object representing the last day of the current month.
*/
public static Date getLastDayOfCurrentMonth() {
return getLastDayOfMonth(Date.today());
}
}