Unlocking AI Secrets: 19 Strategies, Tips, and Best Practices for Maximizing the Potential of AI Coding Tools
Source:Unsplash

Unlocking AI Secrets: 19 Strategies, Tips, and Best Practices for Maximizing the Potential of AI Coding Tools

BY ABDULLAH SALAUDEEN?


We all enjoy our favourite AI Code assistants, don’t we? They make our coding journey smoother, faster, and maybe even a tad more enjoyable. A survey comprising more than 2,000 developers revealed that the most productive individuals were those who embraced the largest quantity of code suggestions from Copilot. Next time you go all-in on AI-driven development, it's vital to grasp the ins and outs of utilizing these cutting-edge tools, especially if you're already using them.


In this article, I'll provide you with a developer's checklist—a handy roadmap to navigate the landscape of AI code editors . We've compiled 19 essential tips to help you harness the power of artificial intelligence while avoiding common pitfalls. So, whether you're a seasoned coder looking to enhance your workflow or a beginner eager to explore the possibilities, let's embark on this journey together and discover how AI can supercharge your coding endeavours.


Here Is A Quick Overview of My Checklist

  1. Do Not Use Multiple Tools for a Single Project
  2. Use CoPilot To Translate Code Into Several Languages
  3. Provide Context And Examples To Your Prompts
  4. Break Down The Coding Tasks Into Bit-Sized Steps To Provide More Context
  5. Use CoPilot To Collaborate With Your Team.
  6. Increase Usage of Domain-Specific Languages (DSL) For Complex Projects
  7. Streamline Your Preparation for Technical Interviews With Code Assistants?
  8. Context Hack: Use the ‘Act as’Prompt For Long Conversations
  9. Context Hack: Use The ‘As a’ Prompt For Short And Sweet Replies
  10. Context Hack: Create Different Dialogs For Different Contexts.?
  11. Don't Blindly Copy Code Snippets. Evaluate and Add Your Manual Code.?
  12. Automate Repetitive Tasks.?
  13. Cut Down Unnecessary Formalities
  14. Make The Documentation of AI-generated Code Compulsory Within Your Organization?
  15. Exit Vim with AI Code Assistants?
  16. Test Unfamiliar Stacks By Translating Your Code Into Other Programming Languages.
  17. Automate Unit Test For Your Code.?
  18. Identify And Respect Your Company's Ethical Guidelines Regarding AI Usage??
  19. Use Coding Assistants To Solve Algorithmic Problems


Here is a complete breakdown of each strategy


1. Do Not Use Multiple Tools for a Single Project

I enjoy reading privacy policies and legal documents before using any app or service. I've realized over time that to avoid legal complications, it's best to stick with one AI coding tool for a project, just in case any issues come up.


Why? Let me show you.?


Chat GPT and Codeium, terms of service follow Californian laws. CoPilot and Blackbox follow Canadian laws. Tabnine follows Israeli laws, Safurai follows Italian laws while Codiga follows Delaware laws. This shouldn’t be a problem. But it surprisingly is!?


Imagine a healthcare technology company using both Tabnine and CoPilot assistants to develop its Electronic Health Record (EHR) system . Now, suppose they encounter a significant lawsuit because of data breaches or medical liabilities related to their system. As such, not only does the company need to navigate the complexities of the lawsuit, but the involvement of the AI coding assistants adds an extra layer of complexity.


Tabnine is subject to Israeli laws, and CoPilot to Canadian laws. This can create complex legal issues, requiring compliance with two legal systems, document translation, and grasping the international law nuances.?


So, to simplify and minimize legal complications, use only one AI coding tool per project, ensuring consistency with the chosen tool's legal jurisdiction, streamlining the legal aspect of your project, and allowing more focus on development.


2. Use AI Coding Assistants To Translate Code Into Several Languages

CoPilot understands other languages beyond English. It understands the CSS command, 'Color' in American English. It is spelt 'Colour' in Britain, pronounced 'Couleur' in French, 'Farbe' in German, 'Colore' in Italian and 色 in Japanese. All things equal, forgetting the distinctions between ‘color’ and ‘colour’ can lead to typos, syntax errors and bugs when writing your code.?


But CoPilot's understanding of several languages means that you can write code in any version of English. As a non-native English speaker, you can write in your native language. For instance, a German developer that sends the prompt "importieren" in German, which means Import in English, will get a response from CoPilot in the same language.?


