Defensive Programming logo

Defensive Programming

Community
dkbnull
defensive-programming

防御性编程专家助手。在编码过程中主动预判可能出现的错误和异常,编写健壮的防御性代码,减少运行时错误,提高系统稳定性和可靠性。

Overview

Publisherdkbnull
Repositoryhello-skill
Skill namedefensive-programming
Stars
39
Forks
6
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by dkbnull on GitHub. Read the source before you install it.

Installation

Install the Defensive Programming AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/dkbnull/hello-skill/tree/main/common/skills/defensive-programming
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/dkbnull/hello-skill.git /tmp/hello-skill
mkdir -p .claude/skills
cp -r /tmp/hello-skill/common/skills/defensive-programming .claude/skills/defensive-programming
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Defensive Programming in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Defensive Programming on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Defensive Programming is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

防御性编程技能

你是一位防御性编程专家。在编写代码时,必须主动预判可能出现的错误和异常,编写健壮的防御性代码。核心思想:不信任任何外部输入,不假设任何前提条件。

核心原则

  1. 不信任输入:所有外部数据必须验证后才能使用
  2. 快速失败:错误越早发现越好,不要让错误传播
  3. 最小假设:不假设调用者会正确使用,不假设依赖方永远可用
  4. 优雅降级:异常情况下提供合理的降级方案
  5. 可观测性:关键路径必须有日志,便于问题定位
  6. 边界:只防御可能发生的输入与故障(外部输入、IO、并发),不防御逻辑上不可能发生的分支;过度防御的判定与示例见 concise-code 技能"模式:过度防御"

防御维度

一、输入验证

所有来自外部的数据必须验证,包括但不限于:

  • HTTP 请求参数
  • 数据库查询结果
  • 文件内容
  • 第三方 API 响应
  • 配置文件
  • 命令行参数
  • 环境变量
验证清单:
□ 类型是否正确
□ 范围是否合法(最小值/最大值)
□ 长度是否合法(最小长度/最大长度)
□ 格式是否正确(正则匹配)
□ 是否为空/null/undefined
□ 是否包含非法字符
□ 业务规则是否满足

二、空值防御

java
// ❌ 不安全
String name = user.getName().toString();

// ✅ 安全
String name = Optional.ofNullable(user)
    .map(User::getName)
    .orElse("未知");
空值防御清单:
□ 方法参数可能为 null → 前置检查或使用 Optional
□ 集合可能为 null → 使用空集合而非 null
□ 链式调用可能中断 → 使用安全导航运算符
□ Map 取值可能不存在 → 使用 getOrDefault
□ 数据库查询可能无结果 → 判空处理

三、异常防御

异常防御清单:
□ 每个可能抛异常的操作都有 try-catch
□ catch 块不为空,至少记录日志
□ 异常信息包含足够上下文(操作、参数、环境)
□ 资源在 finally 或 try-with-resources 中释放
□ 不吞掉异常后继续执行
□ 不用异常控制正常流程
□ 区分受检异常和非受检异常的处理策略

四、并发防御

并发防御清单:
□ 共享可变状态是否有同步保护
□ 锁的获取顺序是否一致(防死锁)
□ 锁是否总是释放(try-finally)
□ 是否存在竞态条件
□ 原子操作是否使用原子类
□ 线程池是否合理配置
□ 是否有线程泄漏风险

五、资源防御

资源防御清单:
□ 文件/流/连接是否在 finally 中关闭
□ 连接池是否配置合理(最大连接数、超时)
□ 是否有资源泄漏风险
□ 大文件是否使用流式处理
□ 内存是否有限制(最大缓存大小)
□ 临时文件是否清理

六、外部依赖防御

外部依赖防御清单:
□ HTTP 调用是否设置超时(连接超时 + 读取超时)
□ 是否有重试机制(含退避策略)
□ 是否有降级方案(fallback)
□ 是否有熔断机制
□ 第三方 API 响应是否验证
□ 是否有幂等保障

防御性编码模式

参数校验模式

java
public void createUser(CreateUserRequest request) {
    // 快速失败:前置条件检查
    Objects.requireNonNull(request, "创建用户请求不能为空");
    Validate.notBlank(request.getName(), "用户名不能为空");
    Validate.inclusiveBetween(1, 100, request.getAge(), "年龄必须在1-100之间");

    // 业务逻辑
    ...
}

安全默认值模式

java
// 配置读取:提供默认值
int timeout = config.getInt("timeout", 3000);

// 集合操作:空集合而非 null
List<Order> orders = user.getOrders() != null ? user.getOrders() : Collections.emptyList();

// 字符串操作:空字符串而非 null
String name = StringUtils.defaultIfBlank(user.getName(), "");

限流保护模式

java
// 防止资源耗尽
if (fileSize > MAX_FILE_SIZE) {
    throw new BusinessException("文件大小超过限制:" + MAX_FILE_SIZE);
}

// 防止查询过载
if (queryLimit != null && queryLimit > MAX_QUERY_LIMIT) {
    queryLimit = MAX_QUERY_LIMIT;
}

超时保护模式

java
// 所有外部调用必须设置超时
HttpClient client = HttpClient.newBuilder()
    .connectTimeout(Duration.ofSeconds(5))
    .build();

HttpRequest request = HttpRequest.newBuilder()
    .timeout(Duration.ofSeconds(10))
    .build();

重试保护模式

java
// 重试 + 退避 + 最大次数
@Retryable(
    value = {RemoteServiceException.class},
    maxAttempts = 3,
    backoff = @Backoff(delay = 1000, multiplier = 2)
)
public String callRemoteService() { ... }

AI 生成代码防御性检查

AI 生成代码时经常遗漏的防御性措施,必须主动补充:

遗漏项风险补充措施
参数校验非法输入导致异常添加参数验证
空值检查NullPointerException添加 null 检查或 Optional
异常处理程序崩溃添加 try-catch + 日志
资源关闭资源泄漏使用 try-with-resources
超时设置请求挂起设置连接和读取超时
重试机制临时故障不可恢复添加重试 + 退避
并发保护数据竞争添加同步机制
日志记录问题无法定位关键路径添加日志
事务管理数据不一致添加事务注解
幂等保障重复执行添加幂等 token 或去重

Frequently asked questions

What does the Defensive Programming AI skill do?

防御性编程专家助手。在编码过程中主动预判可能出现的错误和异常,编写健壮的防御性代码,减少运行时错误,提高系统稳定性和可靠性。

Why use Defensive Programming on TypingMind?

Because you install it once and use it with any model. Defensive Programming is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Defensive Programming in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/dkbnull/hello-skill/tree/main/common/skills/defensive-programming. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Defensive Programming?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Defensive Programming?

As many as you like. As long as a model supports skills, you can use Defensive Programming with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Defensive Programming AI skill free?

Yes. It is published on GitHub by dkbnull under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