Showing posts with label gayan virajith. Show all posts
Showing posts with label gayan virajith. Show all posts

Friday, January 4, 2013

PHP implode function

implode() Function

The implode function is used to join an elements of an array with a string.

The implode() function returns a string from elements of an array. It takes an array of strings and joins them together into one string using a delimiter (string to be used between the pieces) of your choice.

The implode function in PHP is easily remembered as "array to string", which simply means that it takes an array and returns a string. It rejoins any array elements and returns the resulting string, which may be put in a variable.

Let's take an example:

If you want to separate array values with a dashed (-), Following statement is just fine.

<?php

$array = array('XXX', 'TTT', '2123123');
$dash_separated = implode("-", $array);

var_dump($dash_separated);

It will output the result as follows :

string(15) "XXX-TTT-2123123"

Here are the tricky ways of implode will get naughty.

1) When try to implode with empty array.
eg:

<?php
//When using empty array it will return empty string even passed the glue 
var_dump(implode('hello', array()));


Above code will output empty string as :


string(0) ""


2) When try to implode with array with boolean.

eg:
<?php

//When imploding boolean values it will just return the values of true
var_dump(implode('',array(true, true, false, false, true)));



Above code will output only true(s) as :

string(3) "111"

Advanced usage of implode method

If you are dealing with sql functions the implode method is just perfect. try following codes:

<?php

//Quite handier with sql functions with arrays

$fields = array(
        'subject' => 'go green',
        'message' => 'i am going to take off!'
);

$sql = 'INSERT INTO table_name';
$sql .= " VALUES (`" . implode("`,`", array_keys($fields)) . "`)";
$sql .= " ('" . implode("','", $fields) . "')";

var_dump($sql);

$userIds = array(2, 32, 55, 200, 44);

$sql2 = "SELECT * FROM table_name";
$sql2 .= " WHERE 1 AND (id=" . implode(" OR id = ", $userIds) . ")";

var_dump($sql2);



Above codes will give the output as follows:


string(90) "INSERT INTO table_name VALUES (`subject`,`message`) ('go green','i am going to take off!')"
string(88) "SELECT * FROM table_name WHERE 1 AND (id=2 OR id = 32 OR id = 55 OR id = 200 OR id = 44)"

Happy coding ~

Thursday, September 13, 2012

Transactions in MySQL


Definition of a transaction

A transaction is an atomic unit of database operations against the data in one or more databases. The effects of all the SQL statements in a transaction can be either all committed to the database or all rolled back.

MySQL supports several storage engines. The InnoDB is fully ACID compliant. The ACID stands for Atomicity, Consistency, Isolation and Durability. Reliable transactions must support all these four properties.

Operations within a transaction must be atomic. This means, that either all operations succeed or fail. This is all or nothing rule. The consistency property ensures that the database is in a consistent state after the transaction is finished. The data is valid and there are no half-finished records. For example there are no customers left with no payment records or there are no payment records without customers. Isolation is the requirement that other operations cannot access data that has been modified during a transaction that has not yet completed. The question of isolation occurs in case of concurrent transactions. Without isolation, the data may end up in inconsistent state. Durability is the ability of the database system to recover the committed transaction updates against any kind of system failure.

The default transaction isolation level for MySQL is repeatable read.

mysql> SELECT @@tx_isolation;
+-----------------+
| @@tx_isolation  |
+-----------------+
| REPEATABLE-READ |
+-----------------+

The current isolation level is stored in the tx_isolation server variable.

mysql> SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

mysql> SELECT @@tx_isolation;
+----------------+
| @@tx_isolation |
+----------------+
| SERIALIZABLE   |
+----------------+

We can change the isolation level with the SET TRANSACTION ISOLATION LEVEL statement.


Autocommit


MySQL also automatically commits statements that are not part of a transaction. The results of any UPDATE or INSERT statement not preceded with a START will immediately be visible to all connections.

mysql> SELECT @@autocommit;
+--------------+
| @@autocommit |
+--------------+
|            1 |
+--------------+

The autocommit variable is set by default.

mysql> SET autocommit=0;

mysql> SELECT @@autocommit;
+--------------+
| @@autocommit |
+--------------+
|            0 |
+--------------+

The autocommit can be turned off.
Now we are going to demonstrate the autocommint variable.

mysql> SELECT @@autocommit;
+--------------+
| @@autocommit |
+--------------+
|            1 |
+--------------+

CREATE TABLE Test(Num INTEGER NOT NULL) engine=InnoDB;

The autocommit is set. We create a simple Test table with InnoDB storage engine, which supports transactions.

mysql> INSERT INTO Test VALUES (1), (2), (3);

mysql> SELECT * FROM Test;
+-----+
| Num |
+-----+
|   1 |
|   2 |
|   3 |
+-----+

We insert three rows into the column of the table. The values are immediately committed.

mysql> SET autocommit=0;

mysql> INSERT INTO Test VALUES (4), (5);

mysql> SELECT * FROM Test;
+-----+
| Num |
+-----+
|   1 |
|   2 |
|   3 |
|   4 |
|   5 |
+-----+

Now we set the autocommit variable to false. We insert two values and select all data from the table. We have now 5 rows in the table.

mysql> ROLLBACK;

mysql> SELECT * FROM Test;
+-----+
| Num |
+-----+
|   1 |
|   2 |
|   3 |
+-----+

However, the data is not permanently written to the table. With the ROLLBACK statement, we take them back.

mysql> INSERT INTO Test VALUES (4), (5);

mysql> COMMIT;

mysql> ROLLBACK;

mysql> SELECT * FROM Test;
+-----+
| Num |
+-----+
|   1 |
|   2 |
|   3 |
|   4 |
|   5 |
+-----+

Now we insert value 4, 5 again. This time, the rows are committed with the COMMIT statement. Subsequent rollback statement has no effect.


Starting transactions

With autocommit enabled, each single SQL statement is wrapped automatically in its own transaction. To start our own transaction, we issue the START TRANSACTION statement. The transaction is later finished with the COMMIT or ROLLBACK statements. Multiple statements may be issued in the body of the transaction. All are either committed or rolled back as one unit.

mysql> TRUNCATE Test;
Query OK, 0 rows affected (0.02 sec)

mysql> SELECT * FROM Test;
Empty set (0.00 sec)

We will work with the same Test table. We truncate the data in the table.

mysql> START TRANSACTION;

mysql> INSERT INTO Test VALUES (1), (2);

mysql> INSERT INTO Test VALUES (3), (4);

mysql> SELECT * FROM Test;
+-----+
| Num |
+-----+
|   1 |
|   2 |
|   3 |
|   4 |
+-----+

In the above code, we start a transaction and insert four rows into the table. The values are not yet committed. From the current connection the rows are visible.

$ mysql -uroot -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 65
Server version: 5.1.41-3ubuntu12.9 (Ubuntu)

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> SELECT * FROM mydb.Test;
Empty set (0.00 sec)


However, from a different connection, the Test table is empty. We launch a new instance of a mysql client program. This is a different connection to the MySQL database. From this connection, the values are not yet visible.


mysql> COMMIT;

Finally, the COMMIT statement commits the data to the table. The rows are visible from both connections.

We start another transaction. This time the data will be rolled back.

mysql> START TRANSACTION;

mysql> INSERT INTO Test VALUES (5), (6);

mysql> INSERT INTO Test VALUES (7), (8);

mysql> ROLLBACK;

mysql> SELECT * FROM Test;
+-----+
| Num |
+-----+
|   1 |
|   2 |
|   3 |
|   4 |
+-----+



In the above SQL code, we start a new transaction. We insert four values into the Test table. We roll the changes back with the ROLLBACK statement. Subsequent select from the table shows that the data was not committed to the table.

Tuesday, August 28, 2012

How to find a content of a file linux

You can find content inside a file by using Linux grep command. eg : If you want to find the usage of text called "Hello". You can type as follows:

grep -r hello .

-r option means read all files under each directory, recursively
hello - means the content what you want to search
. - means the path for this scenario it means from current folder.(You can use absolute path as well eg: /home/gayan/)

Enjoy ~

Wednesday, August 1, 2012

Database Access Object Pattern using PHP


The simplest web widget to the most complex online e-commerce website have one thing in
common: they deal with data. So much of programming revolves around data access and
manipulation. With the massive proliferation of the Internet, cheaper storage devices, improved understanding of analytics, and greater expectations for information access, data is being leveraged in more interesting and unique ways. The Data Access Object Design Pattern aims to help construct objects that can work easily (transparently) with all of this data.