Similarly, you can translate a whole code function from English to other languages. For example, MilMikDev showcased in a Twitter Gif, how he used CoPilot to translate an array of words like 'answer', 'question' and 'date' into different languages.?



At the moment, GitHub Copilot supports different languages including English, Spanish, Japanese, French, German, Portuguese, Italian and Chinese.?


3. Provide Context And Examples To Your Prompts

AI coding assistants generate code based on the context you provide. They analyze your prompts to understand what you mean and deduce context from your past actions.?


To get a decent code, be precise with your instructions. For instance, instead of asking AI to write a short function, give the system a broad stroke of what you want such a function to achieve. Provide your preferred variable names, function signatures and the precise behaviour you expect.?


Plus, you can add examples to increase context. By offering usage examples, you provide the AI with vital context. It allows it to generate more accurate code suggestions when you provide similar prompts. It's like giving Copilot real-world usage scenarios, making it a more capable coding assistant.?


Suppose you have a custom generateReport() function in your code, but Copilot struggles with how to use it. It certainly needs more context to provide relevant code suggestions. Here's an example of how to use the generateReport() function in a real-world context:

# Example: Generate a Sales Report for Multiple Products
product_sales_data = [
    {"product_name": "Product A", "units_sold": 150, "revenue": 7500},
    {"product_name": "Product B", "units_sold": 200, "revenue": 10000},
    {"product_name": "Product C", "units_sold": 120, "revenue": 6000},
    {"product_name": "Product D", "units_sold": 180, "revenue": 9000},
]

# Generate a sales report for the products
def generateReport(product_data):
    report = "Sales Report:\n"
    total_revenue = 0

    for product in product_data:
        product_name = product["product_name"]
        units_sold = product["units_sold"]
        revenue = product["revenue"]
        
        report += f"Product: {product_name}, Units Sold: {units_sold}, Revenue: ${revenue}\n"
        
        total_revenue += revenue

    report += f"Total Revenue: ${total_revenue}"
    return report

# Generate the report for the provided product sales data
sales_report = generateReport(product_sales_data)

# Output the sales report
print(sales_report)        

This code example provides a generateReport() function that generates sales reports for multiple products based on their sales data. By giving a concrete real-world scenario, this usage example enhances Copilot's understanding of the function's purpose and allows it to generate more context-aware code suggestions.


4. Break Down The Coding Tasks Into Bit-Sized Steps To Provide More Context

Breaking complex coding tasks into smaller steps is crucial when working with Coding AI like Copilot or Tabnine. Here's a different example with CoPilot to illustrate this concept:


Imagine you're building a weather app from scratch, and you want it to display current weather, a three-day forecast, and weather alerts. You start by writing a single, comprehensive prompt for Copilot:


  1. You explain what you want for your entire weather app in one comment.
  2. ?The copilot struggles to grasp all the requirements accurately.
  3. ?Copilot can neither understand nor implement the entire logic accurately. Thus, provide the wrong code?

Rather than doing this, you break it down into smaller, manageable steps:


Step 1: Current Weather Display

Begin by creating a function or module to display the current weather. Isolate this step and focus on the function's core structure. Here's a simple code snippet for the current weather display:


def display_current_weather():
    # Fetch current weather data from an API
    weather_data = fetch_weather_data()

    # Display the current weather information
    print(f"Current Weather: {weather_data['temperature']}°C, {weather_data['condition']}")        


Step 2: Three-Day Forecast

Separate the three-day forecast feature into its module or function. Define what data you need and how it should be presented.


def display_three_day_forecast():
    # Fetch three-day forecast data from an API
    forecast_data = fetch_forecast_data()

    # Display the three-day forecast
    for day in forecast_data:
        print(f"{day['date']}: {day['condition']} - High: {day['high']}°C, Low: {day['low']}°C")        


Step 3: Weather Alerts

Lastly, address weather alerts as a distinct component. Specify how alerts should be triggered and displayed.


def check_weather_alerts():
    # Check for weather alerts from a data source
    alerts = fetch_weather_alerts()

    if alerts:
        # Display weather alerts to the user
        print("Weather Alerts:")
        for alert in alerts:
            print(f"- {alert['message']}")
    else:
        print("No weather alerts at the moment.")        


