Click here to close now.


Microsoft Cloud Authors: Jayaram Krishnaswamy, Elizabeth White, Andreas Grabner, Jim Kaskade, Pat Romanski

Related Topics: PowerBuilder, Microsoft Cloud

PowerBuilder: Article

Elegant Programming | Part 4

Private and public affairs

Law of Demeter (or Principle of Least Knowledge)
A given object should assume as little as possible about the structure or properties of anything else (including its subcomponents).

In simpler words: if you want to get data from an object, referenced by a variable, then use a public function declared in the referenced object itself, but not variables and functions of its nested object(s).

The law is dictated by real life. Imagine you are paying in a store, and the cashier asks you to give your credit card. You take your wallet from your pocket, take the card from the wallet and hand it to the cashier. Nothing strange or unusual. Let's describe this situation in a programming language:

lnv_credit_card = lnv_buyer.uf_get_credit_card()

But imagine a slightly different situation: instead of asking for your card, the cashier silently takes your wallet from your pocket and takes the card from the wallet:

lnv_credit_card = lnv_buyer.uf_get_jacket().uf_get_upper_left_pocket() .uf_get_wallet().uf_get_mastercard()

In both cases there is the same result - the cashier will have your credit card. But there is a huge difference if we are talking about possible dangers. In the first case, the buyer is responsible for his credit card - he knows in which pocket the wallet is and which credit card should be used (if there are more than one). If next time the buyer decides to put the wallet in other pocket, or use different credit card - it's his/her private affair; in programming terms: if the credit card's storing method in the "buyer" class has changed, it's enough to change only GetCreditCard() function's code, and all the calls to that function all over the application will continue to work. The calling objects don't have to know anything about jackets, pockets and other details - they have enough of their own problems and should not be responsible for the private affairs of others (do you want a cashier, an unknown person, to be responsible for your credit cards?).

This issue doesn't exist if data is properly encapsulated, but PowerBuilder has problems in this area: while instance variables can be declared as private or protected, data in DataWindows is always public, so it's enough to have a pointer to a window to access its DWs (w_XXX.tab_XXX.tabpage_XXX.dw_XXX.object.field_XXX[1]).

If a function of a class will be accessed only from inside the class, declare that function as private (if also from descendants then as protected).

If you do so, then developers using the class will immediately see its "outer world" interface; may be, they only want to learn how to use the class as a "black box" - in that case the implementation details (like private functions) are not needed. If a function, which is practically used privately, is mistakenly declared as public, then the class consumers can think they can (or even should) use it to work with the class. And the opposite, if a developer is working on the class (changing or increasing its functionality), then he/she cannot be 100% sure that a public function is not called from somewhere outside, and is forced to apply the global search if that function's logic or signature must be changed.

Instance Variables
Avoid public instance variables.

Create them only "private" (or "protected" if you are planning to have the class be extended and the descendants have a need to access the variable directly). The purpose of instance variables is to keep internal information of the object, so the outer world (other classes) should access this information only using public functions, i.e., in a controllable way.

Change default access level of class members
Don't leave instance variables and functions public as they are created by default - change the access level to reflect their practical use.

Remember, that PowerBuilder's instance variables and functions are public by default. A method's access can be changed to "private" or "protected" using the dropdown in the declaration section, and instance vars must be "privatized" by adding the "private" or protected" keyword before each var, or the same keyword with a semicolon before a group of vars. Pay attention - if no scope identifier is mentioned explicitly then the vars are public (in contrast to C#, where "no scope identifier" means "private"). IMHO, it was a bad solution of PB authors (everything should be private by default and be changed only if the need arises), but that's what we have... So, when you are creating a new instance variable or a function, and your brain is busy thinking about the functionality being developed, don't forget to change the access level to what it should be.

Why is this advice important? We can see many PB applications with all functions public, and nothing bad is happening... I would say, it's not too important in the development stage, but when the maintenance time comes... Let's say, I have to add and even change the functionality of an existing object. If the stuff I am touching is private, then I know that my changes will not cause straightforward damage in other (sometimes unexpected) parts of the application. For example, I can change the number of parameters or even the name of a private function without having a chance to do any harm to other objects. But if the function is declared as public, I need to perform the Global Application Search (which is extremely slow in PowerBuilder, especially in serious apps) to make sure the function is not called outside the object (and if it is called then, may be, to change the technical solution).

Intriguing World of Logic
Positive wording in Boolean names

Give Boolean variables and functions positive names. Avoid both - direct negation and words that carry a hint of negativity.

Think positively :-) That will simplify the reading and understanding of Boolean expressions, especially if they are nested. As an example, you can see the expressions "if not lb_not_printed" and "if lb_printed": they are logically equivalent, but the positive version is easier to understand. As you can see, the difference appears even when the expressions are standalone, but imagine if they were a part of a complex Boolean expression. You can contradict: and what if the calling code wants to ask if the document has not been printed yet? Whether "if not lb_printed" is better "if not lb_not_printed"? Okay, there is always a chance that our Boolean var or function will be used with NOT, but using the positive wording will cause maximum ONE negation in that situation, while using negative wording can result in TWO of them - "negation of negation." Table 1 contains a few examples of "negative" and "positive" words:












ok (succeeded)

Table 1

But please remember, this advice is only about Boolean names. If your non-Boolean function performs a negative action, its name must reflect exactly that action, for example:

uf_disable_save_button, uf_prohibit_print, uf_exclude_expired_records.

Positive logic in Boolean expressions
Comparing values, try to use "=" instead of "<>".

*** BAD code: ***

if ls_order_status <> n_order_status.CLOSED) then
[actions for orders which are not closed]
[actions for closed orders]
end if

*** GOOD code: ***

if ls_order_status = n_order_status.CLOSED) then
[actions for closed orders]
[actions for orders which are not closed]
end if

This advice is especially important if the value comparison is nested into a Boolean expression:

*** BAD code: ***

if ls_order_status <> n_order_status.CLOSED or &
ls_state <> n_state.MONTANA or &
ls_day_type <> n_day_type.WEEKEND then
[actions if: order is not closed OR state differs from Montana OR day is not a weekend]
[actions for other cases]
end if

*** GOOD code: ***

if ls_order_status = n_order_status.CLOSED and &
ls_state = n_state.MONTANA and &
ls_day_type = n_day_type.WEEKEND then
[actions if: order is closed AND state is Montana AND day is a weekend]
[actions for other cases]
end if

Use CHOOSE CASE to compare one value with many
Comparing one value with many other values, use the "choose case" construction instead of multiple "or" operators, so the compared value will be mentioned in the code only once.

In this situation, we are not really choosing between cases (so we can call it "a fake choose case"), but why not make our code more readable if the programming language doesn't allow the IN clause like T-SQL and PL/SQL do?

*** BAD code: ***

if ls_city = "Toronto" or ls_city = "Boston" or ls_city = "Chicago" then
ls_message = "Nice city!"
end if

*** GOOD code: ***

choose case ls_city
case "Toronto", "Boston", "Chicago"
ls_message = "Nice city!"
end choose

Use CHOOSE CASE TRUE for independent Boolean expressions
Use one compact "choose case true" block to "pack" a series of evaluated Boolean expressions even if they are NOT related to each other. So, instead of:

if not IsValid(ads) then
ls_err = "Passed datastore is not valid"
end if

if ls_err = "" and IsNull(al_row) then
ls_err = "Passed row must not be null"
end if

if ls_err = "" and al_row < 1 then
ls_err = "Passed row must be greater than 0"
end if


choose case true
case not IsValid(ads)
ls_err = "Passed datastore is not valid"
case IsNull(al_row)
ls_err = "Passed row must not be null"
case al_row < 1
ls_err = "Passed row must be greater than 0"
end choose

