Home > Articles > Process Improvement

Robert C. Martin's Clean Code Tip of the Week #10: Avoid Too Many Arguments

We join "The Craftsman," Robert C. Martin's series on an interstellar spacecraft where programmers hone their coding skills. In this tenth tip in the series, the crew learns that functions should have a small number of arguments.

You can review additional articles from Robert C. Martin's series, "The Craftsman," on the ObjectMentor website.

Like this article? We recommend

August 12, 1945, 10:30 AM Philadelphia

General Groves walked up to the secretary at precisely 10:30 AM. This meeting was too critical to be compromised by an error in punctuality. “Hello General.” Said Miss Ives. “Mr. Rearden is expecting you. Please go right in.”

Hank Readen stood up and extended his hand as the General walked into his office. “It is good to see you again, General. How can I help you this time?”

Rearden gestured to the chair next to his desk, and Groves took the seat.

“Hank, we need steel. Lots of steel.”

Rearden chuckled. “General, that is a problem I’d be very happy to help you with. How much steel are we talking about, and when do you need it?”

The General’s eyes fixed upon Rearden’s with an intensity that caused the smile to drain from Rearden’s face.

“Hank, if you tripled your annual production, we’d take it all starting now.”

Rearden sat back and let out his breath.

“Les, that’s…”

“Look, Hank, we need this. We’ll pay you well for it, and loan you the capital to build new physical plant. But this has to be done fast, and it can’t go wrong. Frankly, that’s why we picked you for this. We knew that if anyone could make the steel we need, it’d be Henry Rearden.”

The smile slowly returned to Rearden’s face. “General, I’ll be happy to work with you on this. I have some inkling of what’s at stake. But tell me, Les, are you sure it’s steel that you need?”


Wed, 15 Mar 2002, 11:00

“No way, Avery, he’s just not that good.”

“Alphonse, he’ll beat the pants off him!”

We were sitting together at my workstation, discussion the latest chess championship.

“Look, Avery, Eddie is going to pound Robie into the back ranks. Did you see how he slaughtered Wheeler?”

“Hell, Alphonse, It doesn’t take much to psych Wheeler, he always gives up too many knights.”

Jasmine stuck her head up and glared at us. “Will you two hotshots keep a lid on it please, people are trying to work over here.”

“Leave the boys alone.” Jerry interjected. “I’m interested to hear their view. I think Robie’s going to fall like a rotten tree.”

Jasmine shifted her glare to Jerry. “Can it JJ! I need a little peace to fix this mess you made last year.”

I looked at Avery and snickered. We both silently mouthed: “Jay-Jay?”

Jerry was taken aback. “Woah…huh? What mess? I didn’t….”

But Jasmine wouldn’t be stopped. “This mess of an IO control function you wrote last year. Cripes, JJ, how many arguments can you cram into one function?”

Jerry got indignant. “Jasmine, that system works great! I didn’t make a mess!”

Jasper, Jared, and Adelaide popped their heads up to listen in. This had the makings of a pretty good show.

“OH YES YOU DID!” Jasmine looked around at the silent observers. “You should see this fracking thing!”

Avery got a nasty grin on his face and started typing some commands I hadn’t seen before.

“What are you doing?” I whispered.

“Watch.” He replied.

And suddenly our screen filled with the contents of Jasmine’s screen.

“How did you…” But Avery put his finger over his lips.

“You mean the IOTransfer function?” Jerry wheedled. “But that’s just a low level…”

“THAT’S THE ONE!” Jasmine declared with triumph. “Crimeny, Jeez! What a horror scene! Whoooeee!”

Avery carefully scrolled Jasmine’s screen until he found this:

int result = IOX(0x32, NO_PARITY|DMA1|CLUMP,
buf, 32, 500, true);

Jerry looked around nervously. He could see that this was drawing an audience. “But Jasmine, it’s just a low level IO function.”

“JJ, dear…” (That got Jean’s attention.) “…it’s a low level IO function that you call all over the place! I’m having the frackingest time figuring out what each of those calls do! What possessed you?”

Avery opened an IM window and started sending the viewport address of Jasmine’s screen to the observers. I could see them looking at their screens and smiling.

“Aw, come on Jasmine, we were in a hurry! We had to…”

Avery started scrolling Jasmine’s screen. If she noticed we’d be toast. But she was right, calls to IOX were all over the place, and they were a horror scene.

