Monday, December 08, 2008

Modularization - Important Stuff

Modularization has long been described to a "divide and conquer" approach to simplify complicated program logic.  Modularization requires taking a program with many logic steps and simplifying it by looking for sub routines within the entire program that can stand by themselves (i.e. a sales tax calculation, GPA average calculation).  Sub routines can then be grouped with other sub routines to complete the entire program.  This approach has long been used in engineering. 

For example, when they designed the Space Shuttle, they did not design the entire space craft on a single drawing taking in all of the details in a single design. Instead, they broke the project up into pieces and designed each of those pieces with the idea of integrating them all at the end (i.e.  communications module, thrust module, launch module, space craft controls module, etc.).  

The examples used in this blog are not as complicated as one would find in a typical program (so you may question why they would quality as a module) but the most important point to recognize is that these modules are typical of the blocks of code that exist in every program that really constitute a part of the entire application.

Modularization: Modularization defines the process of reviewing program logic to identify program subtasks. When we divide the program up into subtasks we make the design of logic simpler and more accurate. The logic contained within the subtasks is stored as modules. These modules are combined with statements to make up the program.

 

Modules: A module is a block of code that represents a program subtask. This subtask is a standalone piece of code that performs part of the programs solution but also could stand by itself and potentially be used in other programs. For example, I could create a sub-task that calculates the sales tax of a purchase. It is only part of the logic but is required for the final solution. Because it can stand alone, it could be reused in other programs that have a similar requirement (i.e. other programs also would need to calculate sales tax).


Code Reuse

Code reuse is perhaps the biggest benefit of modularization.  Code reuse can take place within a single program (In the case where lines of logic are called in multiple locations in your application) and also across different applications. 

Taking a sales tax calculation; for a retail business, how many times does a computer need to calculate sales tax.  Could be at the cash register, could be used again to calculate that days sales tax liability, could be used again when printing monthly customer credit card invoices.  Why have the same calculation code statements called over and over again.  Instead, we could take a block of statements and execute that code block as a module in more than one program.

This code reuse is a fundamental part of object orientated programming and a critical concept to understand and appreciate before learning to program with objects. There is also a quality benefit to code reuse.  Can you see it?

An Example

Example the following pseudo code.  There are two modules identified here.  One for sales discount and one for sales tax.  In the diagram the pseudo code on the left is change to call modules that contain the code to be executed.  The new pseudo code that calls the module can be seen on the top right of the diagram.  By setting the code up in modules, the sales discount and sales tax code modules could be executed multiple times. 






















Next up will be some examples of modularization in both Java and Visual Basic.Net.

If you have a question or point to make, send me a comment.


Wednesday, November 12, 2008

Find and Replace ... Found!


Find and Replace is one of the more useful features you can add to a control that holds text. I created this VB form to do a find first, find next, replace and replace all support.

The form was called as a modal form with .showDialog and a screen shot of just the form can be seen below. The Replace button is not enabled until Find First is clicked and the Replace All button is available without clicking on the find button. Find Next is also disabled until the first string is found. Bottom line: you must click on Find First or Replace All before using the other buttons. The program was written with Microsoft Visual Studio 2008 in Visual Basic.












Processing Logic

The program has been written to take advantage of some richtextbox control (mainForm.rtbBody) members (Find, Replace, SelectedText and SelectionColor) combined with some string functions. The program is reasonably straight forward perhaps with the exception of the richtextbox Find method which needs a search string, a starting point (in chars) to search,the length of the search term and the type of match (wholeword, case, etc. - see VB documentation for richtextbox.find method). The starting point of the find changes to start just after the last find so that find next and replace all can continue to search through the textbox.

You should be able to duplicate the form design and copy the code below into your application to test. Note: I had to truncate some lines with continuation characters to fit inside blog post window.

As always in this blog: Use this program example at your own risk. This code was created for educational purposes only. The author provides programming code "as is" and provides no warranty or guarantee. If you have questions, If you can email the author at gmarrer@gmail.com

