---
title: "What Is Hardcoding? Hard Coded Values Simply Explained"
canonical_url: "https://robocitrus.com/en/blog/was-ist-hardcoding"
last_updated: 2026-02-12
locale: en
meta:
  description: "What does hard coded mean? Learn why hardcoded values in programming cause problems and how to avoid them. Explained with practical code examples."
  "og:description": "What does hard coded mean? Learn why hardcoded values in programming cause problems and how to avoid them. Explained with practical code examples."
  "og:title": "What Is Hardcoding? Hard Coded Values Simply Explained"
---

RoboCitrus - Home

![What Is Hardcoding? Why Hard Coded Values Are a Problem](https://robocitrus.com/cdn-cgi/image/w=2048,q=75/images/blog/was-ist-hardcoding.webp)

# **What Is Hardcoding? Why Hard Coded Values Are a Problem**

[![Maximilian Flechtner](https://robocitrus.com/cdn-cgi/image/q=75/images/about-me-maximilian-image.webp)**Maximilian Flechtner**](https://robocitrus.com/en/about)

Published:February 12, 2026

1 min read

[**Technology**](https://robocitrus.com/en/blog/tags/technology) [**Beginners**](https://robocitrus.com/en/blog/tags/beginners) [**App Development**](https://robocitrus.com/en/blog/tags/app development)

If you read programming code or talk to developers, you'll eventually hear the term "hardcoding." Sounds like a deliberate approach, but it's usually a mistake. Let me explain what hardcoding is, why hard coded values cause problems, and when it's actually okay to hard code something.

---

## Video: API Keys in Code? Why That's a Problem

--- ## Quick Summary - **Hardcoding** means writing fixed values directly into source code instead of making them configurable - Hardcoded values make code hard to maintain, insecure, and inflexible - Typical examples: hard coded passwords, API URLs, file paths, or "magic numbers" - The alternative: environment variables, config files, and named constants - In certain cases (mathematical constants, fixed enums), hardcoding is perfectly fine --- ## What Is Hardcoding? Hardcoding (also hard coding or hard-coding) is the practice of writing a fixed value directly into your program code instead of making it configurable from the outside. A hardcoded value sits literally in your code and can only be changed by editing the code itself. So what does hard coded mean? In simple terms: "This value is baked into the code and cannot be changed from the outside." Here's a simple example in JavaScript:```
// Hard coded: The color is fixed in the code
function getHeaderColor() {
  return '#FF5733';
}

// Better: The color comes from a configuration
function getHeaderColor(config) {
  return config.headerColor;
}
``` In the first case, the color is hardcoded. If you want to change it, you need to touch the code, recompile, and redeploy. In the second case, you read the color from a configuration. You can adjust it anytime without changing a single line of code. That's the hardcoded definition in one sentence: A value that lives directly in source code instead of coming from an external source. ## An Everyday Analogy Imagine you buy a new GPS navigation device. But instead of an address input, someone has hard coded the address "123 Main Street, Berlin" into the device. No matter where you want to go, the GPS always navigates to 123 Main Street. To enter a different destination, you'd have to open up the device and reprogram the circuit board. Sounds absurd? That's exactly what happens with hard coding in programming. Instead of giving the user (or the system) the ability to input a value, it's permanently built in. Like a GPS that only knows one single address. A configurable GPS, on the other hand, lets you type in any address you want. That's the difference between hard coded and configurable. ## Examples of Hardcoding Here are four typical cases I encounter constantly in practice. I'll show them in JavaScript and Dart, since those are the languages I work with daily. If you want to understand the difference between [**frontend and backend**](https://robocitrus.com/en/blog/frontend-vs-backend) languages, check out my article on that. ### 1. Hardcoded API URL```
// Hard coded: URL is fixed in the code
async function fetchUsers() {
  const response = await fetch('https://api.myapp.com/v2/users');
  return response.json();
}

// Better: URL from environment variable
async function fetchUsers() {
  const response = await fetch(\`${process.env.API_BASE_URL}/users\`);
  return response.json();
}
``` The problem: When you switch from your development environment to production, you have to change the code. Or worse: you forget and your live app sends requests to the test server. ### 2. Hardcoded Password```
// Hard coded: Credentials directly in code (never do this!)
async function connectDatabase() {
  const connection = await db.connect({
    host: 'localhost',
    user: 'admin',
    password: 'secret123'
  });
  return connection;
}

// Better: Credentials from environment variables
async function connectDatabase() {
  const connection = await db.connect({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD
  });
  return connection;
}
``` Hard coded passwords in source code are a security risk. Anyone with access to the code (and for open-source projects, that's everyone) can see your credentials. Even if you change the password later, it remains visible in the Git history. ### 3. Magic Numbers```
// Hardcoded: What does 86400 mean?
Future<void> refreshToken() async {
  await Future.delayed(Duration(seconds: 86400));
  await getNewToken();
}

// Better: Named constant
const int secondsPerDay = 86400;

Future<void> refreshToken() async {
  await Future.delayed(Duration(seconds: secondsPerDay));
  await getNewToken();
}
``` 86400 is the number of seconds in a day. But only people who've done the math know that. These "magic numbers" make code unreadable. In six months, even you won't remember why 86400 is there. Hardcoded numbers without context are a classic code smell. ### 4. Hardcoded File Paths```
// Hard coded: Path only works on your machine
function loadConfig() {
  return readFile('/Users/max/projects/myapp/config.json');
}

// Better: Relative path or environment variable
function loadConfig() {
  return readFile(path.join(process.env.APP_ROOT, 'config.json'));
}
``` Absolute file paths tailored to a specific machine break on every other system. Your colleague clones the code and nothing works because their username isn't "max." ## Why Is Hardcoding a Problem? Hardcoding causes the same problems over and over:**Maintenance nightmare.** When a value changes (and values always change), you have to find every instance in the code and manually update it. If you've hard coded the API URL in 15 places, you need to find all 15. Miss one and you've got a bug.**Security risk.** Hardcoded passwords, API keys, and credentials in code are an attack vector. They end up in Git repositories, backups, and on every team member's machine. One leak and your database is wide open.**No flexibility.** Hard coded values work in exactly one environment. If you want to switch between development, staging, and production, you have to change the code every time. That's error-prone and annoying.**Hard to test.** If a function has a hard coded API URL, you can't test it with a mock server without changing the code. Configurable values make your tests more flexible and reliable. ## The Alternative: Configurable Values The solution to hardcoding is configurable values. There are several approaches you can combine depending on the situation. ### Environment Variables (.env) The classic approach. You store values in a `**.env**` file that doesn't go into the Git repository:```
# .env
API_BASE_URL=https://api.myapp.com
DB_PASSWORD=secure_password
``````
// In code
const apiUrl = process.env.API_BASE_URL;
```### Configuration Files For more complex settings, JSON or YAML files work well:```
{
  "theme": {
    "primaryColor": "#FF5733",
    "maxUploadSize": 10485760
  }
}
```### Named Constants For values that don't change in code but need a descriptive name:```
const double taxRate = 0.19;
const int maxRetries = 3;
const String defaultLanguage = 'en';
``` This isn't hardcoding in the negative sense. The value is in the code, yes, but it has a descriptive name. The difference: A constant tells you what the value means. A hardcoded value just sits there without context. ### Dependency Injection In larger projects, you pass dependencies from the outside:```
class ApiClient {
  final String baseUrl;

  ApiClient({required this.baseUrl});

  Future<List<User>> fetchUsers() async {
    final response = await http.get(Uri.parse('$baseUrl/users'));
    return parseUsers(response.body);
  }
}

// Usage
final client = ApiClient(baseUrl: Environment.apiUrl);
``` This way you can use a mock server in tests and the real server in production without changing any code. ## When Is Hardcoding Okay? Not every fixed value in code is automatically bad. There are cases where hard coding is perfectly fine:**Mathematical constants.** Pi is 3.14159. That's not going to change. The number of seconds per minute (60) or bytes per kilobyte (1024) are fixed values you can hardcode, ideally as named constants.**Enum values.** Status codes like `**active**`, `**inactive**`, `**pending**` are part of your business logic. They belong in the code because they are the code.**Truly fixed values.** If a value is guaranteed to never change and is only used in one place, hardcoding is pragmatic. Over-engineering is not a solution either. The rule of thumb: If you can imagine a value changing in the future or being needed in multiple places, make it configurable. ## Hardcoding in App Development In mobile app development, hardcoded values show up all the time, and they bite you harder here than anywhere else. ### Hard Coded API Keys in Apps```
// Hardcoded: Anyone can extract the key from the app
class PaymentService {
  final String apiKey = 'sk_live_abc123secret';

  Future<void> processPayment(double amount) async {
    // ...
  }
}

// Better: Key comes from your own backend
class PaymentService {
  Future<String> getApiKey() async {
    final response = await http.get(
      Uri.parse('${Environment.apiUrl}/config/payment-key'),
      headers: {'Authorization': 'Bearer ${userToken}'},
    );
    return jsonDecode(response.body)['key'];
  }
}
``` Mobile apps can be decompiled. A hard coded API key in a published app is like leaving your house key under the doormat. Anyone who knows where to look will find it. That's why sensitive keys belong on the server, not in app code. ### Hardcoded Colors Instead of Themes```
// Hard coded: Colors scattered everywhere in the code
class LoginButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(
        backgroundColor: Color(0xFF2196F3),
        foregroundColor: Color(0xFFFFFFFF),
      ),
      onPressed: () {},
      child: Text('Login'),
    );
  }
}

// Better: Use a theme
class LoginButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(
        backgroundColor: Theme.of(context).colorScheme.primary,
        foregroundColor: Theme.of(context).colorScheme.onPrimary,
      ),
      onPressed: () {},
      child: Text('Login'),
    );
  }
}
``` If you hard code colors and the client says "I'd rather have green instead of blue," you have to find and change every single color value in the code. With a theme, you change one place and the entire app adapts. This gets even worse when you offer a dark mode. ### Hardcoded Strings Instead of Localization```
// Hard coded: Only works in English
Text('Welcome back!')

