使用 ChatGPT 提高工作效率的场景与心得
自从 3 月份开始使用 ChatGPT,我的工作效率有了大幅提升。本文记录我使用 ChatGPT 的一些场景和心得。

文案生成和润色

我使用 ChatGPT 润色了部门季度总结会议的 PPT 内容。ChatGPT 提供了不少的修饰建议,使得最终文案更为流畅、易懂。

代码 Review

公司禁止直接使用 ChatGPT 生成的代码,但可以使用 ChatGPT 辅助 Review,移除敏感的代码片段并保留部分需要检查的代码段。使用 ChatGPT Review 代码的效果非常好。
一个具体的例子:
这是同事提交的原始代码:

void foo::bar(const Json::Value& jsonData)
{
eventMap.clear();

if (jsonData.isMemberWithValidFormat("event")) {
Json::Value event = jsonData["event"];

if(event.isMemberWithValidFormat("licenseTypeOption")){
Json::Value licenseTypeOption = event["licenseTypeOption"];

if (licenseTypeOption.isArray()) {
Json::Value::iterator it = licenseTypeOption.begin();
for (; it != licenseTypeOption.end(); ++it) {
Json::Value& item = *it;

if (item.isMemberWithValidFormat("licenseType")) {
Json::Value& licenseType = item["licenseType"];
Json::Value& licenseOption = item["licenseOption"];

CAString licenseTypeStr = licenseType.isString() ? licenseType.asString() : "";
CAString licenseOptionStr = licenseOption.isString() ? licenseOption.asString() : "";
if (!licenseTypeStr.IsEmpty() && !licenseOptionStr.IsEmpty()) {
eventMap[licenseTypeStr] = licenseOptionStr;
}
}
}
}
}
}

// ...
}

这是 ChatGPT 优化过的代码:

void foo::bar(const Json::Value& jsonData)
{
eventMap.clear();

if (!jsonData.isMemberWithValidFormat("event")) {
return;
}

const Json::Value& event = jsonData["event"];
if (!event.isMemberWithValidFormat("licenseTypeOption")) {
return;
}

const Json::Value& licenseTypeOption = event["licenseTypeOption"];
if (!licenseTypeOption.isArray()) {
return;
}

for (const auto& item : licenseTypeOption) {
if (!item.isMemberWithValidFormat("licenseType")) {
continue;
}

const Json::Value& licenseType = item["licenseType"];
const Json::Value& licenseOption = item["licenseOption"];
if (!licenseType.isString() || !licenseOption.isString()) {
continue;
}

eventMap[licenseType.asString()] = licenseOption.asString();
}
}

ChatGPT 还给出了相关的说明
if 语句嵌套太多,可以考虑进行重构,以提高代码的可读性和可维护性。一种常见的方法是使用早返回(early return)的方式,即在满足某些条件时直接返回结果,而不是嵌套多个if语句。以下是一个示例:
原始代码:

if (a) {
if (b) {
if (c) {
// do something
} else {
// do something else
}
} else {
// do something else
}
} else {
// do something else
}

重构后的代码:

if (!a) {
// do something else
return;
}

if (!b) {
// do something else
return;
}

if (!c) {
// do something else
return;
}

// do something

如上所示,通过早返回的方式,可以将原始代码中的多个嵌套if语句转换为多个单独的if语句,使得代码更加清晰和易于阅读。同时,还可以避免出现嵌套层数过深的情况,提高代码的可维护性。

定义类和接口

ChatGPT 可以根据需求和变量命名规范要求,生成很不错的接口或类定义。

生成单元测试用例

直接提供函数或接口给 ChatGPT,可以生成详细的测试用例和单元测试代码,提高了测试覆盖率。

搜索引擎

我已经使用 ChatGPT 替代 Google 和 StackOverflow。ChatGPT 可以根据关键词快速给出相关信息,缩短了搜索的时间。

翻译

ChatGPT 在翻译方面也很强大。我用它来翻译了一些文档和文章,翻译质量非常好。

学习助手

ChatGPT 可以帮助我总结所学知识,并提供更详细的说明,提高了学习效率。

总的来说, ChatGPT 为我提供了很多帮助,提高了我的工作效率和学习效率。虽然 ChatGPT 目前还有一些局限性,但随着技术的发展,相信 ChatGPT 将会变得越来越强大,为程序员提供更多的帮助。