Saturday, June 15, 2013

When to Use Inheritance?

Reference: http://msdn.microsoft.com/en-us/library/27db6csx%28v=vs.90%29.aspx
Inheritance is a useful programming concept, but it is easy to use inappropriately. Often interfaces do the job better. This topic and When to Use Interfaces help you understand when each approach should be used.
Inheritance is a good choice when:
<![if !supportLists]>·         <![endif]>Your inheritance hierarchy represents an "is-a" relationship and not a "has-a" relationship.
<![if !supportLists]>·         <![endif]>You can reuse code from the base classes.
<![if !supportLists]>·         <![endif]>You need to apply the same class and methods to different data types.
<![if !supportLists]>·         <![endif]>The class hierarchy is reasonably shallow, and other developers are not likely to add many more levels.
<![if !supportLists]>·         <![endif]>You want to make global changes to derived classes by changing a base class.
These considerations are discussed in order below.

Inheritance and "Is a" Relationships


Two ways to show class relationships in object-oriented programming are "is a" and "has a" relationships. In an "is a" relationship, the derived class is clearly a kind of the base class. For example, a class named PremierCustomer represents an "is a" relationship with a base class named Customer because a premier customer is a customer. However, a class named CustomerReferral represents a "has a" relationship with the Customer class because a customer referral has a customer, but a customer referral is not a kind of customer.
Objects in an inheritance hierarchy should have an "is a" relationship with their base class because they inherit the fields, properties, methods, and events defined in the base class. Classes that represent a "has a" relationship with other classes are not suited to inheritance hierarchies because they may inherit inappropriate properties and methods. For example, if the CustomerReferral class were derived from the Customer class discussed previously, it might inherit properties that make no sense, such as ShippingPrefs and LastOrderPlaced. "Has a" relationships such as this should be represented using unrelated classes or interfaces. The following illustration shows examples of both "is a" and "has a" relationships.

Base Classes and Code Reuse


Another reason to use inheritance is the advantage of code reuse. Well-designed classes can be debugged once and used over and over as a basis for new classes.
A common example of effective code reuse is in connection with libraries that manage data structures. Suppose, for example, that you have a large business application that manages several kinds of in-memory lists. One is an in-memory copy of your customer database, read in from a database at the beginning of the session for speed. The data structure might look something like the following:
VB
Class CustomerInfo
    Protected PreviousCustomer As CustomerInfo
    Protected NextCustomer As CustomerInfo
    Public ID As Integer 
    Public FullName As String 
 
    Public Sub InsertCustomer(ByVal FullName As String)
        ' Insert code to add a CustomerInfo item to the list. 
    End Sub 
 
    Public Sub DeleteCustomer()
        ' Insert code to remove a CustomerInfo item from the list. 
    End Sub 
 
    Public Function GetNextCustomer() As CustomerInfo
        ' Insert code to get the next CustomerInfo item from the list. 
        Return NextCustomer
    End Function 
 
    Public Function GetPrevCustomer() As CustomerInfo
        'Insert code to get the previous CustomerInfo item from the list. 
        Return PreviousCustomer
    End Function 
End Class
Your application may also have a similar list of products the user has added to a shopping cart list, as shown in the following code fragment:
VB
Class ShoppingCartItem
    Protected PreviousItem As ShoppingCartItem
    Protected NextItem As ShoppingCartItem
    Public ProductCode As Integer 
    Public Function GetNextItem() As ShoppingCartItem
        ' Insert code to get the next ShoppingCartItem from the list. 
        Return NextItem
    End Function 
End Class
You can see a pattern here: two lists behave the same way (insertions, deletions, and retrievals) but operate on different data types. Maintaining two code bases to perform essentially the same functions is not efficient. The most efficient solution is to factor out the list management into its own class, and then inherit from that class for different data types:
VB
Class ListItem
    Protected PreviousItem As ListItem
    Protected NextItem As ListItem
    Public Function GetNextItem() As ListItem
        ' Insert code to get the next item in the list. 
        Return NextItem
    End Function 
    Public Sub InsertNextItem()
        ' Insert code to add a item to the list. 
    End Sub 
 
    Public Sub DeleteNextItem()
        ' Insert code to remove a item from the list. 
    End Sub 
 
    Public Function GetPrevItem() As ListItem
        'Insert code to get the previous item from the list. 
        Return PreviousItem
    End Function 
