Home > Articles > Programming > Java

Like this article? We recommend

Like this article? We recommend

How Plentiful Is Memory?

You might say: "Memory is always plentiful. It's not as precious as it was in the 1990s." This might be true for desktop machines, but I would argue that it's not true because resources are always limited. However, it's definitely not true for resource-constrained mobile computing devices.

Rule #1: Never assume resources are abundantly available—they aren't and never will be.

As the Web evolves from a static page delivery model to a more natural event-based operation, programmers are tasked with squeezing more and more code into smaller devices. These issues are only beginning to be considered for technologies such as Ajax. So, the safest bet is to assume that you'll always be restricted in memory use.

Java Privacy Leaks

What about other types of Java leaks, though?

A much more serious type of leakage occurs when privacy leaks out of code. This is surprisingly easy to do. Listing 2 illustrates a simple staff management system that contains a class called HRAdmin for employees and their associated details.

Listing 2 A Staff Record Management System

public class HRAdmin
{
public static void main(String[] args)
{
HRStaffDetails staffDetails = new HRStaffDetails();
// Let’s create a member of staff
PermanentStaff staffMember =
 new PermanentStaff("Bill Gates",
           new Salary("50000"));
staffDetails.addPermanentStaff(staffMember);
System.out.println(staffDetails.toString());
}
}

Listing 2 illustrates the instantiation of the HRStaffDetails class. New staff is added to this object as people join the company. Also, staff records are removed as people leave the company.

Another use for this program would be to maintain staff records. Clearly, a real system would allow many more details to be stored: home address, previous employer, and so on. You get the idea!

Figure 1 illustrates the program output. As you can see, the company contains just one staff member.

Figure 1

Figure 1 HR admin program output.

Private Data—Salary

While the data in the staff records system is private, the salary item is especially so. For this reason, you don't want client programs to be able to modify salary details in an unauthorized fashion. Imagine if employees were able to view and modify their salaries! Listing 3 illustrates the method from the Salary class that provides salary details.

Listing 4 A Privacy Leak

public Salary getSalary()
{
return new Salary(salary.getSalary());
}
Listing 3 Accessing private data
You might be tempted to use the following code in Listing 4 in place of that in Listing 3:

public Salary getSalary()
{
return salary;
}

The code in Listing 4 will compile and run just fine. It will produce output identical to that in Figure 1. So, why is the code in Listing 4 so bad? If you think about it, any code that calls the method in Listing 4 will now have direct access to the private salary object. Such code could be part of a client running in another country. Once this client has access to the private data, the code has suffered a privacy leak.

On the other hand, when you use the code in Listing 3, a new object is instantiated and passed to the client. The client can make merry with this object (by changing the salary amount), and this will have no effect on the salary object in the main class.

A Deliberate Error—Separation of Concerns

Notice the last line in Figure 1. It intentionally has an error. Any idea why the word Salary is repeated? It's simple enough, and involves the area commonly called separation of concerns. Let's have a look at this because if you use the principle of separation of concerns, you will generally produce safer code.

Each class you define and use has a set of capabilities. In the case of Listing 2, the class HRStaffDetails instantiated by HRAdmin serves as a container for staff member records. So, I can create new staff records and add them to the administration system. Likewise, I can modify these records and also remove them if required. Given this, the major concerns of the class HRStaffDetails are:

  • Staff record creation
  • Staff record storage
  • Staff record modification
  • Staff record retrieval and listing
  • Staff record deletion

The fourth item in this list is the location of the error (the duplicate word Salary at the bottom of Figure 1). Each class that is subordinate to class HRStaffDetails provides a standard Java method called toString(). The main class (HRStaffDetails) also implements this method. Listing 5 illustrates the toString() method for HRStaffDetails.

Listing 5 The toString() Method

public String toString()
{
String newline = System.getProperty("line.separator");
StringBuffer buf = new StringBuffer();
buf.append("Permanent Staff: ").append(newline);
for(int i = 0; i < permanentFolks.size(); i++)
{
buf.append(permanentFolks.elementAt(i)).append(newline);
}
return buf.toString();
}

The Listing 5 method just calls into the toString() method of the contained objects, which are instances of the vector permanentFolks. So, there’s no problem here because there’s no mention of Salary in Listing 5. Let's now look at Listing 6 to see the toString() method for the elements contained within the permanentFolks vector.

Listing 6 The PermanentStaff toString() Method

