收集、管理和分享有用的代码片段,提高开发效率
代码复用特性
<?php
trait Logger {
public function log($message) {
echo date('Y-m-d H:i:s') . ' ' . $message . PHP_EOL;
}
}
class User {
use Logger;
public function save() {
$this->log('Saving user');
// Save logic
}
}
class Product {
use Logger;
public function update() {
$this->log('Updating product');
}
}
$user = new User();
$user->save();
$prod = new Product();
$prod->update();
类型注释示例
from typing import List, Tuple, Dict, Optional
def greet(name: str) -> str:
return f"Hello, {name}!"
def process_data(data: List[int]) -> float:
return sum(data) / len(data)
User = Dict[str, int]
Address = Tuple[str, int, str]
def get_user(user_id: int) -> Optional[User]:
if user_id == 1:
return {"name": "Alice", "age": 30}
return None
instanceof增强
public class PatternMatching {
public static double calculate(Object shape) {
if (shape instanceof Rectangle rect) {
return rect.width() * rect.height();
} else if (shape instanceof Circle circle){
return Math.PI * Math.pow(circle.radius(), 2);
}
return 0;
}
public static void main(String[] args) {
Object shape = new Rectangle(5, 10);
double area = calculate(shape);
System.out.println("Area: " + area);
}
}
class Rectangle {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double width() { return width; }
public double height() { return height; }
}
class Circle {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double radius() { return radius; }
}
绘制简单图形
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Draw rectangle
ctx.fillStyle = '#FF0000';
ctx.fillRect(10, 10, 150, 80);
// Draw circle
ctx.beginPath();
ctx.arc(250, 100, 50, 0, 2 * Math.PI);
ctx.fillStyle = '#0000FF';
ctx.fill();
// Draw text
ctx.font = '30px Arial';
ctx.fillStyle = '#000000';
ctx.fillText('Happy Coding', 150, 200);
动态调用方法
public class ReflectionDemo {
public static void main(String[] args) throws Exception {
Class<?> clazz = Class.forName("java.util.ArrayList");
Object list = clazz.getDeclaredConstructor().newInstance();
Method addMethod = clazz.getMethod("add", Object.class);
addMethod.invoke(list, "Hello Reflection!");
System.out.println(list);
}
}
审计日志触发器
CREATE TRIGGER before_update_users
ON USERS FOR EACH ROW
BEGIN
INSERT INTO user_audit (user_id, old_name, new_name, change_date)
VALUES (OLD.id, OLD.name, NEW.name, NOW());
END;
高效管理您的代码片段,提高开发效率
通过关键字、语言或分类快速查找代码片段,支持模糊搜索和过滤功能
支持多种编程语言的语法高亮,使代码更加清晰易读
随时随地访问您的代码片段库,支持桌面和移动设备
浏览最受欢迎的代码分类