Skip to main content

How to do good programming ?


"If computer programming is to become an important part of computer research and development, a transition of programming from an art to a disciplined science must be effected."
Computer scientists are taught to program properly, just like linguists are taught how to write literary texts. However, not all computer scientists are programmers, just like not all linguists are writers, although most of us program regularly. For some reason, many programmers seem to think their role is to write code that makes things work. It’s not. Your job is to solve a problem with code in the most elegant way, such that your solution is easy to adapt, modify and reuse. Just like “the grass is green and the sky blue” is not literature, although it might perfectly describe the environment, coding something that just works is not programming. It’s fiddling.

Most people do the wrong thing correctly and think that it is correct. Here is the post which illuminates such things and guide in the correct way.
The topic is about
  • Dynamic object creation
  • Structured Programming
Dynamic object creation is all about how an object can be created on the fly. Normally it is believed that an object is created only using the new keyword but in reality it achieves static binding which is not so much desirable. Hence we go for dynamic object creation using the java rich language features. This is achieved by using Class.forName(String args).
The args should be a fully qualified classname which if not found throws me a ClassNotFoundException. What we have achieved by using this is only a class but we need a new object of the class. Hence we go for its method newInstance().
The call for the dynamic object creation will be something like
Object object= Class.forName(classname).newInstance();
You can cast this object to the requirement and call the methods upon it.
An example of doing this is:
 package com.immanikanta.dynamicpack;  
 public class DynamicObject {  
      public static void main(String[] args) {  
           try{  
                String str="java";  
                Object object=Class.forName("java.lang.StringBuffer").newInstance();  
                StringBuffer newStr=(StringBuffer)object;  
                newStr.append("java");  
                if(str.equals(newStr.toString()))  
                {  
                     System.out.println("Your object is created...");  
                }  
                else{  
                     System.out.println("Your object creation failed...");  
                }  
           }catch(ClassNotFoundException cnf){  
                cnf.printStackTrace();  
           } catch (InstantiationException e) {  
                e.printStackTrace();  
           } catch (IllegalAccessException e) {  
                e.printStackTrace();  
           }  
      }  
 }  
Erich gamma, who coined object oriented programming said, “If your code consists of structured programming practise, it can be thrown in the dustbin”. Basically all the if else statements are structured programming practise only.
This is a normal way of writing a menu which contains if else if statements. This is purely structures programming even though you might have used classes and oops concepts of java.
 package in.blogspot.immanikanta;  
 import java.io.BufferedReader;  
 import java.io.InputStreamReader;  
 public class Marks {  
      public static void main(String args[]) throws Exception {  
           String option = "";  
           BufferedReader br = new BufferedReader(new InputStreamReader(System.in));  
           do {  
                System.out.println("Please enter your option...");  
                option = br.readLine();  
                if (option.equals("FirstOption")) {  
                     System.out.println("You have selected first option...");  
                } else if (option.equals("SecondOption")) {  
                     System.out.println("You have selected second option...");  
                } else if (option.equals("OtherOption")) {  
                     System.out.println("You have selected other options...");  
                } else {  
                     System.out.println("You have exit succcesfully...");  
                }  
           } while (!option.equals("Exit"));  
      }  
 }  
This code, even though written in java cannot be reused. "reuse", in sense that the code modifications should be reflected even when the code is running. This code doesn't produce the desired effect when later the user enters FourthOption. It simply takes me to exit.
 package in.blogspot.immanikanta;  
 import java.io.BufferedReader;  
 import java.io.InputStreamReader;  
 public class Marks_OOPS {  
      public static void main(String[] args) throws Exception {  
           String option = "";  
           BufferedReader br = new BufferedReader(new InputStreamReader(System.in));  
           do {  
                System.out.println("Please enter your choice...");  
                option = "in.blogspot.immanikanta." + br.readLine();  
                Option choice = (Option) Class.forName(option).newInstance();  
                choice.execute();  
           } while (!option.equals("in.blogspot.immanikanta.Exit"));  
      }  
 }  

