What is hard coding

Hard coding in programming terms is the creation of code with elements that are inflexible and require changes from the inside. A program should work consistently without the need to alter its internal data. Hard coded lines of code diminish this goal. By eliminating hard coded values we increase re usability and have the ability to create libraries that can be used in different environments:

/* our database is hard coded, therefore making a change to a new database very painful */ $query = ' SELECT * FROM books '; $result = mysql_query($query); /* the actual database is now encapsulated and we can change it in a configuration file */ Database::setDatabase(MYSQL); $query = ' SELECT * FROM books '; $result = Database::query($query);

We should also try to eliminate hard coded values from our functions to make them re usable:

/* inflexible ridiculous functions */ function getName($array) { return $array['name']; } function getSex($array) { return $array['sex']; } /* a more flexible ridiculous function */ function getValue($array, $name) { return $array[$name]; }

Hard coding can also be thought of as incorrectly naming elements. Using incorrect names can make changing internal data very difficult. Therefore names should be verbs and not nouns. For example:

/* the colour green is hard coded into our class name (noun), therefore changing our colours in the box will break our name */ .green-box { background:#17ce65; border:1px solid #427a4e; color:#0f3f0b; padding:5px; text-align:center; } /* our class name is now more general (verb) and its internals can be changed */ .success-box { background:#17ce65; border:1px solid #427a4e; color:#0f3f0b; padding:5px; text-align:center; }

Hard coding values into our scripts causes inflexibility and modularity problems. There are no correct solutions and correct ways to do things. All you need to do is think about how you can write code that can be used in multiple environments without the need for change.