End Class
The ListItem class needs only to be debugged once. Then you can build classes that use it without ever having to think about list management again. For example:
VB
Class CustomerInfo
    Inherits ListItem
    Public ID As Integer 
    Public FullName As String 
End Class 
Class ShoppingCartItem
    Inherits ListItem
    Public ProductCode As Integer 
End Class
Although inheritance-based code reuse is powerful tool, it also has associated risks. Even the best-designed systems sometimes change in ways the designers could not foresee. Changes to an existing class hierarchy can sometimes have unintended consequences; some examples are discussed in "The Fragile Base Class Problem," in Base Class Design Changes After Deployment.

Interchangeable Derived Classes


Derived classes in a class hierarchy can sometimes be used interchangeably with their base class, a process called inheritance-based polymorphism. This approach combines the best features of interface-based polymorphism with the option of reusing or overriding code from a base class.
An example where this can be useful is in a drawing package. For example, consider the following code fragment, which does not use inheritance:
VB
Sub Draw(ByVal Shape As DrawingShape, ByVal X As Integer, _
    ByVal Y As Integer, ByVal Size As Integer)
 
    Select Case Shape.type
        Case shpCircle
            ' Insert circle drawing code here. 
        Case shpLine
            ' Insert line drawing code here. 
    End Select 
End Sub
This approach poses some problems. If someone decides to add an ellipse option later, it will be necessary to alter the source code; it is possible that your target users will not even have access to your source code. A more subtle problem is that drawing an ellipse requires another parameter (ellipses have both a major and a minor diameter) that would be irrelevant to the line case. If someone then wants to add a polyline (multiple connected lines), then another parameter would be added, and it would be irrelevant to the other cases.
Inheritance solves most of these problems. Well-designed base classes leave the implementation of specific methods up to the derived classes, so that any kind of shape can be accommodated. Other developers can implement methods in derived classes by using the documentation for the base class. Other class items (such as the x- and y-coordinates) can be built into the base class because all descendants use them. For example, Draw could be a MustOverride method:
VB
MustInherit Class Shape
    Public X As Integer 
    Public Y As Integer 
    MustOverride Sub Draw()
End Class
Then you could add to that class as appropriate for different shapes. For example, a Line class might only need a Length field:
VB
Class Line
    Inherits Shape
    Public Length As Integer 
    Overrides Sub Draw()
        ' Insert code here to implement Draw for this shape. 
    End Sub 
End Class
This approach is useful because other developers, who do not have access to your source code, can extend your base class with new derived classes as needed. For example, a class named Rectangle could be derived from the Line class:
VB
Class Rectangle
    Inherits Line
    Public Width As Integer 
    Overrides Sub Draw()
        ' Insert code here to implement Draw for the Rectangle shape. 
    End Sub 
End Class
This example shows how you can move from general-purpose classes to very specific classes by adding implementation details at each level.
At this point it might be good to reevaluate if the derived class truly represents an "is a" relationship, or instead is a "has a" relationship. If the new rectangle class is just composed of lines, then inheritance is not the best choice. However, if the new rectangle is a line with a width property, then the "is a" relationship is maintained.

Shallow Class Hierarchies


Inheritance is best suited for relatively shallow class hierarchies. Excessively deep and complex class hierarchies can be difficult to develop. The decision to use a class hierarchy involves weighing the benefits of using a class hierarchy against complexity. As a general rule, you should limit hierarchies to six levels or fewer. However, the maximum depth for any particular class hierarchy depends on a number of factors, including the amount of complexity at each level.

Global Changes to Derived Classes Through the Base Class


One of the most powerful features of inheritance is the ability to make changes in a base class that propagate to derived classes. When used carefully, you can update the implementation of a single method, and dozens—or even hundreds—of derived classes can use the new code. However, this can be a dangerous practice because such changes may cause problems with inherited classes designed by other people. Care must be taken to ensure that the new base class is compatible with classes that use the original. You should specifically avoid changing the name or type of base class members.
Suppose, for example, that you design a base class with a field of type Integer to store zip code information, and other developers have created derived classes that use the inherited zip code field. Suppose further that your zip code field stores five digits, and the post office has expanded zip codes with a hyphen and four more digits. In a worst-case scenario, you could modify the field in the base class to store a 10-character string, but other developers would need to change and recompile the derived classes to use the new size and data type.
The safest way to change a base class is to simply add new members. For example, you could add a new field to store the additional four digits in the zip code example discussed previously. That way, client applications can be updated to use the new field without breaking existing applications. The ability to extend base classes in an inheritance hierarchy is an important benefit that does not exist with interfaces.