Breaking down your weather app project into smaller steps helps Copilot understand your intentions better. This approach ensures accurate implementation and allows you to tackle each feature independently. It makes your coding process more efficient and manageable, whether you're working with AI assistance or not.


5. Use CoPilot To Collaborate With Your Team.

After all, every developer working in a team uses the same coding patterns, structure, style and project-specific modules consistently. So, AI learns the consistent style within the team or organization and modifies its suggestions to align with the team's coding style. Thus, when the team on-board a new member, he easily learns the house style through the AI coding assistant.?


To make the task easier, you can team-train your AI model to fit in your local code patterns. In this case, companies like GitHub or Tabnine help you train and run the LLM on your company's system either via on-premise or Virtual Private Cloud .?


Say your team uses the Observer pattern for Python coding . The training model helps a new member to instantly recognize the pattern and tailor his code to such a style. This feature helps the system tailor its team responses to your projects, preferences and patterns.?


For instance, a company that codes its Python on an Observer Pattern will find this example indispensable. Once any team member wants to code, this pattern becomes an indispensable guideline.?


class Observer:
    def update(self, message):
        pass

class ConcreteObserver(Observer):
    def __init__(self, name):
        self.name = name
    def update(self, message):
        print(f"{self.name} received message: {message}")

class Subject:
    def __init__(self):
        self.observers = []
    def add_observer(self, observer):
        self.observers.append(observer)
    def remove_observer(self, observer):
        self.observers.remove(observer)
    def notify_observers(self, message):
        for observer in self.observers:
            observer.update(message)

if __name__ == "__main__":
    observer1 = ConcreteObserver("Observer 1")
    observer2 = ConcreteObserver("Observer 2")
    subject = Subject()
    subject.add_observer(observer1)
    subject.add_observer(observer2)
    subject.notify_observers("Hello, observers!")
    subject.remove_observer(observer2)
    subject.notify_observers("Observer 2 has been removed.")        


6. Increase Usage of Domain-Specific Languages (DSL) For Complex Projects

Here is another hack to tailor your responses. Domain Specific Languages are made for specific domains and stacks. They have distinct syntax, semantics and patterns. Using DSL help you communicate complex ideas clearly to the AI coding assistant. This language enhances its understanding of the task, reduces errors, and increases coding speed, accuracy and problem-solving skills.


7. Streamline Your Preparation for Technical Interviews With Code Assistants

Do you know you can prepare for and pass technical interviews with coding assistants? Yes, as a technical recruiter, this might seem unorthodox and borderline unethical. But it depends on how job applicants use the tool. Next time you have a technical interview scheduled, here is how you can use the tool effectively within the ethics.?


You might have a tricky coding problem to solve when preparing for interviews. But the creative juices aren't flowing. Maybe you don’t know how to structure the code or create the features to achieve the desired solution. Here is a way out?


Get your AI coding tool like Copilot or Codeium account,? and send a prompt on how to solve that problem. The AI gives you new ideas and perspectives from which you get a headway and solve the problem manually.?


This hack can help with technical interviews in different ways. It opens up your creativity juices when experiencing writer's block, gives you new and unexplored perspectives, and replaces the guiding role of a teacher or mentor. When you see similar problems during interviews, you're better at solving them, which increases your chances of being hired.?


On the other hand, I don't recommend using AI while doing interviews. That's nothing but cheating.?


8. Context Hack: Use the 'Act as' Prompt For Long Conversations.

Another hack to generate an accurate output is to make the AI a role player using the “Act as’ prompt. Whittle down the description to a specific role, job title, profession, or position. Then, ask the AI to act on the role, and include the guidelines for what the LLM must do and must not do. Then, follow it with your main question.?


The coding AI instantly takes up a specific role contextualizes your conversation and addresses your problem from that point of view.?


Take, for example, I typed the following prompt to Chat GPT to act as a javascript console?

"I want you to act as a javascript console. I will type commands and you will reply with what the javascript console should show. My first command is console.log("Good Morning Everyone");"


Here is the response?


Of course, I can act as a JavaScript console for you. Here's the response to your command:
Hello Good People        
The console.log function in JavaScript is used to print messages or values to the console, and it will display "Hello Good People" when you execute it.


9. Context Hack: Use The 'As A' Prompt For Short And Sweet Replies

