DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations

Saving lines - the usage of ternary and null-coalescing operators

Denzel D. user avatar by
Denzel D.
·
May. 06, 10 · Interview
Like (0)
Save
Tweet
Share
8.96K Views

Join the DZone community and get the full member experience.

Join For Free

Think about the situations when you had to write multiple IF statements to verify the validity of a statement or a value. More than that, think about the situations when you had to basically repeat almost the same IF statements in several cases – the code volume becomes huge. Take a look at this sample piece of code:

int i = 0;
int b = 10;
int c = 120;
int d = 12;

if (i == 0)
Debug.Print(i.ToString());
else
Debug.Print("Not zero");

if (b == 10)
Debug.Print(b.ToString());
else
Debug.Print("Not 10");

if (c == 120)
Debug.Print(c.ToString());
else
Debug.Print("Not 120");

if (d == 12)
Debug.Print(d.ToString());
else
Debug.Print("Not 12");
Mind, that this is generic code and many other situations can be referenced to this specific example. However, it shows the idea behind multiple  verifications on different values. The good news is – this code can be significantly shortened. And the key here is the ternary IF operator (also known as the conditional operator). The ternary IF operator is a specific feature of the C-type languages (like C++ or C#), however it was implemented in other languages as well (like VB.NET or Perl). It allows to put the above mentioned IF statements in a single line, sometimes saving significant amounts of code.

I am going to show the implementation of the code above using ternary IF operators and later I am going to explain its structure.

int i = 0;
int b = 10;
int c = 120;
int d = 12;

Debug.Print(i== 0 ? i.ToString() : "Not zero");
Debug.Print(b == 10 ? b.ToString() : "Not 10");
Debug.Print(c == 120 ? c.ToString() : "Not 120");
Debug.Print(d == 12 ? d.ToString() : "Not 12");

Pretty concise, isn’t it? Although it might seem a bit confusing, the overall structure is pretty simple. The general idea behind it is this:

Statement [IF] ? Action 1 [THEN – CONDITION VERIFIED] : Action 2 [ELSE – CONDITION FAILED]

The important part about ternary operators is that those cannot be used as statements. I can only use them in assignments or method calls.

Another element that is worth mentioning on the same topic is the null-coalescing operator. It works similar to the ternary operator, but it has a different purpose. It checks whether the passed instance (either a variable or class instance) is null. Personally, I found it extremely useful when reading XML that is obtained via different web APIs. Since XML nodes can be null, it is good to check whether those can be used further in the application.

An example of using the null-coalescing operator is below:

string a = null;
Debug.Print(a ?? "Null");

Notice the fact that it doesn’t have an ELSE part. It only triggers the specified action if the object is null.

Both ternary operators and the null-coalescing operator can be easily used to minimize the volume taken by IF statements. Their structure is easy enough to understand, making the code readable even with a short representation.

In many cases when elements like these are used (shorthand versions of full-sized statements), I advise not to over-use them. This is not the case. I advise the developers who used two-way IF-statements before to consider ternary operators and the null-coalescing operator.



Operator (extension)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Front-End Troubleshooting Using OpenTelemetry
  • Building Microservice in Golang
  • How To Build a Spring Boot GraalVM Image
  • Comparing Map.of() and New HashMap() in Java

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: