24
Wed, Apr
0 New Articles

Open Source Starter Guide for IBM i Developers: i Object!

Web Languages
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

We’re all familiar with the concept of an object-based operating system like IBM i, but an object-oriented (OO) programming language is foreign to some. 

By Pete Helgren

Editor's Note: This article is excerpted from chapter 5 of Open Source Starter Guide for IBM i Developers, by Pete Helgren.

Oh, you might have tripped across it in some generic computer science class, but perhaps it was too long ago or you were groggy enough in class that that particular chapter has been forgotten. If so, we are going to take a very brief trip down the orientation road (don’t worry, we aren’t talking about that kind of orientation).

It’s probably been a while since you played with Play-Doh unless you have kids or grandkids. Remember how you’d take a chunk of that stuff, flatten it, take a cookie cutter or some kind of mold, and stamp out a Play-Doh object? If so, you were dealing with an OO metaphor. Sure, you could work that stuff with your hands and try to make a flat tree, or person, or dog “freestyle,” but being able to grab a mold and stamp out an object shaped like a tree, person, or dog made it that much easier and consistent. Well, in OO programming, that’s just what we want to do: crank out consistent objects easily and quickly without cranking out unstable code (or, in some cases, we create consistently unstable code!).

Objects typically have these characteristics:

  1. Contain data (sometimes called fields)
    1. Class variables
    2. Instance variables
  2. Contain code (called methods or procedures)
    1. Class methods
    2. Instances

The astute reader would recognize that if there are class things and instance things (aka instantiation), then there must be some connection between the two. Right you are! Objects typically rely on a property called inheritance. Before you get excited about collecting on your inheritance, what we mean in the case of objects is that instances of the class inherit the characteristics of the class, a copy in other words. So unless you want a copy of your aunt’s money, inheritance in an object world won’t be fungible. It’ll get you just a few years in an orange jumpsuit for counterfeiting. The class becomes a “cookie cutter” to stamp out similarly shaped objects.

My first foray into the OO programming world was SmallTalk. I don’t know why I chose SmallTalk except it sounded cool, and the quick overviews I read made it sound drop-dead simple to use. Instead of simple, I thought I was experiencing some ’70s-style flashbacks with mind-bending concepts like polymorphism (illegal in Texas), encapsulation, reflection, abstraction, constructors, and on and on. Everything in SmallTalk was an object. Everything! I immediately wrote a couple of RPG programs just to restore my sanity. But the light bulb had turned on, and although I could have turned to LISP (the granddaddy of OO programming), or Python, or C++, or Ruby, I turned instead to Java. I had the good fortune of taking a beginning Java programming class with an instructor who was not only an excellent Java programmer, but someone who could also communicate in real English that I could understand. So here, as I can best describe them, are the necessary basics as I see them.

Classes

These are representations of (usually) real-life objects. Take a bank account, for example. It would typically have an account number, a balance, and some methods for adding money to and removing money from the account. So we could create one of these things, and typically when you create a bank account, you are issued a number and a beginning balance.

Account (class)

variable: Account Number

variable: balance

constructor: Account number, beginning balance

method: deposit (money)

method: withdraw (money)

method: display balance (money)

We are working with pseudo-code at this point, so the basic description of this class is that it has two properties (data fields). One contains the account number, and one contains the current balance. It also has four methods:

  • A constructor—This takes an account number and a beginning balance as A constructor is a “built-in” method that most objects will have. Basically, it allows for certain values to be passed in and may even trigger other methods during the creation of an instance of the class. You determine what the constructor may do when an instance is created. It may do nothing.
  • Deposit—This method adds money to the
  • Withdraw—This method removes money from the
  • Display balance—This method simply outputs the balance for

These types of transactions would be common to any instance of the class Account. When you create a new account for Pete, you might do it by passing in 1234 as the account number and $5 as the beginning balance in the constructor of the new account. If you were to invoke the display balance method on the Pete account, it would return $5.00.

Encapsulation

There are a couple of things to learn about classes. First is encapsulation. As you create a class definition, you try to encapsulate the functional pieces into methods rather than update data values directly. Sure, you might be able to update the account balance by just adding the money directly to the balance (balance = balance + money), but for many reasons that I won’t go into, it is better to create a method that encapsulates the logic. So yes, when you invoke the “deposit” method in your Account object, the code may well work (balance = balance + money), but you are indirectly accessing the balance rather than directly updating it. Yes, you could walk into the bank, open your wallet, take out the cash, and then have a guard accompany you to the accountant, who would make a note of the amount and then walk outside, take the armored car to the Federal Reserve bank, and stuff it into the giant bank vault directly. Or you could just make a deposit and let the internals of the system handle the rest.

