Can We Trust Code Written by AI? What We Should and Shouldn't Do

Can We Trust Code Written by AI? What We Should and Shouldn't Do



Introduction

AI coding assistants have changed the way we write software. Developers can now generate functions, create API integrations, write unit tests, fix bugs, and even build entire application features by describing what they need in natural language.

What once took hours can sometimes be accomplished in minutes.

But there is an important question we should ask ourselves:

Just because AI can generate code that works, does that mean we can trust it?

The answer is no—not without verification.

AI-generated code can be syntactically correct, look well structured, and pass a few basic tests while still containing security vulnerabilities, logical errors, performance problems, or hidden assumptions.

The real risk is not using AI to write code. It is assuming that code generated by AI is correct simply because it looks convincing.

As software engineers, developers, and QA professionals, we need to change how we approach code generated by AI. We should focus not only on how quickly code can be produced, but also on how confidently we can verify it.

1. Why AI-Generated Code Cannot Be Trusted Blindly

AI models generate code based on patterns learned during training and the context provided in a prompt. They do not automatically understand every detail of our application's architecture, business rules, security requirements, or production environment.

Consider a simple example.

A developer asks an AI assistant to create a login API. The generated code might successfully authenticate a user and return a response. However, it could also:

  • Store passwords insecurely.

  • Fail to validate input correctly.

  • Expose sensitive information in error messages.

  • Allow improper access to protected resources.

  • Lack rate limiting or adequate abuse protection.

  • Use outdated or vulnerable dependencies.

The code might work in a demonstration but fail under real-world conditions.

This is why code correctness and code trustworthiness are not the same thing.

A successful execution proves only that the code worked for a particular scenario. It does not prove that the code is secure, reliable, maintainable, or correct for every expected situation.

2. What We SHOULD Do When Using AI to Generate Code

Understand the code before accepting it

Never merge code that you cannot explain.

If AI generates a complex function, ask it to explain the logic, assumptions, edge cases, and dependencies. Then independently verify that explanation against the actual requirements and code.

AI explanations can also be incorrect, so understanding must come from reviewing and validating the implementation—not simply asking AI whether its own code is correct.

Review the code as if another developer wrote it

AI-generated code should go through the same review process as human-written code.

Check:

  • Whether the implementation satisfies the requirements.

  • Whether error handling is appropriate.

  • Whether input validation is sufficient.

  • Whether the code follows project conventions.

  • Whether unnecessary complexity has been introduced.

  • Whether sensitive information is handled correctly.

  • Whether the changes introduce unexpected side effects.

A pull request should not receive automatic approval simply because AI generated the implementation.

Validate security explicitly

Security should be considered from the beginning, not added as an afterthought.

Review AI-generated code for common weaknesses, including:

  • SQL injection and command injection.

  • Cross-site scripting (XSS).

  • Broken authentication and authorization.

  • Insecure direct object references and other access-control failures.

  • Hardcoded secrets and credentials.

  • Insecure file handling.

  • Sensitive information exposed through logs or API responses.

  • Unsafe deserialization and insecure dependency usage.

Use appropriate security tools, such as static application security testing (SAST), software composition analysis (SCA), secret scanning, and dynamic application security testing (DAST).

These tools help identify risks, but they cannot guarantee that code is secure. Manual review and threat modelling remain important, especially for sensitive functionality.

Test beyond the happy path

One of the biggest mistakes is accepting AI-generated code because it works for a simple example.

Testing should include:

  • Positive scenarios.

  • Negative scenarios.

  • Boundary values.

  • Invalid and unexpected input.

  • Empty or missing values.

  • Authentication and authorization failures.

  • Dependency failures and timeouts.

  • Concurrent requests, where relevant.

  • Regression scenarios.

For example, if AI generates a refund function, testing a successful refund is not enough. What happens if the refund is requested twice? What if the payment provider times out after processing the refund? What if the user does not have permission to request it?

The quality of the test scenarios is just as important as the quality of the generated code.

Use AI to challenge the implementation

AI can be useful not only for generating code but also for identifying possible weaknesses.

You can ask it to:

  • Review the code for security vulnerabilities.

  • Identify missing edge cases.

  • Suggest negative test scenarios.

  • Explain potential race conditions.

  • Identify assumptions that need verification.

  • Suggest performance and reliability tests.

However, do not treat a second AI review as independent proof that the implementation is safe. Different prompts can reveal different issues, but AI reviewers can share similar blind spots.

Always validate important findings independently.

Keep humans accountable

AI can assist with implementation, but responsibility for the resulting software remains with the people and organisation delivering it.

Developers must understand and review their changes. QA engineers must challenge assumptions and validate behaviour. Security specialists should assess high-risk changes. Engineering leads must ensure that appropriate review and release controls exist.

AI should strengthen these responsibilities, not replace them.

3. What We SHOULD NOT Do When Using AI to Generate Code

Don't copy and paste code directly into production

Generated code should never bypass the normal development process.

It should be reviewed, tested, scanned where appropriate, and validated against the application's requirements before deployment.