public String toString()
{
return "PermanentStaff: Name = " + personName +
  System.getProperty("line.separator") +
  "Salary = " + salary + ". " +
  System.getProperty("line.separator");
}

In Listing 6, notice the mention of the word Salary. As you can see, an instance of a Salary object is used in this line. Now look at Listing 7: the toString() method for the Salary class.

Listing 7 The Final Destination in the toString() Chain

public String toString()
{
  return "Salary = " + getSalary();
}

And there you see the second mention of the word Salary. So, there's no need for the code in Listing 6 to include the word Salary. The Salary class handles this task. In other words, there is a separation of concerns—all salary-related tasks should be left to the Salary class.

Rule #2, described next, might help you to remember how to employ the separation of concerns.

Rule #2: In order to respect separation of concerns, make sure your classes mind their own business!

If you think you need some capability in a given member function, check that some other class isn't already doing it.

Safer Java Data Structures

Remember my tale from the 1990s about exceeding the boundary of an array? Here's a scheme that avoids this problem altogether and that can be extended for any programming language.

Imagine you have another simple HR staff list application that stores employee details. I've placed the names of the staff members in an enum in Listing 8. Given the staff members listed, it's an interesting company, maybe some kind of a consultancy!

Listing 8 Employee Management System

import java.util.Scanner;
public class EnumValuesDemo
{
enum EmployeeList {PLACE_HOLDER,
          BILL_GATES,
          GEORGE_BUSH,
          WARREN_BUFFET,
          TONY_BLAIR,
          CARLY_FIORINA,
          NEXT_EMPLOYEE};

public static void main(String[] args)
{
// Create a human resources staff list object using the enum
EmployeeList[] staffList = EmployeeList.values();
for (int i = EmployeeList.PLACE_HOLDER.ordinal() + 1;
    i < EmployeeList.NEXT_EMPLOYEE.ordinal(); i++)
{
System.out.println("Staff name " + staffList[i]);
}
}
}

After the enum, my main() method instantiates an array of EmployeeList objects; this is a really handy feature of the enum type. I now have an array that includes a string for each member of the enum. If you think about this, the code has defined an enum, but pretty much for free I get an array of the enum elements. And these two entities are inextricably interwoven. As you'll see, this provides scope for safer code.

Remember that I want to avoid overstepping the boundary of an array of staff member names. While this can be done fairly easily in Java using the length method, I want to try to impose some of the data semantics on the code. This is the purpose of the two enum elements, PLACE_HOLDER and NEXT_EMPLOYEE.

The PLACE_HOLDER element marks the beginning of the enum type. This element is never used to define an employee. The first employee is defined in the next element following PLACE_HOLDER. The NEXT_EMPLOYEE.element is used to mark the position where you add a new employee element in the enum.

Figure 2 illustrates the elements of the staff list array displayed using the following line:

EmployeeList.PLACE_HOLDER.ordinal()
Figure 2

Figure 2 Staff listing.

The for loop in Listing 8 uses as limits the start and end elements of the enum (PLACE_HOLDER and NEXT_EMPLOYEE). This means that the array can have as many elements as are defined in the enum—tens, hundred, thousands, and more.

Let's now assume that it's a fairly frequent occurrence for new people to join and existing staff members to leave our little company. Imagine if the enum member TONY_BLAIR left the company. The employee list in Listing 8 would have to be updated to match that shown in Listing 9.

Listing 9 Modified Employee List

enum EmployeeList {PLACE_HOLDER,
          BILL_GATES,
          GEORGE_BUSH,
          WARREN_BUFFET,
          CARLY_FIORINA,
          NEXT_EMPLOYEE};

Then, when I rerun the for loop, Figure 3 illustrates the new program output.

Figure 3

Figure 3 Updated staff listing.

So, only a data change was required. No real programming effort. It wasn't necessary to dig into the code to modify the for loop. Indeed, if the names were read in from a database instead of being hardcoded, there would be no programming effort at all.

Because the data semantics drive the code, there is a much-reduced chance of exceeding the boundary of the array. This means that if you code carefully, you don't need to worry about an exception occurring. This in turn reduces the size of your code and to some extent improves its performance.

Running the Supplied Java Code

To run the code, download it from here, and unzip it into any old folder. Next, open a DOS console and change the directory to where the unzipped code files reside. Run the command javac *.java in each of these folders: Safer data, Memory Leak, and Other Leaks. To run the code, just type java followed by the name of the class file that contains the main() method.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020