Short conditions in IFs
Don't write complicated expressions inside of if statements (just after the if); instead, store the expression's result in a Boolean variable with a quality, descriptive name and use that variable in the if statement.

That will make the logic being implemented extremely easy to understand.

*** BAD code: ***

if (ls_calc_method = n_calc_method.ADDITIVE and lb_additive_calculation_passed) or &
(ls_calc_method = n_calc_method.RATIO and lb_ratio_calculation_passed) then...

*** GOOD code: ***

boolean lb_structural_change_occurred

lb_structural_change_occurred = &
(ls_calc_method = n_calc_method.ADDITIVE and lb_additive_calculation_passed) or &
(ls_calc_method = n_calc_method.RATIO and lb_ratio_calculation_passed)

if lb_structural_change_occurred then...

As you see, the bad code tells us only when the condition is true, but the good code tells us both when and why!!! It is so important that I easily go against the rule to decrease scripts size - I don't try to keep my scripts short, sometimes I prefer to add lines if that makes the code more understandable or looking less like a heap of rubbish. And, of course, don't forget that the expression in my example is pretty small because it's enough to convey the idea; in real life I have seen statements with half-a-screen Boolean expressions inside an "if". If the logic is complicated, don't populate the Boolean variable in one assignment statement (as described earlier) but come to the truth step-by-step using a number of simple Boolean expressions instead of one monstrous construction. Please see the next example of populating a variable step-by-step instead of inserting everything in the if statement:

boolean lb_the_show_must_go_on

lb_the_show_must_go_on = false
choose case true
case [cond1], [cond2]
lb_the_show_must_go_on = true
case [cond3] and [cond4]
lb_the_show_must_go_on = this.uf_xxx()
case [cond3]
lb_the_show_must_go_on = this.uf_yyy()
end choose

if lb_the_show_must_go_on then...

Don't duplicate conditions in Boolean expressions
Don't add conditions to a Boolean expression that don't change the final result, produced by the expression.

Foolish advice, you say? Why add them? But this advice was learned during my code inspection practice. Look at the following nice examples:

  • if (not IsNull(ld_expire_date)) and ld_expire_date < ld_today then

is logically the same as:

if ld_expire_date < ld_today then

because when ld_expire_date contains null then the second part of the expression will produce null, and nulls are interpreted by code branching operators as false.

  • if dw_xxx.RowCount() > 0 and dw_xxx.GetSelectedRow(0) > 0 then

must be re-written as;

if dw_xxx.GetSelectedRow(0) > 0 then

because when dw_xxx contains no rows, dw_xxx.GetSelectedRow(0) will never return a positive number.

  • if (not IsNull(ids_xxx)) and IsValid(ids_xxx) then

is the same as:

if IsValid(ids_xxx) then

because if IsValid returns true (i.e., memory is allocated for the pointed object) then, of course, the variable is pointing something (i.e., is populated), so testing it with IsNull will produce true.

if ll_row_count > 0 then
for ll_row = 1 to ll_row_count
end if

will work exactly in the same way as simply:

for ll_row = 1 to ll_row_count

Boolean functions
If a function returns Boolean then its name should convey the meaning of the returned value to make the business logic in the calling scripts easily understandable. Calling that function as an "if" statement's condition must produce a correct real-English sentence.

Here are some examples of well-named Boolean functions:

uf_row_is_validated, uf_orders_are_ok, uf_file_name_already_exists.

A strange tradition dictates to put the words "is"/"are"/"does"/"do" in the beginning (like uf_is_row_validated, uf_are_orders_ok etc.), but I personally don't like that approach because it produces incorrect English: we say "if row is validated then do something," not "if is row validated...". Of course, it's not an issue of high importance - you can even omit "is"/"are" at all, and the names will still be fine:

uf_row_validated, uf_orders_ok.