Programming typically can be a lot of repetition. This was especially true before more popular frameworks started being released. Most PHP programmers can count into the double digits the number of CRUD (create, read, update, delete) applications they’ve had to make. One of the major portions of repetition in the standard create/update application is the data source manipulation. For the rest of the discussion, I’m going to stop generalizing the data source and refer to it as SQL.

In the application, a SQL statement has to be written to create the entity in the database. Next, an additional SQL statement must be written in order to provide updates to any of the individual features of that entity. The repetition involved in creating these SQL statements is not only boring but also not best practice.

Code example

First create your own database and create following table

 CREATE TABLE task (  
      id INT PRIMARY KEY AUTO_INCREMENT,  
      subject VARCHAR(255),  
      description text  
 );  

Create php file called "baseDao" and put following code

 <?php  
 class baseDao  
 {  
   private $connection;  
   public function __construct() {  
     $this->connectToDb(DB_USER, DB_PASS, DB_HOST, DB_NAME);  
   }  
   public function connectToDb($user, $pass, $host, $database) {  
     $this->connection = mysql_connect($host, $user, $pass);  
     mysql_select_db($database, $this->connection);  
   }  
   public function fetch($value, $key = NULL)  
   {  
     if (is_null($key)) {  
       $key = $this->_primaryKey;  
     }  
     $sql = "SELECT * FROM {$this->_tableName} WHERE {$key} = '" . $value . "';";  
     $results = mysql_query($sql, $this->connection);  
     $rows = array();  
     while ($result = mysql_fetch_array($results)) {  
       $rows[] = $result;  
     }  
     return $rows;  
   }  
   public function update($keyedArray)  
   {  
     $sql = "UPDATE {$this->_tableName} SET ";  
     $updates = array();  
     foreach ($keyedArray as $column=>$value) {  
       $updates[] = "{$column}='" . $value . "'" ;  
     }  
     $sql .= implode(",", $updates);  
     $sql .= " where {$this->_primaryKey}='". $keyedArray[$this->_primaryKey] . "';";  
     mysql_query($sql, $this->connection);  
   }  
      public function save($keyedArray)  
   {  
     $sql = "INSERT INTO {$this->_tableName} ";  
     $updates = array();  
     foreach ($keyedArray as $column=>$value) {  
       $updates_columns[] = "{$column}";  
       $updates_values[] = "'" . $value . "'" ;  
     }  
           $sql .= "(";  
     $sql .= implode(",", $updates_columns);  
           $sql .= ")";  
           $sql .= " VALUES (";  
     $sql .= implode(",", $updates_values);  
     $sql .= ");";  
     if (!mysql_query($sql, $this->connection))  
                echo mysql_error();  
   }  
 }  

Finally you can use the dao class as follows:


 <?php  
 //DB_USER, DB_PASS, DB_HOST, DB_NAME  
 define('DB_USER', 'root');  
 define('DB_PASS', '');  
 define('DB_HOST', 'localhost');  
 define('DB_NAME', 'blog_samples');  
 //include "baseDao.php";  
 include "taskDao.php";  
 $taskDao = new taskDao();  
 $updates=array('subject' => 'testSubjectValue', 'description' => 'testDescriptionValue');  
 $taskDao->save($updates);  
 echo "<br/>Dao pattern !<br/>";  
Good luck !

Friday, July 27, 2012

Builder design pattern using php

Software complexity is an interesting thing. The requirements for software are complex as are the functionality of a software package or product. Even the code that makes up the software is complex. The focus of the Design Pattern approach is to provide maintainability, architectural 
strength and reduced complexity. With the host of complex objects making up most software repositories, solutions involving the Builder Design Pattern have their work cut out for them.

Code example

The project contains a class that creates the complex product object. This class contains three methods to completely form it. If each of these methods is not called when creating a new product object, attributes of the class will be missing and the program will halt. These methods are setType(), setColor(), and setSize(). The initial version of this code was designed to create the object followed by the execution of each of these methods.

class Product
{
    protected $type = '';
    protected $size = '';
    protected $color = '';
    protected $price = '';

    public function setColor($color)
    {
        $this->color = $color;
    }

    public function setSize($size)
    {
        $this->size = $size;
    }

    public function setType($type)
    {
        $this->type = $type;
    }


    public function setPrice($price)
    {
        $this->price = $price;
    }

    function __toString()
    {
        $text = 'Product { ';
        $text .= ":type => " . $this->type;
        $text .= ", :size => " . $this->size;
        $text .= ", :color => " . $this->color;
        $text .= ", :price => " . $this->price;
        $text .= " }";
        return $text;
    }

}