Visual Basic.Net 2008 Source Code (with Program Comments)

Public Class findreplace
'class instance variables
Private findText As String ' find text
Private replaceText As String ' replace text
Private selectionStart, selectionLen, lastStart As Integer 'position variables for search


Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles btnClose.Click

'close form
Me.Close()
End Sub

Private Sub btnFind_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles btnFind.Click

'if no text in find textbook
If txtFind.Text <> "' then" Then
'get ready to find the text
findText = txtFind.Text
'find text
selectionStart = mainForm.rtbBody.Find(findText, RichTextBoxFinds.WholeWord)
If selectionStart <>
'text not found
MessageBox.Show(findText & " Text Not Found", "Warning", MessageBoxButtons.OK, _
MessageBoxIcon.Exclamation)

Else
'turn on replace and find next
btnReplace.Enabled = True
btnFindNext.Enabled = True
'set new start point for continued search
lastStart = selectionStart
'start the selected text
mainForm.rtbBody.SelectionStart = selectionStart
'get len of selected text
mainForm.rtbBody.SelectionLength = findText.Length
'mark selected text red in richtextbox
mainForm.rtbBody.SelectionColor = Color.Red
End If
Else
'No text in Find input textbox
MessageBox.Show("No find string entered. Please key in a value to find.", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)

txtFind.Focus()
End If
End Sub

Private Sub btnReplace_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles btnReplace.Click

'text in find textbox
If txtFind.Text <> "" Then '
'text in replace textbox
If txtReplace.Text <> "" Then
'get replace text from textbox
replaceText = txtReplace.Text
'replace selected text found with replacement text
mainForm.rtbBody.SelectedText = replaceText
'mark selected text red in richtextbox
mainForm.rtbBody.SelectionColor = Color.Red
Else
'text in replace textbox missing
MessageBox.Show("No replace string entered. Please key in a value to find.", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)

'put cursor in replace textbox
txtReplace.Focus()
End If
Else
'text in find textbox missing
MessageBox.Show("No find string entered. Please key in a value to find.", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)

'put cursor in find textbox
txtFind.Focus()
End If
End Sub

Private Sub btnFindNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles btnFindNext.Click

'make sure find text is still there - mostly cosmetic
If txtFind.Text <> "' then" Then
'find text
selectionStart = mainForm.rtbBody.Find(findText, lastStart + findText.Length, _
mainForm.rtbBody.TextLength, RichTextBoxFinds.WholeWord)