if (IOX(0x38, PARITY|DMA2, s2, l, t+200, false)
== 3) {
. . .
r |= IOX(0x19, VOID, startSequence, 2, -1, null);
. . .
IOX(0x18, INVERTED|NO_DMA|CLUMP, header, 16,
500, true);

I heard startled and strangled moans coming from nearby workstations. Apparently Avery was giving everyone the same tour of this code that I was seeing. So far neither Jasmine nor Jerry seemed to notice.

Jasmine wasn’t giving any ground. “You were in a hurry? And, what? You left all this crap all over the place? “

“Well, I…”

I caught a movement from Jean out of the corner of my eye. It looked like she was about to say something. But then I saw a look come over her face that I’d never seen before. She raised an eyebrow, and then simply sat back down.

Jasmine folded her arms and continued to press her attack. “Can you please explain the arguments of this function to me, JJ? …Can you?”

“OK, sure.” Jerry started to move over to Jasmine’s workstation.

“No you stay right there, JJ! I want you to tell me from memory. What’s that first argument JJ?”

“OK, er, it’s the IO address, I think.”

“I think your right, JJ, very good. But do you think you could have put those blinking addresses in some nicely named variables? I mean, 0x38 doesn’t mean one hell of a lot to me. What does it mean to you?”

Jerry squirmed. “Uh, yeah, uh, I think thirty-eight was the pressure transducer input.”

“I think you might just be right about that JJ. I think it is the pressure transducer input. It only took me an hour to discover that by looking over the circuit diagrams of the module. But never mind that, can you please tell me what the PARITY and DMA and CLUMPING stuff is in the second argument?”

Little beads of perspiration were trickling down Jerry’s forehead. “Uh, well, yeah. I think the second argument was a set of bits that controlled the details of the transfer. They selected things like the DMA port, and parity checking, and whether or not the data was sent byte-by-byte or in 8 byte clumps.”

“And how, dear JJ, would I figure this out? It seems the only supporting document I’ve got is the module circuit diagram, and a chain of ECO modifications to it.”

“Yeah, well, we were just in such a hurry, you know. We… Anyway, you can always ask me what these things are…” Jerry shrugged, his face was pleading for Jasmine to let him off the hook.

“Yes, you were in a hurry. It shows! And now I’m stuck with the consequences of your rushing. Thanks. But please go on. What are the rest of the arguments of this function?”

Jasmine looked at her screen. I saw her pause for half a second, and then smirk to herself.

“Why don’t I just come over there and…”

Jasmine put her hands on her hips and said: “OH NO, YOU JUST TELL ME.”

Jerry sighed. “OK, uh, there’s the buffer address. The next is the length.”

“Stop right there. Is that length in bytes JJ?”

“Uh, well, sometimes. That is, er, yes, it’s in bytes, unless the CLUMP bit is set, and then it’s in, uh, eight byte clumps.”

“Nice… Go on. What comes next?”

I heard a faint echo of her words coming from nearby workstations. I glanced at Avery, and he smiled that evil smile of his. He pointed to his screen. He had set up a connection counter. There were 52 people connected to the viewport he had set up. I saw that he had also connected his microphone to the viewport, so all 52 people could hear this exchange. I knew this wasn’t going to end well for us.

“Uh…” Jerry stammered. “Uh… the next argument is… uh… the timeout in milliseconds!”

Jasmine sneered, her voice dripping with sarcasm. “Really? The timeout in milliseconds? Tell me JJ dear, how long is minus one milliseconds?”

Jerry hung his head. “Oh, yeah, uh, yeah. We, uh, used -1 to mean wait forever.”

“I see, JJ, thank you. Negative one means forever. Good. That’s perfectly clear. Thanks… Now… can you tell me about that last argument please?”

“You mean the Boolean?”

“Yes, JJ, the Boolean.”

“Uh…   I think you pass true if you want the transfer to abort on error, and false if you want it to ignore errors and just finish the transfer.”

Jasmine’s smile was pure, cold, evil. “And what, JJ dearest, does it mean when you pass null into that Boolean argument?”

Jerry drooped like a rag doll. “Uh… null?”

“Yes, JJ, null.”

“Oh yeah, uh… You’d pass null into the Boolean if the previous transfer aborted on error, and you wanted to continue the transfer from where it left off.”

“So let me get this straight, JJ, this is a Boolean with three states…right?

“Well…”

“A BOOLEAN WITH THREE STATES…RIGHT?”

Jerry wouldn’t look up. “Uh…”

Jasmine’s voice ran cold. “Say it Jerry!”

Jerry sighed and stared at the floor. “Yes, it’s a Boolean with… three states.”

“Thank you JJ, that was very informative. You may sit down now.”

Then Jasmine looked around the room, looked at her screen, and then looked around the room once again. “I see that Avery and Alphonse have managed to get about 60 people to watch our little show.”

Avery quickly hunched his shoulders and stared at his hands. I wanted to be anywhere else except where I was.

“OK all you voyeurs, take this as a lesson. Don’t make functions with lots of arguments. They’re hard to understand. Create objects instead. Now look at your screens!”

Jasmine had scrolled to one of the first calls to IOX.

int result = IOX(0x32, NO_PARITY|DMA1|CLUMP,
buf, 32, 500, true);

“I want all you lurkers out there to consider that Jerry could have written it like this:

IOChannel temperatureTransducer = new
IOChannel(temperatureTransducerAddress);
temperatureTransducer.dontUseParity();
temperatureTransducer.useDMAPort(1);
temperatureTransducer.transferIn8ByteClumps();
temperatureTransducer.timeOutAfterMilliseconds(500);
temperatureTransducer.abortOnError();


temperatureTranducer.readNBytes(buf, 32)

“Then he could have used that IOChannel every time he wanted to read from the transducer.”

Jasmine stood glaring around the room. Everyone else had their heads down. Jasmine’s brought Mr. C’s rule about function arguments up on her screen for everyone to see. Then she cranked up the volume on the viewport and laughed as everyone’s speakers screamed with feedback.

F1: Too Many Arguments

Functions should have a small number of arguments. No argument is best, followed by one, two, and three. More than three is very questionable and should be avoided with prejudice.

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