Thursday, June 13, 2013

Information on batch files

Batch file ABCs
Batch files allow MS-DOS and Microsoft Windows users to create a lists of commands to run in sequence once the batch file has been executed. For example, a batch file could be used to run frequently run commands, deleting a series of files, moving files, etc. A simple batch file does not require any special programming skills and can be done by users who have a basic understanding of MS-DOS commands.
A good example of a batch file for someone who is more familiar with Windows or the MacOS is to think of a batch file as a shortcut in Windows or an icon on the MacOS. Much like a shortcut, batch files could be used to run one or more commands or programs through the command line.
Another example of a very well known batch file is the autoexec.bat, which is a boot batch file loaded each time the computer boots into MS-DOS and early versions of Windows. This batch file contained all the necessary commands and programs used to run MS-DOS and Windows each time the computer booted.
Creating a batch file
MS-DOS users
Microsoft Windows and other users

MS-DOS users
To create a basic batch file in MS-DOS, follow the below steps that give you an example of how to create a basic batch file.
  1. Open an MS-DOS command window or get to MS-DOS.
  2. At the MS-DOS prompt, type: edit test.bat and press enter.
  3. If typed properly, you should now be in a blue screen. Within the screen, type:

    pause
    dir c:\windows
    dir c:\windows\system
  4. Once the above three lines have been typed in, click File and choose exit; when prompted to save, click "Yes." Users who do not have a mouse cursor can accomplish this same task by pressing ALT+F to access the file menu, then pressing "X" to exit, and pressing enter to save changes.
  5. Once you are back at the MS-DOS prompt, type: test and press enter. This will execute the test.bat file and begin running the file. Because the first line is pause, you will first be prompted to press a key. Once you press a key the batch file will run line-by-line; in this case, listing the files in the windows and windows\system directories.
If you wish to add more lines to this batch file you would type "edit test.bat" to edit the file again.
Additional information about the MS-DOS edit command can be found on our edit command page. Some versions of MS-DOS and bootable diskettes may not have the edit command; if this the case, you would either need to obtain the edit.com file to access this file or use the copy con command.
Microsoft Windows and other users
A Windows user can still use the above MS-DOS steps if they wish to create a batch file. If, however, you're more comfortable using Microsoft Windows or your operating system, you can use any text editor, such as Notepad or Wordpad, to create your batch files, as long as the file extension ends with .bat. In the below example we use the Windows notepad to create a batch file.
  1. Click Start
  2. Click Run
  3. Type: notepad and press enter.
  4. Once notepad is open, type the below lines in the file or copy and paste the below lines into notepad.

    @echo off
    echo Hello this a test batch file
    pause
    dir c:\windows
  5. Click File and click Save; browse to where you want to save the file. For the file name, type "test.bat", and if your version of Windows has a "Save as type" option, choose "All files", otherwise it will save as a text file. Once all of this has been done click the Save button and exit notepad.
  6. Now, to run the batch file, double-click or run the file like any other program. Once the batch file has completed running it will close the window automatically.
Batch commands
Just like all MS-DOS commands, all batch file commands are not case sensitive. However, in the below listing we have listed all commands in all caps to help you identify what is a command and what is not.
@
Does not echo back the text after the at symbol. This most often used as @ECHO OFF to prevent any of the commands in the batch file from being displayed, just the information needed.
%1
The percent followed by a numeric value, beginning with one, allows users to add variables within a batch file. The below line is an example of what can be used in a batch file.
ECHO Hello %1
When the above one-line batch file is created, add your name after the batch file. For example, typing myname (being the name of the bat file) and then your name:
myname bob
would output:
Hello bob
Note: This can be extended to %2, %3, and so on.
::
One of two ways of adding remarks into the batch file without displaying or executing that line when the batch file is run. Unlike REM this line will not show regardless if ECHO off is in the batch file.
:LABEL
By adding a colon in front of a word, such as LABEL, you create a category, more commonly known as a label. This allows you to skip to certain sections of a batch file such as the end of the batch file. Also see GOTO.
CALL
This used to run another batch file within a batch file. When the batch file that is called is completed, the remainder of the original batch file is completed. Note if the batch file does not exist it will give an error message.
CHOICE
See running different programs for an example of how to use this command.
  • Additional information and the syntax of this command in each version of Windows and MS-DOS can be found on our CHOICE command page.