To create a complete product object, the product configurations need to be passed individually to each of
the methods of the product class:


// our product configuration received from other functionality
$productConfigs = array(‘type’=>’shirt’, ‘size’=>’XL’, ‘color’=>’red’);
$product = new product();
$product->setType($productConfigs[‘type’]);
$product->setSize($productConfigs[‘size’]);
$product->setColor($productConfigs[‘color’]);


Having to call each one of these methods when an object is created is not best practice. Instead, an object based on the Builder Design Pattern should be used to create this product instance.


The productBuilder class is designed to accept those configuration options that are required to build
the product object. It stores both the configuration parameter and a new product instance on
instantiation. The build() method is responsible for calling each of the methods in the product class to
fully complete the product object. Finally, the getProduct() method returns the completely built
product object.




class ProductBuilder
{

    protected $product = NULL;
    protected $config = array();

    public function __construct($config){
        $this->product = new Product();
        $this->config = $config;
    }

    public function build() {
        $this->product->setType($this->config['type']);
        $this->product->setColor($this->config['color']);
        $this->product->setSize($this->config['size']);
        $this->product->setPrice($this->config['price']);
    }

    public function getProduct() {
        return $this->product;
    }
}

Note that this build() method hides the actual method calls from the code requesting the new product. If the product class changes in the future, only the build() method of the productBuilder class needs to change. This code demonstrates the creation of the product object, using the productBuilder class:


$builder = new productBuilder($productConfigs);
$builder->build();
$product = $builder->getProduct();

The Builder Design Pattern is meant to eliminate the complex creation of other objects. Using the Builder Design Pattern is not only best practice but it also reduces the chances of having to repeatedly alter pieces of code if an object’s construction and configuration methods change.

Friday, May 11, 2012

Adapter pattern using php

Programming would be simple, but boring. Programmers would continue to build applications on top of the same technologies that they did years ago. They would never need to introduce different databases, implement new best practices, or consume different APIs. But these things do change. Luckily, programmers have the Adapter Design Pattern to help update legacy systems with new code and functionality.

The solution is to build another object, using the Adapter Design Pattern. This Adapter object works as an intermediary between the original application and the new functionality. The Adapter Design Pattern defines a new interface for an existing object to match what the new object requires.

Code Example

In the original code base of the project, an object exists that handles all of the error messages and codes called errorObject. The original programmers didn’t think their code would ever generate any errors, so they designed the system to output the errorObject’s error information directly to the console.

In this example, a 404:Not Found error is being generated. You are going to assume that the error message content and code may change, but the text will always stay in the same format.

 class ErrorObject  
 {  
   private $error;  
   public function __construct($error){  
     $this->error = $error;  
   }  
   public function getError(){  
     return $this->error;  
   }  
 }  


 class LogToConsole  
 {  
   private $errorObject;  
   public function __construct($errorObject){  
     $this->errorObject = $errorObject;  
   }  
   public function write() {  
     fwrite(STDERR, $this->errorObject->getError() . "\n");  
   }  
 }  

Here is the testing...

 include "ErrorObject.php";  
 include "LogToConsole.php";  
 /** create the new 404 error object **/  
 $error = new ErrorObject("404:Not Found");  
 /** write the error to the console **/  
 $log = new LogToConsole($error);  
 $log->write();  
How about new requirement comes that error need to output to csv format, with the code and description.
Lets look at how we going to do that with Adapter pattern.
 class LogToCsvAdapter extends ErrorObject  
 {  
   private $errorNumber, $errorText;  
   public function __construct($error)  
   {  
     parent::__construct($error);  
     $parts = explode(':', $this->getError());  
     $this->errorNumber = $parts[0];  
     $this->errorText = $parts[1];  
   }  
   public function getErrorNumber()  
   {  
     return $this->errorNumber;  
   }  
   public function getErrorText()  
   {  
     return $this->errorText;  
   }  
 }  






Here is the testing...
 include "ErrorObject.php";  
 include "LogToCsv.php";  
 include "LogToCsvAdapter.php";  
 /** create the new 404 error object adapted for csv **/  
 $error = new LogToCsvAdapter("404:Not Found");  
 /** write the error to the csv file **/  
 $log = new logToCSV($error);  
 $log-&gt;write();  




