Documentation
Getting Started/AI Programming Basics

AI Programming Basics

ThinkCode transforms how you write code by integrating powerful AI assistance directly into your development workflow. This guide introduces the fundamental concepts of AI-assisted programming and how to leverage these capabilities effectively.

Understanding AI-Assisted Development

AI-assisted development enhances your coding process in several ways:

graph LR
    A[Traditional Coding] --> B[Write Code]
    B --> C[Debug]
    C --> D[Refactor]
    D --> B
    
    E[AI-Assisted Coding] --> F[Describe Intent]
    F --> G[AI Generates Code]
    G --> H[Review & Edit]
    H --> I[Refine with AI]
    I --> F
    
    style E fill:#f96,stroke:#333,stroke-width:2px
    style F fill:#f9c,stroke:#333,stroke-width:1px
    style G fill:#f9c,stroke:#333,stroke-width:1px
    style H fill:#f9c,stroke:#333,stroke-width:1px
    style I fill:#f9c,stroke:#333,stroke-width:1px

Key Benefits

  • Accelerated Development: Generate working code faster
  • Reduced Cognitive Load: Focus on high-level logic instead of syntax details
  • Expanded Knowledge: Access expertise beyond your personal experience
  • Improved Code Quality: Get suggestions for optimizations and best practices
  • Learning Opportunities: Understand new approaches and patterns

Core AI Capabilities in ThinkCode

1. Code Generation

ThinkCode can generate code based on your descriptions:

From Comments

The simplest way to generate code is by writing a comment:

// Create a function that calculates the average of an array of numbers

After typing this comment and pressing Enter, ThinkCode might generate:

// Create a function that calculates the average of an array of numbers
function calculateAverage(numbers) {
  if (numbers.length === 0) return 0;
  const sum = numbers.reduce((total, num) => total + num, 0);
  return sum / numbers.length;
}

From Natural Language Requests

You can also make direct requests in the Think Panel:

"Write a React component that displays a paginated list of items with a search function"

2. Code Completion

ThinkCode provides intelligent code completion:

Line Completion

As you type, ThinkCode suggests completions for your current line:

function getUserData() {
  return fetch('/api/user').th // ThinkCode suggests: .then(response => response.json())
}

Block Completion

ThinkCode can complete entire blocks of code:

function setupAuthMiddleware(app) {
  // ThinkCode might suggest the entire middleware configuration
}

3. Context-Aware Understanding

ThinkCode understands your project context:

Multi-File Awareness

ThinkCode considers related files when making suggestions:

  • If you have a component using a custom hook, ThinkCode knows the hook's functionality
  • If you're implementing an interface from another file, ThinkCode understands the requirements

Project Structure Awareness

ThinkCode considers your project's architecture and patterns:

  • Suggests imports from the correct paths
  • Follows existing naming conventions and code style
  • Maintains consistency with your project's architecture

How to Effectively Work with AI

1. Be Clear and Specific

The quality of AI-generated code depends on the clarity of your instructions:

Less Effective

// Make a form

More Effective

// Create a registration form with email, password, and confirm password fields
// Include validation for email format and password matching
// Add a submit button that is disabled until validation passes

2. Iterative Refinement

AI-assisted development works best as an iterative process:

  1. Start with a high-level description
  2. Review the generated code
  3. Refine your request with more details
  4. Repeat until satisfied

Example conversation flow:

You: "Create a function to fetch user data from an API"
AI: [Generates basic fetch function]
You: "Modify it to include error handling and a loading state"
AI: [Updates code with try/catch and loading state]
You: "Add caching to prevent redundant API calls"
AI: [Enhances code with caching mechanism]

3. Contextual Prompting

Help ThinkCode understand your context:

Provide Background Information

// This is part of a React Native app using Redux for state management
// We need a component that displays a list of transactions
// Each transaction has a date, amount, and category

Reference Existing Code

// Similar to the UserCard component we created earlier, but for displaying product information

4. Using Comments for Inline Guidance

Strategic comments help guide AI generation:

// First, validate the input parameters
// Then, make the API request with error handling
// Finally, transform the response data into the required format
function fetchProductData(productId) {
  // AI will generate code following these steps
}

Coding Patterns with AI

1. Scaffolding First

Start by generating the structure, then fill in details:

// Generate a React component scaffold for a checkout form

After reviewing the scaffold:

// Now implement the form validation logic for credit card processing

2. Test-Driven Development with AI

Use AI to help implement tests and then the solution:

// Write a test for a function that validates email addresses

Then:

// Now implement the email validation function to pass the test

3. Refactoring with AI

Use AI to improve existing code:

// Refactor this code to improve performance and readability
function oldFunction() {
  // Your existing code here
}

AI Modes and Roles

ThinkCode offers different AI personalities for specific tasks:

Code Assistant (Default)

General-purpose coding help for completing tasks efficiently.

Architect

Focuses on system design, patterns, and best practices:

"As an Architect, suggest a folder structure for a React Native app with shared components"

Reviewer

Analyzes code for issues and improvements:

"Review this authentication logic for security vulnerabilities"

Teacher

Provides explanations and learning resources:

"Explain how async/await works under the hood"

Practical Examples

Example 1: Building a Feature

User Comment:

// Create a dark mode toggle component with React that:
// 1. Uses localStorage to persist user preference
// 2. Automatically detects system preference
// 3. Provides a smooth transition when toggling

AI Output:

import { useState, useEffect } from 'react';
 
/**
 * DarkModeToggle - A component that handles dark mode functionality
 * Features:
 * - Persists user preference in localStorage
 * - Detects system preference
 * - Smooth transition between modes
 */