Even a small code change can introduce a serious vulnerability if it affects authentication, payment processing, permissions, or data handling.

Don't assume that passing tests means the code is correct

AI can generate tests that validate the same incorrect assumptions used to generate the implementation.

For example, AI might generate a discount calculation function and write a unit test that expects the same incorrect discount formula.

The test passes, but both the implementation and the test are wrong.

This is why tests should be derived from independently understood requirements, business rules, and expected outcomes—not solely from the generated implementation.

Where possible, use independent test data, boundary-value analysis, property-based testing, and mutation testing to improve confidence.

Don't allow AI to make security decisions without review

Avoid blindly accepting generated authentication mechanisms, cryptographic implementations, access-control rules, or permission checks.

Security-sensitive functionality should use established, maintained libraries and frameworks wherever possible.

For example, passwords should be handled using appropriate password-hashing algorithms rather than custom encryption logic suggested by an AI tool.

Similarly, authorisation should be enforced on the server side, even if the frontend already hides restricted actions.

Don't expose confidential information in prompts

Before sending code or technical details to an AI tool, understand the tool's data-handling policies and your organisation's rules.

Do not paste production credentials, API keys, private customer data, confidential insurance records, or proprietary information into an unapproved AI service.

Use approved tools, appropriate access controls, and redacted examples whenever possible.

Don't ignore dependencies and licensing

AI-generated code may introduce unfamiliar packages, outdated APIs, or dependencies with known vulnerabilities.

It may also produce code whose provenance or licensing is unclear.

Review new dependencies, verify that they come from legitimate sources, check their maintenance and security status, and follow your organisation's open-source licensing policies.

Never install a package simply because AI recommends it.

Don't sacrifice maintainability for speed

AI can generate large amounts of code very quickly. That does not mean the code is well designed.

Avoid accepting unnecessary abstractions, duplicated logic, excessive dependencies, or complex implementations that the team cannot maintain.

The goal is not to generate the maximum amount of code. It is to deliver reliable software with a reasonable cost of ownership.

4. The Role of QA in an AI-Assisted Development World

AI changes how quickly code can be written, but it does not remove the need for quality engineering. In fact, it can make independent verification even more important.

QA teams should consider evolving their practices in several areas.

Risk-based testing: Identify which AI-generated changes affect security, financial transactions, customer data, business-critical calculations, or other high-impact functionality.

Independent test design: Derive tests from requirements and business rules instead of relying only on tests generated alongside the implementation.

Automation and CI/CD: Integrate unit tests, integration tests, regression tests, static analysis, dependency scanning, and other relevant quality checks into the delivery pipeline.

API and contract testing: Validate service boundaries, data formats, error responses, authentication, and compatibility between dependent systems.

Observability: Monitor errors, unexpected behaviour, performance, and security signals after release. Testing before deployment cannot reveal every production issue.

AI-specific risk assessment: Consider whether the generated code relies on unsupported assumptions, insecure patterns, or behaviour that is difficult to explain and verify.

QA should not become a bottleneck that reviews every line manually. Instead, QA should help establish the risk-based controls that make faster development safe.

5. A Practical Checklist Before Merging AI-Generated Code

Before approving an AI-assisted pull request, ask the following questions:

  • Does the implementation meet the actual business requirements?

  • Can the author explain how the code works?

  • Have edge cases and negative scenarios been tested?

  • Are authentication and authorisation handled correctly?

  • Has the code been reviewed for injection, data exposure, and other relevant security risks?

  • Have new dependencies been checked?

  • Do automated tests validate independently established expectations?

  • Have relevant unit, integration, and regression tests passed?

  • Have static analysis and security checks been completed where appropriate?

  • Are logs, error handling, and sensitive data handled safely?

  • Is the change maintainable and consistent with the existing architecture?

  • Are appropriate human reviews and release controls in place?

Not every question applies equally to every change. A documentation update and a payment-processing change do not carry the same level of risk.

The checklist should therefore be adapted to the type of change and its potential impact.

6. The Mindset We Need to Adopt

The most important change is not a new tool or testing framework. It is a change in mindset.

We should move from asking:

“Can AI generate this code?”

to asking:

“How will we verify that this code is correct, secure, and fit for purpose?”

AI can reduce implementation time, accelerate learning, and help engineers explore alternative solutions. But generating code is only one part of software development.

Requirements analysis, architecture, security, testing, code review, deployment, and monitoring remain essential.

The more code we generate, the more important it becomes to have effective ways to verify it.

Conclusion

Can we trust code written by AI?

We can build confidence in AI-generated code, but that confidence must be earned through evidence.

We should use AI to accelerate development, improve test coverage, explore potential vulnerabilities, and support engineering decisions. We should not use it as an excuse to skip code reviews, ignore security, or accept unverified assumptions.

The future of software engineering is unlikely to be about choosing between human-written and AI-generated code. It will be about combining the speed of AI with human judgement, independent verification, and strong engineering practices.

AI can help us write code faster. It is our responsibility to make sure that code deserves to be trusted.

Comments