Saturday, November 19, 2016

Object Oriented Programming for Modularity - ROT-13

Many students starting out in Java try to solve a problem using a single class and thinking only about the application not its components and "building blocks".

In this example, writing an application to encrypt a string is simple to do in a single application, but the ROT-13 algorithm is not just useful in this application, but it should be used in many other applications as well. While the application interface and driving code are application specific, the ROT-13 algorithm is not and should be separated into a modular structure.




import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

/** This simple application will help you understand polymorphism
 * @version 1.0.0
 * @author Zoltan Szabo
 */
public class Rot13Demo{
      public static void main(String[] args) {
            try{
                  File inFile=new File("c:\\temp\\infile.txt");
                  File outFile=new File("c:\\temp\\outfile6.txt");
                  Scanner input=new Scanner(inFile);
                  PrintWriter output=new PrintWriter(outFile);
                  while(input.hasNext()){
                        String temp=input.nextLine();
                        for(int i=0;i<temp.length();i++){
                              char ch=temp.charAt(i);
                              if(Character.isLowerCase(ch)){
                                    if(ch<='m')
                                          output.print((char)(ch+13));
                                    else
                                          output.print((char)(ch-13));
                              }
                              else if(Character.isUpperCase(ch)){
                                    if(ch<='M')
                                          output.print((char)(ch+13));
                                    else
                                          output.print((char)(ch-13));
                              }
                              else
                                    output.print(ch);
                        }
                        output.println();
                  }
                  input.close();
                  output.close();
            }

            catch(IOException e){
                  System.out.println("Error: Check your input and output files and locations.");
            }
      }
}

If you are more adventurous, you can simplify the decision making and the "heart" of the algorithm with ternary operator, like this:


output.print((Character.isLowerCase(ch))?(ch<='m')?(char)(ch+13):(char)(ch-13):(Character.isUpperCase(ch))?(ch<='M')?(char)(ch+13):(char)(ch-13):ch);

Look at the simplicity of this driver class where the programmer can focus on the interface and how to handle the input and output files, while the algorithm can be used in any other applications.   


import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

/** This simple application will help you understand object oriented programming and an introduction to encryption
* @version 1.0.0
* @author Zoltan Szabo
*/
public class Rot13Demo{
   public static void main(String[] args)  throws IOException {
       File inFile=new File(args[0]);
       File outFile=new File(args[1]);
       Scanner input=new Scanner(inFile);
       PrintWriter output=new PrintWriter(outFile);
    while(input.hasNext()){
        String temp=input.nextLine();
        output.println(Rot13.encode(temp));
    }
    input.close();
    output.close();
   }
}

Since there are no attributes, the static method is a better choice for this method than a method belonging to an instantiated object.

/** This simple class helps you understand the static methods as a helper class for a collection of encryption algorithms.
* @version 1.0.0
* @author Zoltan Szabo
*/

public class Rot13{
/** This simple method will encode the temp string using ROT-13
* @param temp string to be encoded that can be a string encoded using ROT-13 to decode since ROT-13 is circular encryption algorithm
* @return The 13 character shifted string result
*/
   public static String encode(String temp) {
    StringBuilder encoded=new StringBuilder();
        for(int i=0;i<temp.length();i++){
            char ch=temp.charAt(i);
            if(Character.isLowerCase(ch)){
                if(ch<='m')
                    encoded.append((char)(ch+13));
                else
                    encoded.append((char)(ch-13));
            }
            else if(Character.isUpperCase(ch)){
                if(ch<='M')
                    encoded.append((char)(ch+13));
                else
                    encoded.append((char)(ch-13));
            }
            else
                  encoded.append(ch);
    }
    return encoded.toString();
   }
}

So, think about the generic and blocks in your code that should be independent from a specific application and design your code with objects in mind for mobility and modularity.

Friday, November 18, 2016

Inheritance and Polymorphism Revisited - Challenge



Start with the UML below.  You should try to implement this UML with a simple code not even looking at the code below.  See if you can successfully interpret the UML.


You should interpret the UML above and write the problem statement this UML solves.

You can compare your code to the code below or use it as a reference if you get stuck.

/** Animal class that is used as the super class with different modifiers to help understand inheritance
* @version 1.0.0.0
* @author Zoltan Szabo
*/
public class Animal{
    public int x=50;
    private int y=60;
    protected int z=70;
    int k=80;
  
    public static int XX=150;
    private static int YY=160;
    protected static int ZZ=170;
    static int KK=180;
  
/** Super class no-arg constuctor*/
   public Animal(){
      System.out.println("This is the superclass (Animal) constructor.");
   }

/** Public method in the superclass
* @return x public field from superclass
*/
   public int func1(){
        return x;  
   }

/** Private method in the superclass
* @return y private field from superclass
*/   private int func2(){
        return y;
   }

/** Protected method in the superclass
* @return z protected field from superclass
*/   protected int func3(){
        return z;
   }

/** Public method in the superclass
* @return k default field from superclass
*/   int func4(){
        return k;
   }
}

/**
*Cat class that is a child of the Animal class inherits public, protected, and default attributes and methods
*@version 1.0.0
*@author Zoltan Szabo
*/ public class Cat extends Animal{
/** SubSubClass1 class no-arg constuctor*/
   public Cat(){
      System.out.println("I\'m a Cat constructor.");
   }
}

/**
*Class that is a child of the Animal class inherits public, protected, and default attributes and methods
*@version 1.0.0
*@author Zoltan Szabo
*/

public class Dog extends Animal{

/** SubClass1class no-arg constuctor*/
   public Dog(){
      System.out.println("I'm a Dog constructor.");
   }
   public void doTrick(){
       System.out.println("I can roll over.");
    }
}

/** This simple application will help you understand polymorphism
* @version 1.0.0
* @author Zoltan Szabo
*/

public class AnimalsDemo{
    final static int INDEX=2;

/** application entry point to test inheritance of modifiers
* @param args as a String array for command argument input
*/

   public static void main(String[] args)   {

      Animal obj[]=new Animal[5];
      obj[0]=new Animal();
      obj[1]=new Dog();
      obj[2]=new Cat();
     /*
      * according to the java language specification, 3rd edition:
      * 6.6.8 Example: private Fields, Methods, and Constructors
      * A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.
      * It is not inherited by subclasses.
      */
     //Instantiate one of each objects in an Animal array of objects
     //Display collar color for each animals and the length of the leash where it applies.
   }
}

Now take the initial code and extend the application to implement this UML.

 The output should look like this.