Monday, October 22, 2012


Clear Code in Functions - 10 most important things you should know about functions.

1.       Always make it Small

The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than that. This is not an assertion that I can justify. In the eighties we used to say that a function should be no bigger than a screen-full. Of course we said that at a time when VT100 screens were 24 lines by 80 columns, and our editors used 4 lines for administrative purposes. Nowadays with a cranked-down font and a nice big monitor, you can fit 150 characters on a line and a 100 lines or more on a screen. Lines should not be 150 characters long. Functions should not be 100 lines long. Functions should hardly ever be 20 lines long.

  • Blocks and Indenting

This implies that the blocks within if statements, else statements, while statements, and so on should be one line long. Probably that line should be a function call. Not only does this keep the enclosing function small, but it also adds documentary value because the function called within the block can have a nicely descriptive name. This also implies that functions should not be large enough to hold nested structures. Therefore, the indent level of a function should not be greater than one or two. This, of course, makes the functions easier to read and understand.

2.       Do one thing

Functions should do one thing. They should do it well. They should do it only.

  • ·         Sections within Functions

 This is an obvious symptom of doing more than one thing. Functions that do one thing cannot be reasonably divided into sections.


3.       One Level of Abstraction per Function

In order to make sure our functions are doing “one thing,” we need to make sure that the statements within our function are all at the same level of abstraction. Mixing levels of abstraction within a function is always confusing. Readers may not be able to tell whether a particular expression is an essential concept or a detail. Worse, like broken windows, once details are mixed with essential concepts, more and more details tend to accrete within the function.

  • ·         The Stepdown Rule

We want the code to read like a top-down narrative. We want every function to be followed by those at the next level of abstraction so that we can read the program, descending one level of abstraction at a time as we read down the list of functions. I call this The Stepdown Rule.

4.       Switch Statements

It’s hard to make a small switch statement. Even a switch statement with only two cases is larger than I’d like a single block or function to be. It’s also hard to make a switch statement that does one thing. By their nature, switch statements always do N things. Unfortunately we can’t always avoid switch statements, but we can make sure that each switch statement is buried in a low-level class and is never repeated. We do this, of course, with polymorphism.

5.       Use Descriptive Names

Don’t be afraid to make a name long. A long descriptive name is better than a short enigmatic name. A long descriptive name is better than a long descriptive comment. Use a naming convention that allows multiple words to be easily read in the function names, and then make use of those multiple words to give the function a name that says what it does.
Don’t be afraid to spend time choosing a name. Indeed, you should try several different names and read the code with each in place. Modern IDEs like Eclipse or IntelliJ make it trivial to change names. Use one of those IDEs and experiment with different names until you find one that is as descriptive as you can make it.
Choosing descriptive names will clarify the design of the module in your mind and help you to improve it. It is not at all uncommon that hunting for a good name results in a favorable restructuring of the code.

6.       Function Arguments

The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification—and then shouldn’t be used anyway.

Arguments are hard. They take a lot of conceptual power.

Arguments are even harder from a testing point of view. Imagine the difficulty of writing all the test cases to ensure that all the various combinations of arguments work properly. If there are no arguments, this is trivial. If there’s one argument, it’s not too hard. With two arguments the problem gets a bit more challenging. With more than two arguments, testing every combination of appropriate values can be daunting.

Output arguments are harder to understand than input arguments. When we read a function, we are used to the idea of information going in to the function through arguments and out through the return value. We don’t usually expect information to be going out through the arguments. So output arguments often cause us to do a double-take.

Always try to use Common Monadic Form functions, try to reduce Dyadic form functions, don’t use triads form and flag arguments.

  • ·         Common Monadic Forms

Always try to have functions with one argument. That is the best practice and it will help to reduce the complexity of the function.

  • ·         Flag Arguments

Flag arguments are ugly. Passing a Boolean into a function is a truly terrible practice. It immediately complicates the signature of the method, loudly proclaiming that this function does more than one thing. It does one thing if the flag is true and another if the flag is false!

  • ·         Dyadic Functions

A function with two arguments is harder to understand than a monadic function.

  • ·         Triads Functions

