Ideas to help code

I have caught myself doing this often, and need to always regroup and figure out what is a better way to do these types of things. I am speaking of coding in absolutes. What does this mean? Coding a type of block that is hard set to do something exactly. Like for an example, let’s say that there is a calendar application. In this calendar application, there are four languages to select from, so a code block does something like this:

// Controller file
$eng = $this->Users->Select("language", "English");
$spn = $this->Users->Select("language", "Spanish");
$gmn = $this->Users->Select("language", "German");
$fre = $this->Users->Select("language", "French");

**Note this is not using any kind of construct in CakePHP, Symfony or any particular framework, just an example of a User class with a function called Select passing in 2 variables.

As an example, the view of this same code may be something like:

// Controller File
$this->set('lang', array($eng, $spn, $gmn, $fre);

Now while this may work for the time being, it could cause a hassle later on if there are more languages that the application will need to support.

Now, this is not saying that the above example is bad practice, because it is entirely possible that it will only need these two languages. Like if you were programming an application for a Canadian business, it would need to have both English and French. There may never be a requirement for Spanish, German, or any other language. What I am doing more of now, is making things more dynamic, to handle new items seamlessly and with little new code.

Taking the above example, we could put it into something like so:

// Model File
class User extends someBaseModelObject {
. . . 
function getLanguages(){
      $langs = array(
          "English", "German", "Spanish", "French"
      );
      return $langs;
}

// Controller File
$langs = $this->User->getLanguages();

$this->set('lang', $langs);

Now if there is a new language, all that needs to be updated is the Model file instead of adding new lines of code to one part, updating another line of code in another part, and so on.

Is this possibly an oversimplification of this idea? Yes it is. But I do not write this as a simplification, but to just show something I am starting to focus on more, is that I need to make things more dynamic so I do not have to re-do code as new things are added. I use language as an example in this post, because that is just an easy example to show. There are many things that could be done for dynamic purposes. It is all about thinking about the right way to code.

Leave a Reply