// Better: Localized
Text(AppLocalizations.of(context)!.welcomeBack)
``` If you want to offer your app in other languages later, hardcoded strings become a real problem. You have to find and extract every single text. If you use localization from the start, a new language is just a translation file. ## How Do I Find Hardcoded Values in My Code? There are a few practical approaches: - **Code search**: Search for typical patterns like `**http://**`, `**https://**`, IP addresses, or conspicuous numbers - **Linter rules**: Many linters (like ESLint or dart analyze) have rules that warn about magic numbers or hard coded strings - **Code reviews**: A second pair of eyes often catches hardcoding that you missed yourself - **Static analysis**: Tools like SonarQube automatically scan your code for problematic patterns ## Conclusion Hardcoding is one of those mistakes that seems harmless at first. The code works, after all. But long-term, you're accumulating technical debt that will catch up with you. Every hard coded value is a small time bomb: Eventually it needs to change, and then things get expensive. The good news: it's not hard to do it right. Environment variables, config files, and named constants solve 90% of all hardcoding problems. It takes very little effort, but saves you a lot of pain down the road. My tip: When you type a value into your code, briefly ask yourself: "Could this ever change?" If yes, make it configurable. Your future self will thank you. ## Frequently Asked Questions [**What is Git? Version Control Simply Explained for Beginners** Git is like a time machine for your code. Learn why every developer uses Git and how to safely manage projects with it. No prior knowledge required.](https://robocitrus.com/en/blog/was-ist-git) [**What Is OAuth? Login with Google & Apple Explained Simply** What is OAuth? I explain OAuth 2.0, social login with Google and Apple, the authorization flow, and why OAuth is safer than classic logins. With a Flutter example.](https://robocitrus.com/en/blog/was-ist-oauth) ## **Let's Connect! 🚀**### **Ready for your next project? **** Let's get started!**![Maximilian Flechtner - Gründer](https://robocitrus.com/cdn-cgi/image/w=3840,f=png,q=75/images/about-me-maximilian-image.webp) #### **Maximilian Flechtner **[flechtner@robocitrus.com](mailto:flechtner@robocitrus.com) [ +49 0176 41766223](tel:+4917641766223) ### **Let's get started** Tell me about your vision – just drop me an email or use the contact form. Let's plan your digital success together! 💪 [Send me an email](mailto:flechtner@robocitrus.com) [Contact Form](https://robocitrus.com/en/kontakt)