Ace IIT Programming Principles Courseworks

The blog is migrated to https://thiloshon.wordpress.com 

IIT is in my opinion a coursework-driven university where students believe they can learn more in the last two days before submission than in the entire lectures. At IIT programming is taught from the first day itself and I have seen students trying and failing to grasp the sense of programming and proper programming practices despite of lecturers trying all their best to provide students what they need. So this is from my experience of how to get good grades in 1st year CWs and to build on top of what you learned at IIT. Lecturers teach everything there is to get good grade and be a good programmer. If you listened to all the programming and design lectures and attended all the tutorials, then this blog is not probably for you. You know all this. For others, see if this makes sense.

This is the first part of 2-part blog. 2nd part covers 2nd CW.

Note: I’m using and recommending IntelliJ IDEA as the IDE and few of the demonstrations in the blog would need IDEA. IDEA is a cool IDE with great intellisense than NetBeans or Eclipse and I suggest you use IDEA.

The SDP module has two main CWs in the first semester

CW 01 – A Command Line Interface (CLI) Program
CW 02 – A Graphical User Interface (GUI) Program

Typically, the first CW is designed to test few learning outcomes namely,

  •         LO2 Write common algorithms involving sequence, selection, and iteration, and translate those algorithms into working programs using a range of key programming language instructions and syntax.
  •         LO3 Create and test code using appropriate features of an Integrated Development Environment which adhere to coding standards and proper layout
In simple terms, the 1st CW tests if you have understanding of,
  1.              Scanner and getting input
  2.              Storing data
  3.              Functions
  4.          Loops
  5.             Switch Case
And additionally,
  1.                Menu system
  2.                Validation
  3.                Exception handling
  4.               Comments
  5.              Proper coding practices
Before getting into the CW, I have seen students not being able to differentiate between CLI and GUI. They know what those are, but when it comes to programming, how these two differ is what they don’t get.

In Java, before IDEs came into existence, code was written in normal text editors (Notepad in Windows) and compiled and executed in the Terminals (Command Prompt in Windows). This is exactly what you did in first few weeks of tutorials. You would have used javac to compile the code and java to call the JVM. And after the IDEs came, the IDEs still have the same terminal but with a new look.

This is the terminal in IDEA and the code which runs only in this terminal, is the CLI application.

If the java code is written to view a new window and do event driven actions, then it’s a GUI application.

This is a typical GUI application.

But note even when this GUI component does all the actions there are few warnings in the terminal behind. The terminal can be used in the GUI application too. But there is no point in using terminal since user won’t see the terminal outputs when the GUI application is converted to a standalone application (as jar file).  But don’t worry if you don’t understand this, you will later.

So now that is covered, let’s get into the CW.

The first CW differs batch to batch but the evaluation is pretty much the same regardless of the specification. The specification is
  •          Get collections of input from user as the data.
  •          Store it appropriately utilizing best data structure.
  •          Do some sort of calculation and find results.
  •          Output results.
The first step of programming is to design. You should use multiple classes and should know how the data is going to flow between classes. After knowing this only, the code can be written efficiently.
In programming there are several architectural patterns. One such pattern is called MVC, Model-View-Controller. You are not expected to know what these are, but knowing the terms would help a lot in the Viva.

The model will be the model class to store the data user inputs. Something like,

class Student{
int iD
String name
String course
}

See here when a user inputs ID and Name details of the student an object of Student class can store those values. So when you get data of student ID 5, all his details will be stored in the student object of ID 5. This is a neat solution of storing data, isn’t it? This is the model. To store data.

View is just the way your application looks. If a GUI, how GUI looks is view. In CLI of this CW the basic menu based system is view. The menu is covered below.

Controller is the bridge between the view and the model. It has all the application logic and calculations and whatnots.

So the view class creates a basic menu. The model class gives the basic storage to data. The controller uses view to get data, stores it in model and does the logic. Right?

Okay, now the design is almost covered. Let’s come to model in the CW. Let’s say the CW is to get student details, store and then tell who got highest marks.

Model

The model would be something like,

class Student{
int iD
String name
int marks
}