The second thing, of course, is that you created an instance of the original class rather than using the class directly. Certainly, if you wanted to, you could create a brand-new class and store everything in it, but since you’ll create millions of these things, why not do that with an Account (new!) command?

Inheritance

So, with encapsulation and instantiation through creating an instance taken care of (more or less), what about inheritance? Inheritance is really a process of saying that you have a model that’s close, but it’s not exactly what you want. In fact, you have several of these “oh so close!” models that are similar to one another but different from the original model. This is where subclassing comes into play. Subclassing means taking an original class and then extending it to include other characteristics.

For example, if you need a credit type of account, it certainly would have an account number and a balance, but it also might have a service charge data field and an interest data field. Since you already have an account with everything you need with the exception of service charges and interest rates, you could say something like: Credit Account is an extension of Account. Inherit everything that Account class has, but add:

variable: Service charge

variable: Interest rate

method: Add service charge

method: calculate interest

So your class for Credit Account would have this if you could examine it:

variable: Account Number

variable: balance

variable: Service charge

variable: Interest rate

constructor: Account number, beginning balance

method: deposit (money)

method: withdraw (money)

method: display balance (money)

method: Add service charge

method: calculate interest

Java uses extend: class CreditAccount extends Account. Ruby uses the < operator: class CreditAccount > Account. Python uses parentheses to denote the base class: class CreditAccount(Account). Get the picture? One class based on another.

Interfaces

With inheritance, you can subclass only one class. But what if you had more than one “template” class that you wanted to inherit? You could create a template that is “less” than a class in that it has no functional methods but basically says you must have this function and that function and this function without really defining what the function must do. Then the class would “implement” those functions with specific code.

Going back to our Account example: you might require that any Account created have an account number as a string value and also have a “deposit” method for getting money into the account, but exactly how the deposit is made is left up to the programmer to determine. But you do require that the Account class implements the needed methods. This type of class is typically called an “interface” in that it provides only the barest description of what is needed and leaves the implementation details up to the programmer.

That leads us to the last concept I want to tepidly step into ...

Polymorphism

At the easiest-to-understand level, you can reflect on what adding a “print” method might mean in a few different contexts. Your print() method in an analog world might trigger a line-by-line text output in one environment; a glossy, color page in another environment; a 3D image in another environment; and a Web page in yet another environment. The print() method is polymorphic, outputting completely different things with completely different programming yet invoked with the same call.

Classes can be polymorphic as well. The point is that the class/object/method is manipulated in different ways even though the original call or reference looks nearly identical. That is a very simplistic and incomplete description of polymorphism. Even if you don’t understand it, no doubt you’ll use it without thinking about it at some point in OO programming.

Have Some Class

Finally ...

As we go through each chapter, I’ll attempt to point out which of the concepts above we might be dealing with. I say might because there are some cases where it just isn’t 100 percent clear what concept is being applied.

Generally, seeing this stuff in action is more helpful than just talking about it, and if I were writing about only one language, then I could give you comprehensive examples in that language. But since I am writing a multilingual book, I’ll give examples in upcoming chapters.

Well, the programming context is multilingual; I can speak and write only English, with the exception of una cerveza por favor or Ein bier bitte or HIq qIj vItlhutlh vIneHor (Klingon).

Want to learn more?  You can pick up Peter Helgren's book, Open Source Starter Guide for IBM i Developers at the MC Press Bookstore Today! 

Peter Helgren

Peter Helgren is programmer/team lead at Bible Study Fellowship International. Pete is an experienced programmer in the ILE RPG, PHP, Java, Ruby/Rails, C++, and C# languages with more than 25 years of system 3X/AS400/iSeries/IBM i experience. He holds certifications as a GIAC certified Secure Software Programmer-Java and as an MCSE. He is currently executive vice president on the COMMON Board of Directors and is active on several COMMON committees. His passion has always been in system integration, and he focuses on open-source applications and integration activities on IBM i. Pete is a speaker/trainer in RPG modernization, open-source integration, mobile application development, Java programming, and PHP and actively blogs at petesworkshop.com.


MC Press books written by Peter Helgren available now on the MC Press Bookstore.

Open Source Starter Guide for IBM i Developers Open Source Starter Guide for IBM i Developers
Check out this practical introduction to open-source development options, including XMLSERVICE, Ruby/Rails, PHP, Python, Node.js, and Apache Tomcat.
List Price $59.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: