Lección 4 de 11
Dominando el Autocompletado Inteligente
GitHub Copilot: Par-Programming AI
Más que autocompletado. Entiende contexto, patterns y best practices.
Cómo Funciona
OpenAI Codex entrenado en millones de repos, docs, Stack Overflow.
Proceso:
- Captura contexto (~4KB)
- Analiza archivos relacionados
- Identifica lenguaje/framework
- Genera sugerencias
- Filtra por seguridad
1. Comment-Driven Development
// Función: Celsius → Fahrenheit
function celsiusToFahrenheit(celsius) {
return (celsius * 9/5) + 32;
}
// Validar contraseña segura:
// - Min 8 chars, mayúscula, número, especial
// - No contiene username
function isStrongPassword(password, username) {
if (password.length < 8) return false;
if (!/[A-Z]/.test(password)) return false;
if (!/[0-9]/.test(password)) return false;
if (!/[!@#$%^&*]/.test(password)) return false;
if (password.toLowerCase().includes(username.toLowerCase())) {
return false;
}
return true;
}2. Pattern Recognition
// CRUD - Copilot completa patrón:
async function createUser(data) {
return await prisma.user.create({ data });
}
// Solo nombre, Tab completa:
async function getUser(id) {
return await prisma.user.findUnique({ where: { id } });
}
async function updateUser(id, data) {
return await prisma.user.update({ where: { id }, data });
}
async function deleteUser(id) {
return await prisma.user.delete({ where: { id } });
}3. Contextual Awareness
// types.ts
interface User {
id: string;
name: string;
role: "admin" | "user";
}
// UserService.ts
// Copilot conoce User interface:
class UserService {
async findByEmail(email: string): Promise {
return await db.user.findUnique({ where: { email } });
}
async isAdmin(user: User): Promise {
return user.role === "admin";
}
} 4. Multi-Line Completions
// Solo firma:
async function fetchUserPosts(userId: string) {
// Copilot completa todo:
try {
const response = await fetch(`/api/users/${userId}/posts`);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
} catch (error) {
console.error(error);
throw error;
}
}
// React component:
const UserProfile = ({ userId }) => {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchUser().then(setUser).finally(() => setLoading(false));
}, [userId]);
if (loading) return Loading...;
return {user.name};
};5. Alternative Suggestions
Ctrl+Enter → múltiples opciones (fetch, axios, con error handling)
6. Inline Chat
// Selecciona + Ctrl+I
// "agregar validación y JSDoc"
/**
* Calcula precio con descuento
* @param {number} price - Precio (positivo)
* @param {number} percentage - Descuento (0-100)
* @returns {number} Precio final
* @throws {Error} Si inválido
*/
function calculateDiscount(price, percentage) {
if (price < 0) throw new Error("Price positive");
if (percentage < 0 || percentage > 100) {
throw new Error("Percentage 0-100");
}
return price - (price * percentage / 100);
}Casos Avanzados
Tests
// Función:
function isPalindrome(str) {
const cleaned = str.toLowerCase().replace(/[^a-z0-9]/g, "");
return cleaned === cleaned.split("").reverse().join("");
}
// Copilot genera:
describe("isPalindrome", () => {
it("returns true for palindromes", () => {
expect(isPalindrome("racecar")).toBe(true);
expect(isPalindrome("A man a plan a canal Panama")).toBe(true);
});
it("returns false for non-palindromes", () => {
expect(isPalindrome("hello")).toBe(false);
});
it("handles edge cases", () => {
expect(isPalindrome("")).toBe(true);
});
});Tips Pro
- Nombres descriptivos: UserAuthService.ts mejor que auth.ts
- Imports claros: Ayudan a contexto
- Consistencia: Mantén estilo uniforme
- Examples first: 1-2 ejemplos, Copilot continúa
- Funciones pequeñas: Mejor con código específico
- TypeScript: Tipos ayudan muchísimo
Limitaciones
❌ No confíes ciegamente:
- Revisa SIEMPRE
- Puede ser inseguro
- Librerías obsoletas
- No entiende negocio específico
⚠️ Cuidado: Crypto, finanzas, DB complejo, performance crítica
Practica para multiplicar productividad!