We just need to store the marks right? This would suffice. But remember the attributes of this model class should have a restricted access. Why? Well that’s covered in the lecture so I’m not going to say.

So the best way to have the model class is,

class Student{
private int iD
private String name
private int marks
}

If these have private access how to access them? Using public getters and setters. How to create objects? Use a constructor.

class Student{
private int iD
private String name
private int marks

    public Student(int iD, String name, int marks) {
        this.iD = iD;
        this.name = name;
        this.marks = marks;
    }

    public String getiD() {
        return iD;
    }

 public String getName() {
        return name;
    }

    public String getMarks() {
        return course;
    }

    public void setID(int iD) {
        this.iD = iD;
    }

    public void setName(String name) {
        this.name = name;
    }

public void setMarks(int marks) {
        this.marks = marks;
    }
}

This would make a proper model class.
This code should be stored in a single java file. Don’t put model, controller everything in the same file. It would work but not a proper practice.

The View

Okay let’s get to view. In the CW its not expected to use MVC pattern, but to “ace” you will need it. But a menu based application is strictly expected. If you don’t have a menu, chances are your report will be thrown out of the room during Viva, literally. So if you feel like MVC is overkill, its fine but have this menu in your application.

So what is a menu? A simple navigation system to direct user to various functionalities of your application. For instance,

This is a simple menu of a university system. 

You get the choice in number from user and based on the number he gives, do that operation.
Next question is how to “do operation”? That is covered in Controller. Remember? Controller does all the logic and operations.

So the code for view would have all these System.out statements. But it will be inside a method.

class View{
   public void printMenu() {   
        System.out.println("WELCOME TO THE AWARD CALCULATION SYSTEM");
        System.out.println("-------------------------------------");
        System.out.println("Choose your option:");
        System.out.println("-------------------------------------");
        System.out.println("1 Add New Student");
        System.out.println("2 Add Marks");
        System.out.println("3 View Students List");
        System.out.println("4 Generate Award");
        System.out.println("5 Edit Modules");
        System.out.println("6 Generate Records");
        System.out.println("");
   }
}

So this is the basic view and you store this code in a separate java file.

The Controller

Controller connects both view and model. So in the controller class you create an instance of the View class and use it to print menu to the screen.

View view = new View();
View.printMenu(); would do that.

So how to “do operation”?  This is where switch and functions comes in handy. You define few functions to do the basic operations. Say,

addStudent(){
// body of the function 01
}
deleteStudent(){
// body of the function 02
}
viewStudent(){
// body of the function 03

}

likewise, and to call each of these functions, use a switch case.
So you print the view, get the choice user wants. And then navigate.

Scanner sc = new Scanner(System.in);

int option = sc.nextInt();
switch (option) {
            case 1:
                addStudent();
                break;
            case 2:
                deleteStudent();
                break;
            case 3:
                viewStudent();
                break;        
        }
Likewise.

How to store data?

Another place where students get confused is “why we need a Student class to store data? Why can’t we use array? When to go to array and when to array list? “

First of all we don’t really need a model class to store the values at all. Storing in arrays will work. But it’s so tedious with all kinds of object type and its ugly. If you are using OOP language make use of it.

“So if we use Student model class to store object why we need an array?”

To store the student objects! See, one student object will store data of one student. So if you need to get data of 20 different students, you need 20 student objects. And to store 20 objects, you need a data structure. Thus, the array.

The array you define will be of the type of the model you want to add.

How do you create an int array?
Int[] array = new int[size]; right?

How do you create an array of students?
Student[] studentArray = new Student[size];

And in this array you store the student objects.

Student st = new Student(iD, name, marks); // create one student object
studentArray[0] = st; // store in array

Student st2 = new Student(iD2, name2, marks2); // create another student object
studentArray[1] = st; // store in array

So in your operations use this array to access student details.

Loops are used as taught in the lectures, there is nothing to add.

I told to use functions to do operations. Don’t forget to call the menu at the end of each operation.
public void addStudent(){
 // body of the method

View.printMenu(); // calling menu print method
}