Another prompt that can achieve a precise and contextual code generation with LLM, is "As a" prompt. Begin your prompt with "As a? [role name], + [optional action]." This instructs AI to generate code in a specific way, making your requests more focused.


For example, if you want LLM to help you with a Python programming problem, you can say, "As a Python developer, explain how to use a for loop." By using "As a," you're telling the AI coding tool your role and what you'd like it to do, making it easier to get coding-related assistance.


Overall, note that “Act as” is better for assigning a role for the duration of a lengthy dialogue, while “As a” is better when you want to give a role for a single reply.


10. Context Hack: Create Different Dialogs For Different Contexts

Know how to use dialogues effectively when interacting with Coding AI models to get accurate and relevant responses. To achieve this, keep your conversations fixated on a single task or topic for each dialogue. For instance, if you're inquiring about machine learning algorithms, it's better to structure all your dialogue around this subject and not introduce unrelated questions or themes. It helps the AI model contextualize your prompt, and provide coherent responses that address the specific queries effectively.


Besides, don't hesitate to create separate dialogues for distinct tasks or questions. For instance, if you have inquiries related to web development and data analysis, consider initiating two stand-alone dialogues—one for web development queries and another for data analysis questions.?


This separation prevents mixing topics and ensures the AI model maintains clarity and relevance in its responses. In short, treating each dialogue as an independent conversation allows for more efficient interactions and better outcomes when seeking information or assistance from AI.


11. Don't Blindly Copy Code Snippets. Evaluate and Add Your Manual Code.

While utilizing AI coding tools to enhance efficiency, avoid a mere copy-and-paste approach without assessing the code's purpose and functionality. Instead, thoroughly scrutinize the generated code snippets and verify their alignment with the intended behaviour. This practice will effectively shield your code from potential bugs or security concerns.?


Plus, consider integrating your manual code to strike a harmonious balance between faster coding and code quality. This approach allows you to assess the intricate nuances of your project, add your unique expertise to the code, and keep your coding skills sharp.


My strategy involves jump-starting my creativity by generating coding snippets and then proceeding to complete the task through manual coding, ensuring a holistic and informed approach to software development.


12. Automate Repetitive Tasks.

Another method I use to strike a balance between code quality and speed is to automate repetitive tasks. While manually tackling complex challenges, any mundane task goes to AI.


Hence, tasks that involve repetitive coding, like creating basic CRUD (Create, Read, Update, Delete) operations in a web application development, can benefit from AI-generated code. But you can continue practising manual coding for intricate features that require custom logic, like machine learning algorithms.


For instance, when developing a simple blog website, you can use AI-generated code to generate the user authentication and content management system (CMS) . It accelerates the initial setup process. But when executing a recommendation engine that provides personalized content recommendations based on user behaviour, the complexity necessitates the hands-on involvement of human developers to create custom algorithms.


The combo creates balance, which involves using AI for routine tasks and human expertise for complex challenges. It ensures efficient development and preserves the developer's ability to handle intricate coding tasks.


13. Cut Down Unnecessary Formalities

While maintaining as much detail as possible, keep your prompts brief by avoiding formality. Every word in your input determines the complexity and potentiality of what comment the AI will give. So, the caveat here is to avoid unnecessary formalities. Otherwise, the LLM might get confused which might alter its responses.?


Take, for example, avoid words like "Can you…", "Will you…", "Can I help…". Rather, go straight to the point. Unlike AI writing assistants, an AI coding tool only cares about the context, nuances and relationships amongst the words you use, not with proper grammar or formality.?


14. Make The Documentation of AI-generated Code Compulsory Within Your Organization.

Make it a rule that your developers must document AI-generated code. First, it helps them delve deeply into the details, nuances and relationships of the code, and then spot mistakes and hidden discrepancies. They can also find parts that can be better optimized, where it needs integration and potential hotspots that can compromise its security.?


Besides, code documentation provides headway into code maintenance, testing, debugging and continued code optimization during upgrades.?


That is, as software development evolves, future developers need to understand how the code works. This is important for fixing problems, adding new features, or integrating the code smoothly with other parts. Code that doesn't have clear explanations can become hard to change or understand over time.


Because AI can be difficult to decipher, people need to write down how it works. This helps us see what's going on inside the AI-generated code, just like we do for code written by people.?


15. Exit Vim with AI Code Assistants.

Getting trapped in the decades-old code editor, Vim is one of those experiences a Neovim first-time user struggles with.?