Good luck...

Wednesday, May 9, 2012

How to delete .svn files for linux

Recursively delete .svn directories


This is a simple example of a unix command, which recursively deletes subversion .svn folders. Subversion is a well-spread open-source revision control application. Every copy of source code received from subversion repository has .svn folders, which store metadata. However, if you want to use or distribute source code, these .svn folder are often not necessary.     

We use find command to find all .svn folders beginning from current directory.


eg: type : find . -type d -name .svn

It is possible to pass these directories directly to rm command, using grave accent quotes (key to left of '1')

eg: type : rm -rf `find . -type d -name .svn`

above command will remove every .svn folder beginning from current directory.

You may do not like to type each and every time so you can create shell script for that.


1) Create a file called  /usr/bin/csvn 
2) Input following codes:

#!/bin/sh
echo "recursively removing .svn folders from"
pwd
rm -rf `find . -type d -name .svn`

You may save this script to /usr/bin/csvn (or other binary folder included in path) and use later to get 'clean' project source without typing lengthy commands.

For example

$ svn checkout svn://server.com/svn/project
A    project/index.php
A    project/sourceA/a.php
A    project/sourceA/a1.php
A    project/sourceA/a2.php
A    project/sourceB/b.php
A    project/sourceB/module/lib.php
A    project/sourceC/c.php
Checked out revision 15.
$ cd project
$ csvn
recursively removing .svn folders from
/Users/anyexample/Source/project

~Good luck~

Wednesday, March 14, 2012

Libraries installation for symfony development using yum

yum install php-pdo.i686
yum install php-xml
yum install php-mbstring.i686
yum list php-pear
yum install php-pecl-apc
yum install php-process

Saturday, December 4, 2010

How to create sample vaadin application with maven 2.2.1

How to create sample vaadin application with maven 2.2.1

Step one
--------

Create maven project with typing the following command on your command line.


mvn archetype:create -DgroupId=com.sample.vaadin -DartifactId=SampleVaadin -DarchetypeArtifactId=maven-archetype-webapp

Here is the sample pom.xml

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  <modelVersion>4.0.0</modelVersion>  
  <groupId>com.sample.vaadin</groupId>  
  <artifactId>SampleVaadin</artifactId>  
  <packaging>war</packaging>  
  <version>1.0-SNAPSHOT</version>  
  <name>SampleVaadin Maven Webapp</name>  
  <url>http://maven.apache.org</url>  
  <dependencies>  
   <dependency>  
    <groupId>junit</groupId>  
    <artifactId>junit</artifactId>  
    <version>3.8.1</version>  
    <scope>test</scope>  
   </dependency>  
  </dependencies>  
  <build>  
   <finalName>SampleVaadin</finalName>  
  </build>  
 </project>  

Step two
--------

Integrate jetty servlet container to vaadin project

Please update your pom.xml as follows:

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  <modelVersion>4.0.0</modelVersion>  
  <groupId>com.sample.vaadin</groupId>  
  <artifactId>SampleVaadin</artifactId>  
  <packaging>war</packaging>  
  <version>1.0-SNAPSHOT</version>  
  <name>SampleVaadin Maven Webapp</name>  
  <url>http://maven.apache.org</url>  
  <dependencies>  
   <dependency>  
    <groupId>junit</groupId>  
    <artifactId>junit</artifactId>  
    <version>3.8.1</version>  
    <scope>test</scope>  
   </dependency>  
      <dependency>  
           <groupId>com.vaadin</groupId>  
           <artifactId>vaadin</artifactId>  
           <version>6.6.2</version>  
           <type>jar</type>  
           <scope>compile</scope>  
      </dependency>  
  </dependencies>  
  <build>  
   <finalName>SampleVaadin</finalName>  
      <plugins>  
        <plugin>  
          <groupId>org.mortbay.jetty</groupId>  
          <artifactId>maven-jetty-plugin</artifactId>  
     </plugin>  
           <plugin>  
                     <groupId>org.apache.maven.plugins</groupId>  
                     <artifactId>maven-compiler-plugin</artifactId>  
                     <version>2.3.2</version>  
                     <configuration>  
                          <source>1.6</source>  
                          <target>1.6</target>  
                     </configuration>  
           </plugin>  
   </plugins>  
  </build>       
 </project>  


*** You can test whether jetty is running by typing "mvn jetty:run"


Step tree
--------