This way the menu keeps iterating getting choice from the user.

Aiming for 70s, 80s

You can easily get decent marks without even following what I have said. But to get an additional 10 or 20 marks and to get a great grade, the point below would be of some help.

Validation.

Validation is an essential part of any application. Validation is just checking if the input user gives aligns with the type he should give. Say, you get marks input. Marks can only be a numeral right. What if he types a string?
Simply, the program won’t do that operation. Yeah? But it’s much worse than that. It would throw an exception and application would terminate.
Reason being, you’re getting the marks from,

int marks = sc.nextInt(); method right?

This method only reads ints. When you give a string to this method an InputMismatchException will be thrown. This causes the application to terminate.

There are two workarounds to this, this is where the difference between validation and exception handling comes into play. If you just catch the exception and continue the logic, its exception handling.
       
  try{
            int marks = sc.nextInt();
        }catch (InputMismatchException e){
            System.out.println("You typed a non-numeral");
        }

This is try catch block. The exception handling. But you wouldn’t have learned this by the time you do 1st CW. So it’s better to do the validation. And another problem in this try catch is, if user types a string, there is no way to go back and get the marks again. The application simply keeps going forward. This is where validation comes in handy. So know when to use validation and when to use exception handling.

How to use validation?

                           int marks;
 while (!sc.hasNextInt()) {
                System.out.println("Please Choose Numeral");
                sc.next();
            }
            marks = sc.nextInt();

This code does the validation. While the sc.hasNextInt() returns false, i.e while input is not an int, keep asking for input. So when user inputs int, sc.hasNextInt() returns true, !sc.hasNextInt gives false, comes out of loop, gets the integer value and assigns it to marks. This is the basic validation.

Comments.

Commenting is another crucial part of programming. The code should be properly commented. Alright, you would have probably heard this before. So where exactly comments should be placed? In Java there are two types of comments,

  1.         Normal in-line and block comments
  2.          Java doc comments

I’m not going to talk about inline or block comments. You know line comments are used to help programmer understand what each line does and all.

The real deal is java doc comments. The start of java file should have a header comment. Header comment says what that java file is responsible for. Maybe a view class. So,

/***************************************

 * This file has a view class

 * The view class prints menu options to standard output

 * Don’t use it to order pizza.

 ***************************************/

Would be a proper header comment.

Each function should have a proper doc comment.

/**
* This is a function comment. This function gets student data and adds
* to the array
     *
     * @param iD   The ID of the student
     * @param name The name of the student
     * @param marks The marks of the student
*/

Notice here the function explanation is given first and then the parameter list is also given in the comment with annotation @param. This helps programmer understand what the function is and what parameters it takes without reading the function body.

In IntelliJ IDEA java doc can be easily created with shortcuts. Search on line for ways to do.

A sample code with comments.

Proper Coding Practice

This would have been mostly covered in lectures. In Viva lecturers check if your method, variable names are in camelCase, the class names start with Capital, have you used static methods in place of instance methods and so on. So take note of those too.

So this wraps the part one of the series. I rushed it a bit, because I got to know today that the submission is tomorrow (lol). So anyways, I’ll make a proper one later. Part two will cover GUI so come back later and check that too.

And almost all the students who don’t do the CW well are the ones who start late. Start doing it at least one and a half week before deadline. Programming is extremely fun. When you code everything yourself and when it runs in the machine perfectly the feel you get is priceless. If you copy the code, you won’t get the feel of programming. Try to do it yourself. If you don’t understand anything ask from seniors. Get their feedback on your code, improve. Check who got good grades in CWs and ask for their code. Read their code and see how they have programmed. Best way to improve programming is to read others code. Not to blindly copy, to improve.

If you want any more clarifications, comment below.

Good luck with your CW!


24 March 2017

Comments

Post a Comment

Popular posts from this blog

Dijkstra’s Algorithm For Path Finding Problems

Web Service, Implementing a

Web Services, The Theories and Concepts of

A List of Royalists and Thomians in the Corporate World

GSoC 2017 : Integrating biodiversity data curation functionality

How Dreams Work

A Kid with Leukemia.