Never use verbs in imperatives to name Boolean functions. For example, the following names are absolutely unacceptable for functions returning Boolean:


We don't say "if validate row then save," "if check orders then print."

Sometimes it makes sense to return Boolean from the function as an OUTPUT argument instead of the return value. Once I found this line of existing code:

if uf_display_comments_window() then...

Any idea what the meaning of the Boolean value the function returns? I opened the function code and saw that it returned true if the user clicked the OK button in the comments window, opened in the function, and false if he/she clicked CANCEL. As you can see, the function uf_display_comments_window() cannot be renamed to uf_user_cicked_ok_in_comments_window() because its main purpose is to display the comments window (not to report the fact of button clicking), so the best solution in that situation is to use a REF argument - that will force (!!!) developers to create a variable, pass it to the function and use beautifully in the "if" construction:

boolean lb_user_cicked_ok
uf_display_comments_window(ref lb_user_cicked_ok)
if lb_user_cicked_ok then...

Populating Boolean variables
If it's possible, populate Boolean variables with results of Boolean expressions instead of directly assigning true and false.

*** BAD code: ***

if ll_rows_retrieved > 1 then
lb_multi_rows_mode = true
lb_multi_rows_mode = false
end if

*** GOOD code: ***

lb_multi_rows_mode = (ll_rows_retrieved > 1)

Don't return null from Boolean functions
Boolean functions must always return true or false (but not null). Think defensively if the function fails to return the asked value.

You cannot be sure if the calling script (which must make a code branching decision) will check the returned result for null. In fact, usually there is no such check, especially when the function is directly put inside an if construction. There is a high probability that a null, returned by a Boolean function, will be treated as false - it's acceptable in most cases, but not always. What do we have to return if the function cannot answer the asked question? In this situation, think in a pessimistic way. If the function checks an eligibility, return a value, saying "the entity is not eligible for what you asked". For example, if the function uf_customer_can_get_discount() failed to connect to the database, it should return false, but the function uf_passenger_must_be_double_checked_by_security should return true in that situation - simply use common sense trying to prevent the bad. But the best way to treat technical failures is to throw an exception.

De Morgan's Laws
Simplify Boolean expressions using De Morgan's Laws.

To ensure that logical statements are expressed simply, use the De Morgan's Laws:

(NOT P) OR (NOT Q) can be expressed shorter as NOT (P AND Q)

(NOT P) AND (NOT Q) can be expressed shorter as NOT (P OR Q)

In that situation, use the NOT operator only once, as shown below.

Example 1 (AND becomes OR):

lb_is_gas = (not lb_is_liquid) and (not lb_is_solid) and (not lb_is_plasma)

should be simplified as:

lb_is_gas = not (lb_is_liquid or lb_is_solid or lb_is_plasma)

Example 2 (OR becomes AND):

(To go to a restaurant, 2 conditions must be satisfied: "we are hungry" AND "restaurants are open now").

lb_we_will_stay_home = (not lb_we_are_hungry) or (not lb_restaurants_are_open_now)

should be simplified as:

lb_we_will_stay_home = not (lb_we_are_hungry and lb_restaurants_are_open_now)

More Stories By Michael Zuskin

Michael Zuskin is a certified software professional with sophisticated programming skills and experience in Enterprise Software Development.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

