Tuesday, November 8, 2011

Commentary to Student Test Scores System

The main wisdom of this week is in the way the most common business applications are usually designed. Spend some time in matching the UML diagram on fig. 10-4 to the classes in the help document that I uploaded to W10A Q&A. I will go now through the main features of those classes that are most important to understand.

Test Scores App (see diagram)

The most important function of this class is to provide “public static void main” method since when Java sees a bunch of classes with multiple methods – it doesn't know where to start compared to using programs versus pure classes, where you just have to start the execution from the first line in the program. So they use the trick – Java seeks the method called “main” and starts execution there.

Since its role is to be an entry point to the system of interacting classes and initialize the beginning of the system's operations it has to have minimum to nothing operations. In our case it determines (a la MVC) the active part which in event-driven environments (see my previous post) determine the sequence of execution – which is the VIEW (Test Scores View in our case). It also (attention here!) instantiates the specific Model (Test Scores Model) and passes it (the whole class!!!) as a parameter to the View. AND THAT'S IT! This is a very typical way of designing MVC systems for popular business (and other) uses. Next time you design the system of yo own – remember this pattern and just rewrite it. Chances are that this model will be your first model in all those cases (including this week's task)

TestScoresModel class

Usually the Model includes the class(es) that are clearly separated from the interface. Think if you can easily change interface from console dialog with loops to a complex GUI Window WITHOUT changing the Model. If you can – than you already satisfied the necessary condition for a proper model design.

In our case the model describes operations that can be performed on the main conceptual system of our project – which is... yes, you are right, which is the array of Students (Student objects created from the same Student class) – see the diagram, which starts looking more an more useful.

In typical business systems they usually have at least one in-memory database-like data structure. The typical operations for your future development, again without much thinking, will include full VCR-style navigation (first, last, previous, next) as well as the complete set of database file management CRUD operations (Create a record, Remove, Update, Delete). Additional operations required by the customer should also be here like: getClassAverage, getHighScore, etc.

Therefore, in this class you have to instantiate an adequate memory structure (array of objects in our case). Then you will ALWAYS need (again without thinking in the future) to have a variable like indexSelectedStudent, which keeps the current position. The CURRENT POSITION is a very important concept in data processing since all navigation operations (next, previous, etc) are done with respect to the Current Position stored in such variable. Then moving to the next or previous is a matter of adding or subtracting 1 from the current position. Remember that position starts with one, but index always works from 0. So some adjustment might be necessary.

In case of data structures where you have to decide on the length of the array in advance – a special variable like studentCount will be very important for control of the really filled records not to show the blank array elements and to minimize all the loops done on arrays to the real count of records (like looping only through 10 REAL records in an array that can have 10000 elements).

When a new Student object arrives or is replaced it is just a matter of assigning the pointer to that student to the element of the students array like in:

students[studentCount] = s;

Student class

Since the main conceptual focus is usually on complex data structures with multiple more simple elements (like Students in students array) we will need a special class for each of these simple (relatively) primary structures (classes) to maintain independence from their life cycles, like adding more elements and methods to Students making them more complicated.

TestScoresView

This is the VIEW, which designs and declares the View elements (see the program). Notice abundance of fields for information communication, buttons, etc. It can fit all the multiple dialog windows that some of you preserved in the first game GUI design.

Notice the well-developed constructor that has to provide a working version of the interface window at the start of the program (since it is event-driven and nothing is executed without user's actions on the interface).

A traditional method (you can use it in many cases similar to this one) is in the use of one Structure filling all the visible elements of the WHOLE interface - this is displayInfo method using all visible fields. The idea is that AT ALLL TIMES users should see something (otherwise they get scared and think that they ruined something). Such collection of fields in one method will be constantly reused in the View since after controllers do their thing – the result will be always in calling this method to prepare the image for the main interface window.

Also notice that using Model makes View operations (your task for the week) trivial – just get info from the screen or from the button (using Controller) and pass it to the Model for Execution with delivering the result back to the same displayInfo method.

Saturday, October 29, 2011

GUI and event-driven programming

This week A-Track (with B-Track to follow later) students will start using one important Java technology hidden in special object communications and behaviors provided with Java – GUI. GUI is not just a graphical interface but a whole different concept of communications and program logic. It makes threads of interactions with chains of questions obsolete and instead creates a set of windows and controls (buttons for now) that offer the user a choice of how to interact. GUI runs some internal loops waiting for various user actions and responds to any of such actions (mouseover, buttonpress, mouse down, etc.). For example instead of asking if the player wants to play again in a loop that you had to program manually – there is a rich choice of communication controls that user can initiate (like the button “Play Game” as one example) with event (like buttonpress) being passed to the listener waiting behind the scene.
Another important aspect to notice is that you are starting “event-driven” programming when code is executed not when you write your java command on console and even not when logic of one object calls method code to be executed from another object, but when some interface event happens that is passed to the listener object AND TRIGGERS its execution. AWT, that you include in the beginning of the program supports such event driven mechanism allowing various listener objects to subscribe for notification about some possible events happening to certain controls (text boxes, buttons, check boxes, radio buttons, etc.). When the event that the listener subscribed for occurs – Java “notifies” the listener by sending an event class with rich information about the event and allowing to trigger the code execution.
This shifted the method of program communication with the user from program-initiated one, with lots of loops polling the user for required information forcing to write complex logic fitting this loops in special sequences and nesting constructions, to user-controlled or event driven as described above. The benefit of MVC model and previous separation of Account and GameMachine classes from the Interface is that the new changes to GUI are done ONLY in the Interface class (if you PROPERLY separated it). If not – it is time to move the remaining game and accounting and possible other supporting actions into the Model section, which can consist of several classes interacting with each other or with Control components (listeners). In this case it is also good to clear the Application class with main() method from everything else just letting it start the Interface Window and instantiate the Interface class, which in turn will instantiate other necessary classes. It is not necessary to such clean-up of the Application class now but this is what you be doing later. In your first GUI driven program is important just to get rid of all user polling and allow for necessary windows and buttons to be properly placed on the main Window

Monday, October 17, 2011

Object-Oriented Design Part 1 (the beginning)

Congratulations! Now you know Java enough to write any program (as an algorithm)! As of now you know three sufficient language constructs: sequence, selection, and repetition. See the theorem ( http://en.wikipedia.org/wiki/Structured_program_theorem )  proving sufficiency of these constructs  for the design of any algorithm.
Then what is left in learning Java? Although we will pick a few small language enhancements – the main task will be in learning software engineering  as assembling (designing) increasingly complex software systems. The leading industrial approach to such engineering is called Object-Oriented design and programming. According to this approach (which we will be learning in more detail) – nobody writes programs. What do they do instead – is create classes (that will be instantiated as objects at runtime) and organize their interaction when the task triggers such collective attempt to solve the problem or just to be aware of the situation and react when necessary.  
This week gives you an introduction to the concept of classes and objects with some demonstration of data that an object can store and methods (work like local code libraries) that an object can invoke or that can be invoked by other objects in communication attempts.
A few good ideas for good design (many more to follow):
  1. A class should capture one and only one key abstraction/concept/responsibility. For example Student, Professor, Course, etc. are responsible for the behavior of particular entities with their data and methods (behaviors).  Thus a student can get a grade, be transferred, enroll into a course or drop one, pay the required tuition, can change the room in the dorm, etc. as well as have an assigned ID, name, address, telephone, and other data. Of course the program will work if to place these methods in, say, Course class, but following life modifications, updates, and relationships with other entities will become increasingly difficult.  Therefore an object is a special software construct combining properties of data types (allowing for information storage = state) and software libraries capable of executing the called process. Together they create a powerful combination capable of behaving as an entity (like Student) in a specific situation and state. They say that objects have state and behaviors. But in order to unleash their full capabilities – objects need to collaborate with other objects/entities providing necessary services and enriching overall system’s behavior.
  2. All data should be hidden within its class (called encapsulation): For now you might have direct access to data in a class, but in later designs should start avoiding such exposure allowing only access to the methods responsible for data reading/modifications (accessors and mutators”). We create private fields that hold the state of an object (like assigning a grade, a name, and address) and public methods that deal with them (in addition to other functions).  

Wednesday, October 12, 2011

Story about Java packages...

Once upon a time my son had a girlfriend (now she is “ex” and not because of poor programming skills). She graduated from college focusing on Java which she saw as a job and good salary guarantee with almost no need to use anything else. After graduation she got a job in a company which worked with sound processing and speech recognition using Java. Her initial salary (10 years ago) was $70K. Company over time developed a bunch of useful classes (just like the ones used in sound processing in week 6) but documented only using automated class documentation methods (just like in the package that A-stream students saw) that are difficult to understand and use. Just look at APSoundClip class packing a lot of free software in it, and imagine the time it would take you to create it from scratch. So she spent the first year struggling with such packages, learning what they can do and thus rapidly increasing her productivity and creative thinking (by knowing what ready-made blocks are available). Since it is a hard task in trying to understand and testing the classes – she, actually, was the only one who new almost all of their packages... and her boss. At some point her boss wanted to start another company (or blackmail the old one?) and invited her to join him. When the BIG boss learned about it he got really scared and offered her $95K and much more to her boss since if they would've left nobody could develop new products fast enough and all had to learn the packages for at least a year. And she was only 1 year after college and it was over 10 years ago... The moral of the story is that the experience that A-stream had in week 6 was tough but very interesting and important.

Sunday, October 9, 2011

Solution to problem 3-7

// Solution to Project 3.7
// Displays coordinates of the center point of the panel. Notice that there are two separate classes
// here that can be compiled separately but work together if are in the same folder
// When both classes are compiled - run this one (the first shown)
//since it has  " public static void main(... "
import javax.swing.*;   
import java.awt.*;      
public class GUIWindow{
   public static void main(String[] args){
      JFrame theGUI = new JFrame();
      theGUI.setTitle("GUI Program");
      theGUI.setSize(300, 200);
      theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      ColorPanel panel = new ColorPanel(Color.white);
      Container pane = theGUI.getContentPane();
      pane.add(panel);
      theGUI.setVisible(true);
   }
}

//Example 3.7: used together with the GUIWindow class but compiled
//as a separate class

import javax.swing.*;
import java.awt.*;
public class ColorPanel extends JPanel{
  
   public ColorPanel(Color backColor){
      setBackground(backColor);
   }
   public void paintComponent(Graphics g){
      super.paintComponent(g);
      int x = getWidth() / 2 - 60;
      int y = getHeight() / 2;
      g.setColor(Color.blue);
      g.drawRect(x, y, 120, 20);
      g.setColor(Color.red);
      g.drawString("Hello world!", x + 10, y + 15);
   }
}

Monday, September 19, 2011

Q&A Good job!

The Q&A forum was very successful last week. Especially the “'javac' is not recognized...” thread. Congratulations to the participants. Good Job!

You can see that these forums can become very valuable sources for students' support as well as places to show your own level of handling Java and getting extra points.

Monday, September 12, 2011

Classpath

Classpath. When yo urun the program in Command Prompt - you need to tell Java which of the compiled programs to use (you might have several different versions and compilations of the same program in different directories). I would recommend typing something like
set classpath=e:/progs
(if your compiled files with extension .class are in that directory on e-drive) or some other drive name. But since you can move your programs to different directories - every time yo start working with Java (or change your class directories) type the Classpath command as shown above. This command doesn't show the location of the system files (like javac.exe, etc.) but the location of your compiled programs (with .java extension). For various tasks you might want to create different subdirecitories (like e:/progs/w1 or e:/progs/w2) where you will place your source code and where after running javac you will find the compiled program with .class extension. Then when you want to run your program by issuing "java myprog" command - the system has to know where is the file that you want to run. Then before running your compiled program you have to set the classpath (one line command as I've just mentioned) but only in case the directory has been changed since you set your classpath in the beginning of the session. If your compiled programs will be in the same directory - then after the initial classpath setting you do not need to repeat it.

For other problems in the future - you can "google" them typing a short representative phrase/keyword in Google search. There are plenty of discussions and people with same problems and other people helping them out, as well as official information on the issue.

The main place for help will remain in QandA of each week...