export const DarkModeToggle = () => {
  // Initialize state based on localStorage or system preference
  const [isDarkMode, setIsDarkMode] = useState(() => {
    // Check for saved preference
    const savedMode = localStorage.getItem('darkMode');
    if (savedMode !== null) {
      return savedMode === 'true';
    }
    // Check for system preference
    return window.matchMedia('(prefers-color-scheme: dark)').matches;
  });
 
  // Apply dark mode class to document and save preference
  useEffect(() => {
    // Add transition class for smooth changes
    document.documentElement.classList.add('color-theme-in-transition');
    
    // Apply or remove dark mode class
    if (isDarkMode) {
      document.documentElement.classList.add('dark');
    } else {
      document.documentElement.classList.remove('dark');
    }
    
    // Save preference to localStorage
    localStorage.setItem('darkMode', isDarkMode.toString());
    
    // Remove transition class after transition completes
    const timeout = setTimeout(() => {
      document.documentElement.classList.remove('color-theme-in-transition');
    }, 300);
    
    return () => clearTimeout(timeout);
  }, [isDarkMode]);
 
  // Toggle dark mode
  const toggleDarkMode = () => {
    setIsDarkMode(prevMode => !prevMode);
  };
 
  return (
    <button 
      onClick={toggleDarkMode}
      className="p-2 rounded-full bg-gray-200 dark:bg-gray-800"
      aria-label={isDarkMode ? "Switch to light mode" : "Switch to dark mode"}
    >
      {isDarkMode ? (
        <SunIcon className="w-5 h-5 text-yellow-500" />
      ) : (
        <MoonIcon className="w-5 h-5 text-blue-500" />
      )}
    </button>
  );
};
 
// Icon components (simplified for example)
const MoonIcon = ({ className }) => (
  <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z" />
  </svg>
);
 
const SunIcon = ({ className }) => (
  <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z" />
  </svg>
);

Example 2: Debugging with AI

User Request in Think Panel:

I'm getting the error "Cannot read property 'map' of undefined" in this component:

function UserList({ userIds }) {
  const [users, setUsers] = useState([]);
  
  useEffect(() => {
    async function fetchUsers() {
      const userPromises = userIds.map(id => 
        fetch(`/api/users/${id}`).then(res => res.json())
      );
      const fetchedUsers = await Promise.all(userPromises);
      setUsers(fetchedUsers);
    }
    fetchUsers();
  }, [userIds]);
  
  return (
    <div>
      {users.map(user => (
        <UserCard key={user.id} user={user} />
      ))}
    </div>
  );
}

Help me fix it.

AI Response:

The error "Cannot read property 'map' of undefined" is occurring because `userIds` might be undefined when the component renders. This can happen if the component is rendered before the prop is available.

Here's how to fix it:

1. Add a check to ensure `userIds` exists before calling `.map()` on it
2. Provide a default value for the `userIds` prop
3. Add error handling in the `fetchUsers` function

Here's the corrected code:

```jsx
function UserList({ userIds = [] }) {  // Provide default empty array
  const [users, setUsers] = useState([]);
  const [error, setError] = useState(null);
  
  useEffect(() => {
    async function fetchUsers() {
      try {
        // Only proceed if userIds exists and is an array
        if (Array.isArray(userIds) && userIds.length > 0) {
          const userPromises = userIds.map(id => 
            fetch(`/api/users/${id}`)
              .then(res => {
                if (!res.ok) throw new Error(`Failed to fetch user ${id}`);
                return res.json();
              })
          );
          const fetchedUsers = await Promise.all(userPromises);
          setUsers(fetchedUsers);
        }
      } catch (err) {
        console.error("Error fetching users:", err);
        setError(err.message);
      }
    }
    
    fetchUsers();
  }, [userIds]);
  
  if (error) {
    return <div>Error loading users: {error}</div>;
  }
  
  return (
    <div>
      {users.length > 0 ? (
        users.map(user => (
          <UserCard key={user.id} user={user} />
        ))
      ) : (
        <div>No users to display</div>
      )}
    </div>
  );
}

This fixes the issue by:

  1. Providing a default empty array for userIds
  2. Adding a check to ensure userIds is an array before calling .map()
  3. Adding proper error handling
  4. Adding a conditional rendering for empty states

## Best Practices for AI-Assisted Programming

### Do:

- **Start with clear intentions** about what you want to build
- **Review all AI-generated code** carefully before using it
- **Break complex tasks** into smaller, more manageable requests
- **Learn from the AI's suggestions** to improve your own skills
- **Use AI as a collaborative partner**, not a replacement for understanding

### Don't:

- **Blindly trust all output** without verification
- **Ask for solutions you don't understand** - use the AI to help you learn
- **Overcomplicate your requests** with unnecessary details
- **Ignore security implications** of generated code
- **Rely solely on AI** for critical security or business logic

## Next Steps

Now that you understand the basics of AI-assisted programming with ThinkCode, explore these related topics:

- [AI Code Assistance](../core-features/ai-code-assistance) for more advanced techniques
- [Role-based Development](../advanced-features/role-based-development) to use specialized AI roles
- [AI Sandbox Debugging](../core-features/ai-sandbox-debugging) for analyzing and fixing code
- [Think Keyboard Shortcuts](./keyboard-shortcuts) to work more efficiently

<div className="bg-blue-100 p-4 rounded-md border border-blue-300 mt-8">
  <h3 className="text-blue-800 font-bold text-lg">Pro Tip</h3>
  <p className="text-blue-700">Keep a "prompt library" of effective instructions for common tasks. Over time, you'll develop a collection of prompts that give you exactly the code you need for your specific workflow.</p>
</div>