@ThingsExpo Stories
The broad selection of hardware, the rapid evolution of operating systems and the time-to-market for mobile apps has been so rapid that new challenges for developers and engineers arise every day. Security, testing, hosting, and other metrics have to be considered through the process. In his session at Big Data Expo, Walter Maguire, Chief Field Technologist, HP Big Data Group, at Hewlett-Packard, will discuss the challenges faced by developers and a composite Big Data applications builder, focusing on how to help solve the problems that developers are continuously battling.
Nowadays, a large number of sensors and devices are connected to the network. Leading-edge IoT technologies integrate various types of sensor data to create a new value for several business decision scenarios. The transparent cloud is a model of a new IoT emergence service platform. Many service providers store and access various types of sensor data in order to create and find out new business values by integrating such data.
NHK, Japan Broadcasting will feature upcoming @ThingsExpo Silicon Valley in a special IoT documentary which will be filmed on the expo floor November 3 to 5, 2015 in Santa Clara. NHK is the sole public TV network in Japan equivalent to BBC in UK and the largest in Asia with many award winning science and technology programs. Japanese TV is producing a documentary about IoT and Smart technology covering @ThingsExpo Silicon Valley. The program will be aired during the highest viewership season of the year that it will have a high impact in the industry through this documentary in Japan. The film...
SYS-CON Events announced today that Luxoft Holding, Inc., a leading provider of software development services and innovative IT solutions, has been named “Bronze Sponsor” of SYS-CON's @ThingsExpo, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. Luxoft’s software development services consist of core and mission-critical custom software development and support, product engineering and testing, and technology consulting.
Developing software for the Internet of Things (IoT) comes with its own set of challenges. Security, privacy, and unified standards are a few key issues. In addition, each IoT product is comprised of at least three separate application components: the software embedded in the device, the backend big-data service, and the mobile application for the end user's controls. Each component is developed by a different team, using different technologies and practices, and deployed to a different stack/target - this makes the integration of these separate pipelines and the coordination of software upd...
SYS-CON Events announced today that IBM Cloud Data Services has been named “Bronze Sponsor” of SYS-CON's 17th Cloud Expo, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. IBM Cloud Data Services offers a portfolio of integrated, best-of-breed cloud data services for developers focused on mobile computing and analytics use cases.
In his session at @ThingsExpo, Tony Shan, Chief Architect at CTS, will explore the synergy of Big Data and IoT. First he will take a closer look at the Internet of Things and Big Data individually, in terms of what, which, why, where, when, who, how and how much. Then he will explore the relationship between IoT and Big Data. Specifically, he will drill down to how the 4Vs aspects intersect with IoT: Volume, Variety, Velocity and Value. In turn, Tony will analyze how the key components of IoT influence Big Data: Device, Connectivity, Context, and Intelligence. He will dive deep to the matrix...
When it comes to IoT in the enterprise, namely the commercial building and hospitality markets, a benefit not getting the attention it deserves is energy efficiency, and IoT’s direct impact on a cleaner, greener environment when installed in smart buildings. Until now clean technology was offered piecemeal and led with point solutions that require significant systems integration to orchestrate and deploy. There didn't exist a 'top down' approach that can manage and monitor the way a Smart Building actually breathes - immediately flagging overheating in a closet or over cooling in unoccupied ho...
SYS-CON Events announced today that Cloud Raxak has been named “Media & Session Sponsor” of SYS-CON's 17th Cloud Expo, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. Raxak Protect automates security compliance across private and public clouds. Using the SaaS tool or managed service, developers can deploy cloud apps quickly, cost-effectively, and without error.
Scott Guthrie's keynote presentation "Journey to the intelligent cloud" is a must view video. This is from AzureCon 2015, September 29, 2015 I have reproduced some screen shots in case you are unable to view this long video for one reason or another. One of the highlights is 3 datacenters coming on line in India.
“The Internet of Things transforms the way organizations leverage machine data and gain insights from it,” noted Splunk’s CTO Snehal Antani, as Splunk announced accelerated momentum in Industrial Data and the IoT. The trend is driven by Splunk’s continued investment in its products and partner ecosystem as well as the creativity of customers and the flexibility to deploy Splunk IoT solutions as software, cloud services or in a hybrid environment. Customers are using Splunk® solutions to collect and correlate data from control systems, sensors, mobile devices and IT systems for a variety of Ind...
SYS-CON Events announced today that ProfitBricks, the provider of painless cloud infrastructure, will exhibit at SYS-CON's 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. ProfitBricks is the IaaS provider that offers a painless cloud experience for all IT users, with no learning curve. ProfitBricks boasts flexible cloud servers and networking, an integrated Data Center Designer tool for visual control over the cloud and the best price/performance value available. ProfitBricks was named one of the coolest Clo...
You have your devices and your data, but what about the rest of your Internet of Things story? Two popular classes of technologies that nicely handle the Big Data analytics for Internet of Things are Apache Hadoop and NoSQL. Hadoop is designed for parallelizing analytical work across many servers and is ideal for the massive data volumes you create with IoT devices. NoSQL databases such as Apache HBase are ideal for storing and retrieving IoT data as “time series data.”
Clearly the way forward is to move to cloud be it bare metal, VMs or containers. One aspect of the current public clouds that is slowing this cloud migration is cloud lock-in. Every cloud vendor is trying to make it very difficult to move out once a customer has chosen their cloud. In his session at 17th Cloud Expo, Naveen Nimmu, CEO of Clouber, Inc., will advocate that making the inter-cloud migration as simple as changing airlines would help the entire industry to quickly adopt the cloud without worrying about any lock-in fears. In fact by having standard APIs for IaaS would help PaaS expl...
Organizations already struggle with the simple collection of data resulting from the proliferation of IoT, lacking the right infrastructure to manage it. They can't only rely on the cloud to collect and utilize this data because many applications still require dedicated infrastructure for security, redundancy, performance, etc. In his session at 17th Cloud Expo, Emil Sayegh, CEO of Codero Hosting, will discuss how in order to resolve the inherent issues, companies need to combine dedicated and cloud solutions through hybrid hosting – a sustainable solution for the data required to manage I...
Apps and devices shouldn't stop working when there's limited or no network connectivity. Learn how to bring data stored in a cloud database to the edge of the network (and back again) whenever an Internet connection is available. In his session at 17th Cloud Expo, Bradley Holt, Developer Advocate at IBM Cloud Data Services, will demonstrate techniques for replicating cloud databases with devices in order to build offline-first mobile or Internet of Things (IoT) apps that can provide a better, faster user experience, both offline and online. The focus of this talk will be on IBM Cloudant, Apa...
Mobile messaging has been a popular communication channel for more than 20 years. Finnish engineer Matti Makkonen invented the idea for SMS (Short Message Service) in 1984, making his vision a reality on December 3, 1992 by sending the first message ("Happy Christmas") from a PC to a cell phone. Since then, the technology has evolved immensely, from both a technology standpoint, and in our everyday uses for it. Originally used for person-to-person (P2P) communication, i.e., Sally sends a text message to Betty – mobile messaging now offers tremendous value to businesses for customer and empl...
As more and more data is generated from a variety of connected devices, the need to get insights from this data and predict future behavior and trends is increasingly essential for businesses. Real-time stream processing is needed in a variety of different industries such as Manufacturing, Oil and Gas, Automobile, Finance, Online Retail, Smart Grids, and Healthcare. Azure Stream Analytics is a fully managed distributed stream computation service that provides low latency, scalable processing of streaming data in the cloud with an enterprise grade SLA. It features built-in integration with Azur...
SYS-CON Events announced today that HPM Networks will exhibit at the 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. For 20 years, HPM Networks has been integrating technology solutions that solve complex business challenges. HPM Networks has designed solutions for both SMB and enterprise customers throughout the San Francisco Bay Area.
The enterprise is being consumerized, and the consumer is being enterprised. Moore's Law does not matter anymore, the future belongs to business virtualization powered by invisible service architecture, powered by hyperscale and hyperconvergence, and facilitated by vertical streaming and horizontal scaling and consolidation. Both buyers and sellers want instant results, and from paperwork to paperless to mindless is the ultimate goal for any seamless transaction. The sweetest sweet spot in innovation is automation. The most painful pain point for any business is the mismatch between supplies a...