'no more occurances
If selectionStart <>
MessageBox.Show(findText & " No more occurances Found", "Warning", _
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

Else
'select and mark the found text
lastStart = selectionStart
mainForm.rtbBody.SelectionStart = selectionStart
mainForm.rtbBody.SelectionLength = findText.Length
mainForm.rtbBody.SelectionColor = Color.Red
End If
Else
'find input textbox is empty
MessageBox.Show("No find string entered. Please key in a value to find.", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)

'put cusor in find textbox
txtFind.Focus()
End If

End Sub

Private Sub btnReplaceAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles btnReplaceAll.Click


'find and replace textboxes should not be empty
If txtFind.Text <> "" And txtReplace.Text <> "" Then
'store find text
findText = txtFind.Text
'store replace text
replaceText = txtReplace.Text
selectionStart = 0
'find first occarance
selectionStart = mainForm.rtbBody.Find(findText, RichTextBoxFinds.WholeWord)
'set new start point for continued search
lastStart = selectionStart
'Text not found test
If selectionStart <>
MessageBox.Show(findText & " Text Not Found", "Warning", MessageBoxButtons.OK, _
MessageBoxIcon.Exclamation)

Else
'text found replace text and mark with red
lastStart = selectionStart
mainForm.rtbBody.SelectionStart = selectionStart
mainForm.rtbBody.SelectionLength = findText.Length
mainForm.rtbBody.SelectedText = replaceText
mainForm.rtbBody.SelectionColor = Color.Red
End If
'Are there more occurances - loop until none or -1
While selectionStart >= 0
'search for text
selectionStart = mainForm.rtbBody.Find(findText, lastStart + findText.Length, _
mainForm.rtbBody.TextLength, RichTextBoxFinds.WholeWord)

'if no more occrances exit
If selectionStart <>
Exit While
Else
'set new start point for continued search
lastStart = selectionStart
'select text, replace and mark red
mainForm.rtbBody.SelectionStart = selectionStart
mainForm.rtbBody.SelectionLength = findText.Length
mainForm.rtbBody.SelectedText = replaceText
mainForm.rtbBody.SelectionColor = Color.Red
End If
End While

Else
'test must be in find and replace textboxes
MessageBox.Show("Find and Replace Text must both be entered into Textboxes.", _
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

'place cursor in find textbox
txtFind.Focus()
End If
End Sub
End Class


Monday, October 13, 2008

Reading and Writing Parameter Files with VB/LINQ

A little trickery with Visual Basic.Net 2008 this week. LINQ Language integrated query is a new tool in the .Net toolbox. Aside from providing a clever SQL like facility for filtering data, if you like XML for parameter files, it can provide a simple way of reading and writing application parameter data.

I was using this the other day as I was providing application settings for a program I am working on. I was looking for a quick way to store settings (autosave, defaultFont, defaultBrowser, etc.) for my application. The program is still growing so at this point I am not sure I have isolated all of the application parameters I want to let my users save. I had a couple for sure and wanted to add more later. XML was a easy way for my to keep track of what I have now and a way to add more later. Here is the XML file I created. Pretty standard. XML version tag and then a well formed document.

XML file - settings.xml

<settings>
<autosave>
true
</autosave>
<defaultbrowser>
firefox
</defaultbrowser>
<defaultfont>
Arial
</defaultfont>
<defaulttextcolor>
black
</defaulttextcolor>
</settings>

The elements each represent a program setting (i.e. autosave).

In my VB program I have a form I created that connects to a class module. I use the class module to load and save the xml values. The class module allows my to reuse this code across other forms/classes/programs etc.. (If you look back into previous blog entries you will see some dicussion on class objects).


As always in this blog: Use this program example at your own risk. This code was created for educational purposes only. The author provides programming code "as is" and provides no warranty or guarantee. If you have questions, If you can email the author at gmarrer@gmail.com

blue - Vb statements
red - LINQ
green - XML


Here is the load method for the XML:

'Class module called SettingsClass
Public Class SettingsClass
'instance variables
Private cAutosave As Boolean
Private cdefaultFont As String
Private cdefaultBrowser As String
Private cdefaultTextColor As String


(code removed here...)

Public Sub loadXML()
'declare and define xml doc type
Dim mySettings As New XDocument

'point to settings.xml file
mySettings = XDocument.Load("settings.xml")

'dimension object to hold elements. F
or this app, there is only one row entry holding four elements.
'LINQ is used to assign data from the XML file. The LINQ expression is on the right side of the =
Dim xmlSetting = From x In mySettings...
'use try to process runtime errors
Try
'read each entry in list - only one for this app
For Each valueItem In xmlSetting

'one variable for each XML element. the elements are retrieved as string datatype
'convert autosave from string to boolean
If valueItem..Value = "true" Then

cAutosave = True
Else
cAutosave = False
End If
'autosave, defaultFont, defaultBroser, defaultTextColor are XML elements
cdefaultFont = valueItem..Value
cdefaultBrowser = valueItem..Value
defaultTextColor = valueItem..Value
Next
'process anty runtime exceptions - you can customize this will multiple catch blocks
Catch ex As Exception

MessageBox.Show("Settings File Loading Error", "File Open/parse Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub


Now lets look at the save method to see how the XML settings file is saved. Note: a new file is created rather than updating the original. You might want to make a backup as part of your application processing.

Public Sub saveXML()
' working local variables
Dim newXML As String

'turn on exception handling

Try
'assign XML text to string variable to be written out later. Note the use of underscore _ continuation character
newXML = "" & vbCrLf & _
"" & vbCrLf & _
"" & cAutosave & "" & vbCrLf & _
"" & cdefaultBrowser & "" & vbCrLf & _
"" & cdefaultFont & "" & vbCrLf & _
"" & cdefaultTextColor & "" & vbCrLf & _
""

' write string to settings.xml text file
My.Computer.FileSystem.WriteAllText("settings.xml", newXML, False)
Catch ex As Exception
MessageBox.Show("Settings File Saving Error", "File Save Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

End Sub


You can still process you setting files with file streaming but I like this soltuion because the structure of the XML makes is more like a record and there are very few lines of code.

Look it over... How would look it it was C#?

Monday, October 06, 2008

A Piece of Pie with your Java












In this installment of ACWCP with programming examples, I am presenting a Java application that creates a simple pie chart.  

This version of the application extends JFrame to create a driver class (with main method) so that the calculations and logic in the paint method will draw a simple pie chart.  It asks the user to input four values and then does the math to paint a pie chart with four slices.

You can change and use the code anyway you would like but understand it is use at your own risk with no warranties or guarantees (legal stuff).    

The program starts with the main method.  It will ask the user via JOptionPane input dialog boxes for four values.  These values will be included in the declare/instantiation of JFPieChart as part of the constructor.

The constructor is called first.  The values are passed as strings and converted to integers.  A try/catch block makes sure that if a string number is not passed that the application will not abort with a runtime error.  NumberFormatException handling was added to allow for a more graceful exit.  You may want to change the code in the catch block depending on your application. 

The paint method is called by the runtime environment whenever it needs to repaint the items in the paint method.  Variables changed in your constructor will cause the paint method to fire and paint the sections of pie with the same point of origin.  This has the effect of creating a pie wheel of pie slices.  The last activity is to place a legend and title at the side and bottom of the window frame.  

The Code:

// Gary Marrer - JFPieChart.java
// October 2008
// Use this program example at your own risk.  This code was created for educational purposes only.
// The author provides programming code "as is" and provides no warranty or guarantee. If you have questions,
// you can email the author at  gmarrer@gmail.com

//  import relevant package files
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;

// extend JFrame to test pie chart creation
// you can use the constructor and paint method in other classes
public class JFPieChart extends JFrame
{

// class instance variables
// used by multiple methods inside this class
private int a, b, c, d, ax, bx, cx, dx, tot;
private static String first, second, third, forth;

// constructor sets private instance variables
    public JFPieChart(String v1, String  v2, String v3, String v4)
    {
// turn on exception handling for NumberFormatException
        try
        {
//convert String values to int for pie chart calculation
a = Integer.parseInt(v1);
b = Integer.parseInt(v2);
c = Integer.parseInt(v3);
d = Integer.parseInt(v4);
// add the values
tot = a + b + c + d;

// calculate pie section
ax = (360 * a) / tot;
bx = (360 * b) / tot;
cx = (360 * c) / tot;
dx = (360 * d) / tot;
        }

// exception handling
        catch (NumberFormatException e)
        {
                JOptionPane.showMessageDialog(null, "Error Message- Number Format Exception: " + e.getMessage(), "Error message",JOptionPane.ERROR_MESSAGE);
        }
        catch (Exception e)
        {
                 JOptionPane.showMessageDialog(null, "Unknown Error Message - Aborting " + e.getMessage(), "Error message",JOptionPane.ERROR_MESSAGE);

        }
    } // end JFPieChart

// paint called by system when screen needs refreshing
    public void paint(Graphics g)
    {
//  used to create Java2D API environment
Graphics2D g2d = (Graphics2D) g;

// Chart Title - set font, color and background
g.setFont(new Font("Arial", Font.BOLD, 16));
g.drawString("Sample Pie Chart",15,200);
g.setColor(Color.black);
g.fillRect(0,0,500,500);

//  Start Java2D code
// set colors, stroke and location of point to anchor pie slice
// place each pie slice next to the other
g2d.setPaint(Color.blue);
g2d.setStroke( new BasicStroke(1.0f));
g2d.fill(new Arc2D.Double(15,35, 80, 80, 0 , ax, Arc2D.PIE));
g2d.setPaint(Color.orange);
g2d.setStroke( new BasicStroke(1.0f));
g2d.fill(new Arc2D.Double(15,35, 80, 80, 0 + ax, bx, Arc2D.PIE));
g2d.setPaint(Color.green);
g2d.setStroke( new BasicStroke(1.0f));
g2d.fill(new Arc2D.Double(15,35, 80, 80, 0 + ax + bx, cx, Arc2D.PIE));
g2d.setPaint(Color.white);
g2d.setStroke( new BasicStroke(1.0f));
g2d.fill(new Arc2D.Double(15,35, 80, 80, 0 + ax + bx + cx , dx, Arc2D.PIE));

//  draw Legend - color
g.setColor(Color.white);
g.drawString( "Value 1 = " + a  ,250,50);
g.drawString("Value 2 = " + b ,250,100);
g.drawString("Value 3 = " + c ,250,150);
g.drawString("Value 4 = " + d ,250,200);

    } // end paint

// main is used in this program to provide input to the pie chart
//drawing routines
     public static void main(String args[])
{
// ask user for four values
  first = JOptionPane.showInputDialog("Enter First Number");
        second = JOptionPane.showInputDialog("Enter Second Number");
        third = JOptionPane.showInputDialog("Enter Third Number");
        forth = JOptionPane.showInputDialog("Enter Forth Number");

// insatiate the class and call constructor. Pass four user values.
JFPieChart pie = new JFPieChart(first, second, third, forth);
// size of frame
pie.setSize(500,500);
// close app when frame is closed
pie.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// make pie chart visible - this needs to be last statement before Frame is displayed
pie.setVisible(true);
} // end main

}

Run it, change it and include it in your programs.  

If you have a comment, send it along as a comment.  

Happy Programming...

p.s. Anyone know where the picture came from?

Saturday, October 04, 2008

Content Change


The ACWCP blog has so far, for the most part, been programming language neutral. I have focused on programming concepts (structured and object orientated programming) and stayed away from examples in specific programming languages. This has probably limited the number of posts I have placed in the blog since the focus was no general concepts alone. There was not a lot of details or specific code snippets to illustrate the example in programming code. This is going to change.

Working forward, I will include examples of Java, Visual Basic, C# and PYTHON in the blog. In some cases, I will demonstrate a concept in a particular languages and in other cases, I will show two languages side by side (a comparison so to speak). This is all in hopes of making the blog more interesting and also provide the raw material for future blogs. Watch next week as my first blog entry with this new focus.

Let me know what you think on my plan... If there is something you have a question about or and example you would like review, send a comment. I will try to post it to the blog.

Wednesday, August 27, 2008

Programmers: Why should we start with a plan...?

Most of the software development tools we have today include visual designers (that contain dozens of visual screen components) that allow us to prototype our user interfaces. By prototyping we can see what our user's see and greatly improve the quality of our interface and also reduce the time needed to built graphical interfaces. This is a GOOD thing but like everything it can be abused. Prototyping the user interface is no substitute for planning the logic that sits behind the screen. This blog topic addresses this issue.

If you are going to be a programmer you have got to plan...

Why do we construct logic models (flow charts and pseudo code) to create computer programs? This is certainly a very valid question and one I have heard many times from programming students. I’ve had many new student programmers who have been in a rush to program. This is a very natural reaction. Our enthusiasm to get started along with the uncertainty of learning a new subject, drive our desire to create our first program. It is difficult to stay patient as we move through the topics of flow charting and pseudo code knowing that you can open that editor and start building your screens or writing your code.

Resist the temptation for a little while longer as we again discuss the discipline of programming. The adage “anything worth having is worth waiting for” is very appropriate explanation of where we are at in your programming training. A little patience now is important as we build a foundation that will help you become a more effective and efficient programmer.

I covered in other blogs about the discipline of programming. I explained that having discipline as a programmer meant approaching programming with a professional standardized process. This discipline has been used by other programmers and has evolved over time from numerous successful programming projects. This is not unlike the professional standards and processes developed by accountants, lawyers, engineers and other professionals.

There are many analogies I could use to demonstrate how program discipline is exhibited and why it is important. One of my favorites is building a house from scratch. We all know what a house looks like and we could go down to the local hardware store and buy the supplies and start putting together a house. Without following the standards used by professional builders (blueprints, accepted construction techniques, building code regulations), we might end up with something that looks like a house (a structure with a roof and four walls) but it’s unlikely that it would be of the quality that was found in a house built by a professional. It might have an unsafe design. We might not be able to remodel or repair the house later on because of its non-standard construction. It would a structure that would probably not stand the test of time like a house built using established standards and techniques.

How about another analogy? Are you the kind of person who doesn’t like to read directions? Do you buy a product from the store and instead of reading over the assembly instructions you simply start putting things together based on the picture on the box? When it comes to installing new software from a CD-ROM to your personal computer, do you just place the CD-ROM in the drive and take all the defaults or do you read the instructions on how to install it properly. Most of the time, the software installs okay. Sometimes the original install seems successful and after awhile you realized the software was not installed correctly and you have to reinstall again. Normally the reinstall is not a problem but you had customized your software settings, the new install will probably wipe them out so that you will need to reconfigure them again. This will be the penalty for your haste. This is why the discipline of programming is so important to becoming an effective programmer.

If you do not take the time to use good programming processes during your project (like building logic models first) and you might find a serious problem later on after the program has been in use. This is the worst kind and most embarrassing type of programming design error. Programs that require a lot of rework and repair just after installation are poorly designed programs and a sure sign that programming discipline was not followed.

What do you think? Ready to build at flowcharts?

Monday, August 04, 2008

Multi Dimension Arrays - the double subscript

As you would have seen from earlier posts, a single dimension array looks much like many boxes stacked on top of one another. All single dimension arrays have one column and many rows. It is also possible to create multi-dimensional arrays. The most common of these multi-dimensional arrays are two dimensional arrays which have multiple columns and multiple rows (much like a spreadsheet has rows and columns). In addition, you can also work with arrays that are three and four dimensions but these arrays are difficult to conceptualize and outside what we can cover in this post. We concentrate on single dimension arrays in our case studies but we will spend a little time in understanding how single and two dimensional arrays are different.

When accessing elements in a two dimensional array, I have two subscripts. One subscript identifies the row and the second subscript identifies the column. Below, I have created a graphic showing a two dimensional array with the array subscripts identified in the diagram.












Figure 3: A multi-dimensional array diagrammed

The declaration of a two dimensional array is similar to a one dimensional array as the code statement below illustrates:

oneDimArray[10]
twoDimArray[10][5]
The single dimension array named oneDimArray has ten elements with subscripts 0 through 9. The two dimension arrays of the named twoDimArray has 50 elements with subscripts addresses 0,0 to 4,9. The two dimension array also has subscripts and that start at 0. The difference is in the fact that with a single dimension array you have one subscript and with the Multi-Dimensional array you have at least two subscripts.

In regards to assigning a value to a two dimensional array the same rules As with a single dimension array also apply. To store a value of 10 in the 3rd row 2nd column of an array called twoDimArray would look like the following in pseudo code:

twoDimArray(2,1) = 10

Take note of the subscripts. They are one less than the rows and columns requested above. This is to compensate for the fact that multi dimensional arrays also start with 0 for both the first row and first column.