Functions that take three arguments are significantly harder to understand than dyads. The issues of ordering, pausing, and ignoring are more than doubled. I suggest you think very carefully before creating a triad.

  • ·         Argument Objects

When a function seems to need more than two or three arguments, it is likely that some of those arguments ought to be wrapped into a class of their own. Reducing the number of arguments by creating objects out of them may seem like cheating, but it’s not.

  • ·         Argument Lists

Sometimes we want to pass a variable number of arguments into a function. So all the same rules apply. Functions that take variable arguments can be monads, dyads, or even triads. But it would be a mistake to give them more arguments than that.

  • ·         Verbs and Keywords

Choosing good names for a function can go a long way toward explaining the intent of the function and the order and intent of the arguments. In the case of a monad, the function and argument should form a very nice verb/noun pair. For example, write(name) is very evocative. Whatever this “name” thing is, it is being “written.” An even better name might be writeField(name), which tells us that the “name” thing is a “field.”

7.       Avoid Side Effects

Side effects are lies. Your function promises to do one thing, but it also does other hidden things. Sometimes it will make unexpected changes to the variables of its own class. Sometimes it will make them to the parameters passed into the function or to system globals. In either case they are devious and damaging mistruths that often result in strange temporal couplings and order dependencies.

8.       Command Query Separation

Functions should either do something or answer something, but not both. Either your function should change the state of an object, or it should return some information about that object. Doing both often leads to confusion.

9.       Prefer Exceptions to Returning Error Codes

Try to convert exceptions into error codes.

  • ·         Extract Try/Catch Blocks

Try/catch blocks are ugly in their own right. They confuse the structure of the code and mix error processing with normal processing. So it is better to extract the bodies of the try and catch blocks out into functions of their own.

  • ·         Error Handling Is separate from functions

Functions should do one thing. Error handing is one thing. Thus, a function that handles errors should do nothing else. This implies that if the keyword try exists in a function, it should be the very first word in the function and that there should be nothing after the catch/finally blocks.

10.   Don’t Repeat Yourself (DRY)

Duplication may be the root of all evil in software. Many principles and practices have been created for the purpose of controlling or eliminating it. Consider, for example, that all of Codd’s database normal forms serve to eliminate duplication in data. Consider also how object-oriented programming serves to concentrate code into base classes that would otherwise be redundant. Structured programming, Aspect Oriented Programming, Component Oriented Programming, are all, in part, strategies for eliminating duplication. It would appear that since the invention of the subroutine, innovations in software development have been an ongoing attempt to eliminate duplication from our source code.

Monday, January 9, 2012

Creating a simple calculator



This calculator program let user to input an arbitrary equation through a graphical interface and display the answer according to BODMAS law. This equation can have all components including parentheses, addition subtraction, multiplication and division.  These system specifications were given.

Description

Your task is to create a program which simulates very simple calculator. The details for the implementation of the system are given in the steps below:

  • .        Design and implement an abstract base class ArithmeticExpression that represent any binary (having two arguments) arithmetic expression. In this coursework you will be implementing various subclasses of this class. The abstract class should include at least two methods called evaluate and display which are described below.
  • .  Design and implement concrete (non-abstract) classes which are subclasses of the class ArithmeticExpression and each one represent some simple arithmetic expression. The operations that you should implement for each subclass should include the binary (i.e. accepting exactly two arguments) operations of addition, subtraction, multiplication and division (all of them accepting double type arguments). Using the classes you should be able to represent an arbitrary expression (i.e. an expression with an arbitrary number of terms), for example an expression like (5.0+8.1)*(2.0) or ((5.0+8.1)*(2.0))/12.5” (not specifically in this format but represent the overall expression in an equivalent way). To design your classes you should think what common functionality and differences (fields and methods) these classes share and place such functionality at the appropriate place of the class hierarchy. Implement methods evaluate and display. Method evaluate evaluates the arithmetic expression that the object represents and returns the result as a double. For example, calling it in an object representing expression (5.0+8.1)*(2.0)   should return 26.2. Method display prints the raw (unevaluated) expression on the screen. For example, calling it in an object representing expression (5.0+8.1)*(2.0) should display the string (5.0+8.1)*(2.0) (without the quotes).You should NOT use static methods!
  • .      Implement a test class CalculatorTest which tests the functionality of your classes (the methods of your classes should be called and make sure that they do what they are supposed to do).
  • .     Implement a class RandomCalculations which automatically creates a random number of random expressions and uses your classes above to evaluate and display them. Every time that this class is run, a deferent number of deferent random expressions is evaluated and displayed. Test its functionality by calling its methods in the CalculatorTest class above.

First of all I have created an abstract class ArithmeticExpression and it has 2 abstract methods evaluate and display. And also it has two variables x, y.
Using that abstract class I have created four concrete classes for each arithmetic operation. Use these classes to do binary expressions.
When we are evaluating particular arbitrary expression we have to follow the BODMAS law. So there are three main ways to do this evaluation.
First one is using String class methods. Take the expression as a String and using String class methods and we can turn that into BODMAS pattern. But it takes huge amount of lines of code. So it is not a good way to implement an advanced calculator.
Second method is using a binary tree. It is very good and interesting way to break down the equation according to BODMAS. Following diagram shows how to do this using the split () method in String class.


Take the equation 2+5/6-(4+7*9). First of all we have to break it from parentheses. Then according to BODMAS we can store the expression in that tree.
Then we have to do the evaluation. We can use post order traversal method to travel through nodes and take the final answer.  But when it is a large expression the height of the binary tree rapidly increases. That means the efficiency of tree goes down. So this is also not a good way to evaluate a big expression.
Third and most suitable way to do this BODMAS evaluation is using STACKs. Using stacks we can turn this expression into Rivers Polish Notation (RPN). Last semester of the 1st year we had learnt about that in Software Development Principals. We can use one Stack and 2 string variables and successfully evaluate any large expression. This is the algorithm.
Stacks are used by compilers to helping the process of evaluating expressions and generating machine-language code. In this and the next exercise, we investigate how compilers evaluate arithmetic expressions consisting only of constants, operators and parentheses. Humans generally write expressions like3+4and7/9in which the operator (+ or / here) is written between its operands—this is called infix notation. Computers “prefer” postfix notation, in which the operator is written to the right of its two operands. The preceding infix expressions would appear in postfix notation as 34+and79/, respectively.
To evaluate a complex infix expression, a compiler would first convert the expression to postfix notation and evaluate the postfix version. Each of these algorithms requires only a single left-to right pass of the expression. Each algorithm uses a stack object in support of its operation, but each uses the stack for a different purpose. In this exercise, you will write a Java version of the infix-to-postfix conversion algorithm. In the next exercise, you will write a Java version of the postfix expression evaluation algorithm. In a later exercise, you will discover that code you write in this exercise can help you implement a complete working compiler.
Write class InfixToPostfixConverter to convert an ordinary infix arithmetic expression (assume a valid expression is entered) with single-digit integers such as (6 + 2)*5-8 / 4 to a postfix expression. The postfix version of the preceding infix expression is (note that no parentheses are needed)
6 2 +5*84 /
 The program should read the expression intoStringBufferinfix and use one of the stack classes implemented in this chapter to help create the postfix expression inStringBufferpostfix. The algorithm for creating a postfix expression is as follows:
a) Push a left parenthesis '(' on the stack.
b) Append a right parenthesis ')' to the end of infix.
c) While the stack is not empty, read infix from left to right and do the following:
ü  If the current character in infix is a digit, append it to postfix.
ü  If the current character in infix is a left parenthesis, push it onto the stack.
ü  If the current character in infix is an operator:
·         Pop operators (if there are any) at the top of the stack while they have equator higher precedence than the current operator, and append the popped operators to postfix.
·         Push the current character in infix onto the stack.
ü  If the current character in infix is a right parenthesis:
·         Pop operators from the top of the stack and append them to postfix until a left parenthesis is at the top of the stack.
·         Pop (and discard) the left parenthesis from the stack.
The stack should be maintained with stack nodes that each contain an instance variable and a reference to the next stack node. Some of the methods you may want to provide are as follows:
a) Method convertToPostfix, which converts the infix expression to postfix notation.
b) Method isOperator, which determines whether c is an operator.
c) Method precedence, which determines whether the precedence ofoperator1 (from the infix expression) is less than, equal to or greater than the precedence ofoperator2 (from the stack). The method returns trueifoperator1has lower precedence thanoperator2.
Otherwise, false is returned.
d) Method stackTop (this should be added to the stack class), which returns the top value of the stack without popping the stack. 
The program should read a postfix expression consisting of digits and operators into a StringBuffer.
Using modified versions of the stack methods implemented earlier in this chapter, the program should scan the expression and evaluate it (assume it is valid). The algorithm is as follows:
a) Append a right parenthesis ')' to the end of the postfix expression. When the right parenthesis character is encountered, no further processing is necessary.
b) When the right-parenthesis character has not been encountered, read the expression from left to right.
If the current character is a digit, do the following:
·         Push its integer value on the stack (the integer value of a digit character is its value in the computer’s character set minus the value of'0' in Unicode).
·         Otherwise, if the current character is an operator:
·         Pop the two top elements of the stack into variables x and y.
·         Calculate y operator x.
·         Push the result of the calculation onto the stack.
c) When the right parenthesis is encountered in the expression, pop the top value of the stack. This is the result of the postfix expression.
 First of all I have to create a stack using a linked list then I turned it into a stack and use it for evaluation.


package calculator;

class Node {
                                char value;
                                double data;
                                 Node next;

                public Node(){
                                value=' ';
                                next=null;
                 }
                public Node(char x){
                                value=x;
                                next=null;
                }
                 public Node(double y){
                                data=y;
                                next=null;
                }
}
 .....................................................................................................................................................
package calculator;

class List {
                Node head;

                public List(){
                                head=null;
                 }
                public boolean isEmpty(){
                                return head==null;
                }
                                public void delete(int index){
                                Node curr=head;
                                Node prev=null;
                                if(index>size()||index<1||isEmpty()==true){
                                                if(isEmpty()==true){
                                                                System.out.println("Empty list…");
                                                 }
                                                else{
                                                                System.out.println("Index should between 1 and list size.");
                                                }
                                }
                                else if(index==1){
                                                deleteHead();//delete index 1 = delete head
                                 }
                                else{
                                                for(int x=1;x<index;x++){
                                                                prev=curr;
                                                                curr=curr.next;
                                                 }
                                                prev.next=curr.next;
                                }
                }
                public void insert(int index,char value){
                                Node newPtr=new Node(value);
                                Node curr=head;
                                Node prev=null;
                                 if(index>size()+1||index<1){//can insert to index size()+1 means insert value to end
                                                System.out.println("Index should between 1 and list size.");
                                }
                                else if(index==1){
                                                insertHead(value);//insert index 1 = insert head
                                }
                                 else{
                                                 for(int x=1;x<index;x++){
                                                                prev=curr;
                                                                curr=curr.next;
                                                }
                                                newPtr.next=curr;
                                                 prev.next=newPtr;
                                 }
                }
                public void makeEmpty() {
                                 head= null;
                                System.out.println("Empty List....");
                }
                public int size(){
                                 int listSize=0;
                                Node a=head;
                                while(a!=null){
                                                 a=a.next;
                                                 listSize++;
                                }
                                 return listSize;
                }
                 public void insertHead(char x){
                                Node NewLink=new Node(x);
                                 if(head==null){
                                                 head=NewLink;
                                }
                                else{
                                                NewLink.next=head;
                                                head=NewLink;
                                }
                }
                 public void insertHead(double x){
                                Node NewLink=new Node(x);
                                 if(head==null){
                                                 head=NewLink;
                                }
                                else{
                                                NewLink.next=head;
                                                head=NewLink;
                                }
                }
                public void deleteHead(){
                if(head==null){
                                                System.out.println("Empty List....");
                                }
                                else {
                                                head=head.next;
                                }
                }
                public void search(int y){
                                Node curr=head;
                                 int index=0;
                                boolean isFound = false;
                                while(curr!=null){
                                                 index+=1;
                                                if(curr.value==y){
                                                                isFound=true;
                                                                System.out.println(y+" Found in index "+index);
                                                                curr=null;
                                                }
                                                 else{
                                                 curr=curr.next;
                                                 }
                                }
                                 if(isFound==false){
                                                System.out.println("Not Found...");
                                }
                }
   