This code takes the chance of adding new classes without even shutting down my program. This code is extensible and reusable. This is called object oriented programming.
 package in.blogspot.immanikanta;  
 public abstract class Option {  
      public abstract void execute();  
 }  

This is achieved through use of abstract classes.
This code illustrates the options.
 package in.blogspot.immanikanta;  
 public class FirstOption extends Option {  
      @Override  
      public void execute() {  
           System.out.println("First option is selected...");  
      }  
 }  

You can add as many as options as they are extending the Option abstract base class
 package in.blogspot.immanikanta;  
 public class SecondOption extends Option {  
      @Override  
      public void execute() {  
           System.out.println("Second option is selected...");  
      }  
 }  

As of now I have stopped the addition of classes but you can add as many as classes during runtime and not during the compile time. This code supports both of them.
 package in.blogspot.immanikanta;  
 public class OtherOption extends Option {  
      @Override  
      public void execute() {  
           System.out.println("Other options is selected...");  
      }  
 }  

A small exit class
 package in.blogspot.immanikanta;  
 public class Exit extends Option{  
      @Override  
      public void execute() {  
           System.out.println("Exit succesfull...");  
      }  
 }  

The essence of the object oriented programming style is that the code can be extended at any time. We need not stop the server which is a very costly process. Classes can be added at runtime.

Steps to reproduce:

  1. Download the packages and keep them in a separate folder.
  2. compile all the classes and keep them in the correct folder structure.
  3. using javac execute the Main_OOPS class
  4. At this point, when the program is running(don't give exit otherwise program will exit, a given functionality) add another class in the package extending the Option base class.
  5. Enter the newly created class name in the program which we are running earlier.
  6. Voila! New objects are created at runtime.
Download packages

Comments

Popular posts from this blog

Trip to narsipura Sri Vaidya Narayana murthy - Shimago for cancer treatment

Hi friends. I would like to share my experience about my trip to Shimago and meet Guru Narayana murthy who would treat for cancer, diabetics, kidney diseases. My brother was diagnosed with rectal cancer on October 2014. The news of cancer to a young boy of 26 years shook our whole family. But we are strong as he was getting treatment from world class care clinic in Cleveland - Cleveland clinic, Ohio, USA. As fate had other plans, his cancer came in January, 2017 back after an extensive surgery, chemotherapy and radiotherapy. The doctors made a decision to keep him in hospice care: support for advanced illness. They said that there is no more treatment and only to keep him comfortable as long as he lives, we lost our hopes and that is when we thought of giving a try to Ayurvedic medicine. We found Guruji narasipura narayana murthy. His medicine gave us hopes and I recently went to narsipura to get the medicine. I thought it would be best to give my share of experience in reaching the

Solution to "child margin affects parent" in CSS

The browser implementation is that when the parent has no content and the child requests for margin, the parent is brought down instead of child going down. The solution for these are listed below with their side effects. floats , You  have  to float elements border-top , This pushes the parent at least 1px downwards which should then be adjusted with introducing  -1px  margin to the parent element itself. This can create problems when parent already has  margin-top  in relative units. padding-top , same effect as using  border-top overflow: hidden , Can't be used when parent should display overflowing content, like a drop down menu overflow: auto , Introduces scrollbars for parent element that has (intentionally) overflowing content (like shadows or tool tip's triangle) See the Pen Relative with Margin by Manikanta ( @immnk ) on CodePen .

Redirection in javascript

How Page Re-direction works ? Example 1: This is very simple to do a page redirect using JavaScript at client side. To redirect your site visitors to a new page, you just need to add a line in your head section as follows: <head> <script type="text/javascript"> <!-- window.location="http://www.newlocation.com"; --> </script> </head> To understand it in better way you can  Try it yourself . Example 2: You can show an appropriate message to your site visitors before redirecting them to a new page. This would need a bit time delay to load a new page. Following is the simple example to implement the same: <head> <script type="text/javascript"> <!-- function Redirect() { window.location="http://www.newlocation.com"; } document.write("You will be redirected to main page in 10 sec."); setTimeout('Redirect()', 10000); //--> </script> </head> Here