Writing code under src/main/java/com/sample/vaadin/HelloVaadin.java


 /**  
 * This is the main class of the vaadin page  
 * @author gayan  
 *  
 * src/main/java/com/sample/vaadin/HelloVaadin.java  
 */  
 package com.sample.vaadin;  
 import com.vaadin.Application;  
 import com.vaadin.ui.*;  
 public class HelloVaadin extends Application {  
   @Override  
   public void init() {  
     Window mainWindow = new Window("HelloVaadin");  
     Label label = new Label("Hello Vaadin user");  
     mainWindow.addComponent(label);  
     setMainWindow(mainWindow);  
   }  
 }  

Step four
--------

Edit you web.xml file under webapp/web.xml as following

 <!DOCTYPE web-app PUBLIC  
  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"  
  "http://java.sun.com/dtd/web-app_2_3.dtd" >  
 <web-app version="2.5" xmlns:xsi="[http://www.w3.org/2001/XMLSchema-instance\" xmlns="[http://java.sun.com/xml/ns/javaee]" xsi:schemalocation="[http://java.sun.com/xml/ns/javaee] [http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd]">  
   <display-name>HelloVaadin</display-name>  
   <context-param>  
     <param-name>productionMode</param-name><param-value>false</param-value><description>Vaadin production mode</description>  
   </context-param>  
   <servlet>  
     <servlet-name>HelloVaadin</servlet-name>  
     <servlet-class>com.vaadin.terminal.gwt.server.ApplicationServlet</servlet-class>  
     <init-param>  
       <param-name>application</param-name>  
                <param-value>com.sample.vaadin.HelloVaadin</param-value>  
                <description>Vaadin application class to start</description>  
     </init-param>  
   </servlet>  
   <servlet-mapping>  
     <servlet-name>HelloVaadin</servlet-name>  
     <url-pattern>/*</url-pattern>  
   </servlet-mapping>  
 </web-app>  

Final step
--------

Have commond "mvn compile jetty:run" and please have a look on http://localhost:8080 on your browser.

Thursday, October 21, 2010

Minimize ripple effects in OOP programing

What is the meaning of minimize ripple effect?
Minimizing the ripple effects means limit the force of  changes to a program. Simply saying by keeping details secret in your code (information hiding or encapsulation).


Basically there are three ways of doing it: 


By indirection 
  That means named constants replacing "magic numbers" in your piece of code.
  e.g: 
  A magic number is a direct usage of a number in the code. see the following piece of code as example     which is not best practice to use:


public class Foo {
     public void setPassword(String password) {
          // don't do this
          if (password.length() > 7) {
               throw new InvalidArgumentException("password");
          }
     }
}


 Best practice is in the following code: 







public class Foo {
     public static final MAX_PASSWORD_SIZE = 7;

     public void setPassword(String password) {
          if (password.length() > MAX_PASSWORD_SIZE) {
               throw new InvalidArgumentException("password");
          } 
}

***  It will improve the readability of the code and of course maintainability

***  Imagine the case where I set the size of the password field in the GUI. If I use a magic number, whenever the max size changes, I have to change in two code locations. If I forget one, this will lead to inconsistencies.


By minimizing visibility


 Use private fields, package-private classes to hide information from public access.


By generic references


Use  (polymorphism) - using high level references (interfaces or abstract classes) instead of low level references (concrete classes).



Tuesday, October 19, 2010

Linux IP Commands

Display Current Config for all NIC's: ifconfig

Display Current Config for eth0: ifconfig eth0

Assign IP: ifconfig eth0 192.168.1.2

Ping: ping -c 3 192.168.1.1

Assign multiple IP's: ifconfig eth0:0 192.168.1.2

Assign second IP: ifconfig eth0:1 192.168.1.3

Disable network card: ifconfig eth0 down

Enable network card: ifconfig eth0 up

View current routing table: route "or" route -n

View arp cache: arp "or" arp -n

Assign IP/Subnet: ifconfig eth0 192.168.1.2 netmask 255.255.255.0

Assign Default Gateway: route add default gw 192.168.1.1

Trace Route: traceroute www.whatismyip.com

Trace Path: tracepath www.whatismyip.com

DNS Test: host www.whatismyip.com

Advanced DNS Test: dig www.whatismyip.com

Reverse Lookup: host 66.11.119.69

Advanced Reverse Lookup: dig -x 66.11.119.69