CLS
Just like the DOS command would clear your screen.
  • Additional information and the syntax of this command in each version of Windows and MS-DOS can be found on our CLS command page.
ECHO
Will echo a message in the batch file. Such as ECHO Hello World will print Hello World on the screen when executed. However, without @ECHO OFF at the beginning of the batch file you'll also get "ECHO Hello World" and "Hello World." Finally, if you'd just like to create a blank line, type ECHO. adding the period at the end creates an empty line.
EXIT
Exits out of the DOS window if the batch file is running from Windows.
  • Additional information and the syntax of this command in each version of Windows and MS-DOS can be found on our EXIT command page.
GOTO LABEL
Used to go to a certain label, such as LABEL. An example of GOTO would be to GOTO END. For an example of this see running different programs.
  • Additional information and the syntax of this command in each version of Windows and MS-DOS can be found on our GOTO command page.
IF
Used to check for a certain condition if the condition exists. If that condition exists it will perform that function. To see an example of this see running different programs.
  • Additional information and the syntax of this command in each version of Windows and MS-DOS can be found on our IF command page.
PAUSE
Prompt the user to press any key to continue.
REM
One of two ways of adding remarks into the batch file without displaying or executing that line when the batch file is run.
SHIFT
Changes the position of replaceable parameters in a batch program.
START
Used for Windows 95, Windows 98, and Windows NT 4.0 and above to start a windows application; such as START C:\WINDOW\CALC would run the Windows Calculator. Users running Windows 3.x need to utilize the WIN command.  For example, WIN C:\Windows\CALC.EXE would run Windows and then Calculator after Windows has finished loading. 
Batch file examples
Running different programs
Below is an example of how you can implement the choice options into your batch files. Each line that is in red can be left out of the batch file. They have been included to help explain some of what the batch file means. Windows 2000 and Windows XP users will need to substitute the choice command with the set command; see the set command page for additional help and information with this command.
@ECHO OFF
REM - LABEL INDICATING THE BEGINNING OF THE DOCUMENT.
:BEGIN
CLS
REM - THE BELOW LINE GIVES THE USER 3 CHOICES (DEFINED AFTER /C:)
CHOICE /N /C:123 /M "PICK A NUMBER (1, 2, or 3)"%1
REM - THE NEXT THREE LINES ARE DIRECTING USER DEPENDING UPON INPUT
IF ERRORLEVEL ==3 GOTO THREE
IF ERRORLEVEL ==2 GOTO TWO
IF ERRORLEVEL ==1 GOTO ONE
GOTO END
:THREE
ECHO YOU HAVE PRESSED THREE
GOTO END
:TWO
ECHO YOU HAVE PRESSED TWO
GOTO END
:ONE
ECHO YOU HAVE PRESSED ONE
:END
How to start Windows files and other programs from a batch file
To run Microsoft Windows programs or files use the START command. The below example would run Windows Notepad.
START /MAX NOTEPAD
You can also specify the direct location of the file by typing the below command.
START /MAX C:\Windows\NOTEPAD.EXE
*Windows users who have a different directory (e.g. Windows 2000 users) would need to substitute WINNT or the name of their directory in place of Windows in the above example.
The /m representing it to start the window Maximized. See the start command page for additional information about this command.
Creating a batch file delay
Below is an example of how to delay a batch file any where from 5 to 99 seconds. In the below example we illustrate a 5 second delay.
Type NUL | CHOICE.COM /N /CY /TY,5 >NUL
Additionally, you could use the sleep file found on our utility download section.
How to make a time log in a batch file
The below example demonstrates how to create a time log of when the batch file is loaded, or for example, this could be used in the autoexec.bat when someone logs into a computer that supports this file.
ECHO. |TIME > TIME
COPY LOG +TIME
An alternate, slightly more complicated method that, to our knowledge, cannot be used in Windows NT, Windows 2000 or Windows ME would be the following:
echo @prompt set date=$d$_set time=$t$h$h$h > {a}.bat
%comspec% /e:2048 /c {a}.bat > {b}.bat
for %%v in ({b}.bat del) do call %%v {?}.bat
echo %date% %time% >> log
Another alternative is:
echo. |time |find "current" >> log
For the above batch file to work properly you must create a file called log, by typing edit log and then save and exit the file, creating a 0 bytes file. If this file is not created or not created properly you will receive the error message Content of destination lost before copy.
This post is copy pasted from http://www.computerhope.com/batch.htm to maintain as repository of knowledge.