                public void printNode(){
                                if(head==null){
                                                System.out.print("Empty List....");
                                }
                                for(Node a=head; a!=null; a=a.next){
                                                System.out.print(" "+a.value);
                                }
                }
}

.....................................................................................................................................................
package calculator;

public class ListStack extends List{
                 public void push(char c){
                                 insertHead(c);
                }
                 public void push(double c){
                                insertHead(c);
                }
                public void pop(){
                                 deleteHead();
                 }
                public char peek(){
                                 if(head==null){
                                                System.out.print("Empty List....");
                                }
                return head.value;
                 }
                public double dpeek(){
                                 if(head==null){
                                                System.out.print("Empty List....");
                                 }
                return head.data;
                }
    }
.....................................................................................................................................................package calculator;

public class InfixPostfixConverter {
                 StringBuffer infix;
                public InfixPostfixConverter(StringBuffer infix){
                                this.infix=infix;
                }
                public StringBuffer Convert(){
                                ListStack myStack=new ListStack();
                                StringBuffer postfix=new StringBuffer();
                                myStack.push('(');
                                infix=new StringBuffer(infix+")");

                                for(int i=0;i<infix.length();i++){
                                                 if(infix.charAt(i)>47 && infix.charAt(i)<58 || infix.charAt(i)=='.'){
                                postfix=new StringBuffer(postfix+Character.toString(infix.charAt(i)));
                                                  }
                                                 if(infix.charAt(i)=='('){
                                                myStack.push('(');
                                                }
                                                 if((infix.charAt(i) =='-') || (infix.charAt(i) =='+') || (infix.charAt(i) =='*') || (infix.charAt(i) =='/')){

                                                                 postfix=new StringBuffer(postfix+":");
                                                                 if(infix.charAt(i) ==47){
while(myStack.peek()!='*'&&myStack.peek()!='+'&&myStack.peek()!='-'&&myStack.peek()!='('){
               postfix=new StringBuffer(postfix+Character.toString((Character)myStack.peek())+":");
                myStack.pop();
  }
 myStack.push(infix.charAt(i));
               }
               if(infix.charAt(i) ==42){
               while(myStack.peek()!='+'&&myStack.peek()!='-'&&myStack.peek()!='('){
                 postfix=new StringBuffer(postfix+Character.toString((Character)myStack.peek())+":");
               myStack.pop();
               }
               myStack.push(infix.charAt(i));
               }
               if(infix.charAt(i) =='+'){
               while(myStack.peek()!='-'&&myStack.peek()!='('){
                   postfix=new StringBuffer(postfix+Character.toString((Character)myStack.peek())+":");
                   myStack.pop();
               }
               myStack.push(infix.charAt(i));
               }
               if(infix.charAt(i) =='-'){
               while(myStack.peek()!='('){
                   postfix=new StringBuffer(postfix+Character.toString((Character)myStack.peek())+":");
                   myStack.pop();
                  
               }
               myStack.push(infix.charAt(i));
               }
  }
           if(infix.charAt(i)==')'){
               while(myStack.peek()!='('){
                   postfix=new StringBuffer(postfix+":"+Character.toString(myStack.peek()));
                   myStack.pop();
               }
               myStack.pop();
           }
    }
return postfix;
}
}
.....................................................................................................................................................
package calculator;

public class ListStack extends List{
                public void push(char c){
                                 insertHead(c);
                }
                 public void push(double c){
                                insertHead(c);
                }
                public void pop(){
                                deleteHead();
                }
                public char peek(){
                                 if(head==null){
                                                System.out.print("Empty List....");
                                 }
                                 return head.value;
                 }
                public double dpeek(){
                                 if(head==null){
                                                 System.out.print("Empty List....");
                                 }
                return head.data;
                 }
    }


.....................................................................................................................................................