This is probably because its functions aren't always intuitive. It won't quit with a single command like "q" unless you type ":q" and click the escape key. Exiting Vim had been such a problem that it turned into an internet meme.?


But thankfully, an AI coding assistant integrated into Neovim can help you leave the editor. Here is a complete video guide on how to exit NeoVim using Copilot. Enjoy ???



16. Test Unfamiliar Stacks By Translating Your Code Into Other Programming Languages.

Here is an atypical yet effective use case of AI coding assistants. They can help you translate your code into any supported language or framework. This benefit can come in handy in several ways.?


First, you can translate old legacy codes into modern languages, like changing an old Fortran code to C or Python. Or reuse a brilliant code in another project. Translating the code will save more time and reduce errors compared to manually typing the codes.?


Besides, you can prototype your applications with a flexible language like Python. Then, subsequently, enhance their performance in a statically compiled language. That is, you go all into algorithm development with Python and compile it into a statically typed language like C++ when seeking better speed and type safety.


It is worth knowing though that the language features don’t overlap perfectly for every code. Thus, you still have to check and iterate the responses, do an in-depth check on the code, rewrite some parts and until you get a functional and satisfactory code.


This video gives a complete guide on how to translate code from one language to another using Github Copilot.?



17. Automate Unit Test For Your Code.

Tabnine and Copilot learn from your code as you write them. Hence, the more you use the tool, the better it becomes at generating tests that match your pattern. By using artificial intelligence, it can then write unit tests and visual regression tests via a simple prompt.?


If you want to generate unit tests via Copilot, check out this webinar . But if you are a ChatGPT freak, the video below might be useful.?



18. Identify And Respect Your Company's Ethical Guidelines Regarding AI Usage.

Most companies ban the use of AI in their companies, to prevent leaking of sensitive information. A Samsung employee once released classified information on Chat GPT which put their source code in jeopardy. Here, the rule of thumb is to follow your company's guidelines regarding the use of AI.?


And besides, clamping down on AI is more stringent in some sectors than others. Most industries in finance, Healthcare, and the government have prohibited using Copilot, or Tabnine within the organization data mainly for security concerns. Some others that use AI provide adequate guidelines for usage. It's important to acknowledge and comply with these regulations.?


19. Use Coding Assistants To Solve Algorithmic Problems

When diving into algorithmic challenges or coding tasks, Copilot is your trusty companion who can effortlessly generate code for all those algorithms, data structures, or optimization strategies. Think of it as your coding sidekick, there to help you breeze through the technicalities and let you concentrate on cracking the main puzzle.


Imagine you're working on a project that requires you to remove duplicates from an array. You sit down to write the code in your preferred programming language, and Copilot jumps in with a handy suggestion like this:


Let’s say you're working on a project that involves finding all the prime numbers within a given range, say from 1 to 100. This problem requires you to identify and list all the prime numbers (numbers divisible only by 1 and themselves) within this range. As you prepare to write the code in your preferred programming language, Copilot can jump in with a handy suggestion like this:


def find_prime_numbers(start, end):
    prime_numbers = []
    for num in range(start, end + 1):
        if num > 1:
            is_prime = True
            for i in range(2, int(num ** 0.5) + 1):
                if num % i == 0:
                    is_prime = False
                    break
            if is_prime:
                prime_numbers.append(num)
    return prime_numbers        

In this scenario, Copilot helps you generate code that efficiently identifies and collects all the prime numbers within the specified range. It's like having a coding partner who's well-versed in complex algorithms, making challenging problems more manageable. Pretty nifty, isn't it?


Conclusion

As you navigate the realm of AI coding tools, a few standout practices can significantly enhance your coding journey. First, the importance of providing clear context and examples to AI assistants cannot be overstated. Precision in instructions and illustrative examples can remarkably boost the accuracy of code generation. Additionally, breaking down complex coding tasks into manageable steps allows these tools to better understand your intentions, making your coding process more efficient and effective. These practices, among others, offer a glimpse into the transformative potential of AI in coding.?


I hope you enjoyed the article. If you find the tips useful, don’t forget to like and share them with anyone who might need them. I would love to know your experiences and thoughts on these techniques. Have you tried them? How did it work out? Do you have any other tricks not covered in this article that will benefit readers? Share your thoughts in the comment section below.?

要查看或添加评论,请登录