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 Video Library
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
View Events Video Library
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
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

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • How to Estimate Object Memory Allocation in Java
  • All You Need To Know About Garbage Collection in Java
  • User-Friendly API Publishing and Testing With Retrofit
  • Top Java Collection Interview Questions for 2021

Trending

  • TDD With FastAPI Is Easy
  • Automated Testing: The Missing Piece of Your CI/CD Puzzle
  • LTS JDK 21 Features
  • Unraveling Lombok's Code Design Pitfalls: Exploring Encapsulation Issues
  1. DZone
  2. Coding
  3. Languages
  4. Defensive Programming: Why You Shouldn't Check Input Parameters for Validity

Defensive Programming: Why You Shouldn't Check Input Parameters for Validity

Do you check input parameters of methods for validity? Well, maybe you shouldn't, and instead you should use validating decorators.

Yegor Bugayenko user avatar by
Yegor Bugayenko
·
Feb. 17, 16 · Tutorial
Like (61)
Save
Tweet
Share
37.22K Views

Join the DZone community and get the full member experience.

Join For Free

do you check the input parameters of your methods for validity? i don't. i used to, but not anymore. i just let my methods crash with a null pointer and other exceptions when parameters are not valid. this may sound illogical, but only in the beginning. i'm suggesting you use validating decorators instead.

shi mian mai fu (2004) by yimou zhang
" shi mian mai fu " (2004) by yimou zhang

let's take a look at this rather typical java example:

class report { 
  void export(file file) { 
    if (file == null) { 
      throw new illegalargumentexception( "file is null; can't export." ); 
    } 

    if (file.exists()) { 
      throw new illegalargumentexception( "file already exists." ); 
    } 

    // export the report to the file 
  } 
}

pretty defensive , right? if we remove these validations, the code will be much shorter, but it will crash with rather confusing messages if null is provided by the client. moreover, if the file already exists, our report will silently overwrite it. pretty dangerous, right?

yes, we must protect ourselves, and we must be defensive.

but not this way, not by bloating the class with validations that have nothing to do with its core functionality. instead, we should use decorators to do the validation. here is how. first, there must be an interface report :

interface report { 
  void export(file file); 
}

then, a class that implements the core functionality:

class defaultreport implements report { 
  @override void export(file file) { 
    // export the report to the file 
  } 
}

and, finally, a number of decorators that will protect us:

class nowriteoverreport implements report { 
  private final report origin; 

  nowriteoverreport(report rep) { 
    this.origin = rep; 
  } 

  @override void export(file file) { 
    if (file.exists()) { 
      throw new illegalargumentexception( "file already exists." ); 
    } 

    this.origin.export(file); 
  } 
}

now, the client has the flexibility of composing a complex object from decorators that perform their specific tasks. the core object will do the reporting, while the decorators will validate parameters:

report report = new nonullreport( new nowriteoverreport( new defaultreport() ) ); 
report.export(file);

what do we achieve with this approach? first and foremost: smaller objects. and smaller objects always mean higher maintainability . our defaultreport class will always remain small, no matter how many validations we may invent in the future. the more things we need to validate, the more validating decorators we will create. all of them will be small and cohesive. and we'll be able to put them together in different variations.

besides that, this approach makes our code much more reusable , as classes perform very few operations and don't defend themselves by default. while being defensive is an important feature, we'll use validating decorators. but this will not always be the case. sometimes validation is just too expensive in terms of time and memory, and we may want to work directly with objects that don't defend themselves.

i also decided not to use the java validation api anymore for the same reason. its annotations make classes much more verbose and less cohesive. i'm using validating decorators instead.

Object (computer science) Crash (computing) Java (programming language) Pointer (computer programming) Memory (storage engine) Foremost (software) Maintainability Interface (computing)

Published at DZone with permission of Yegor Bugayenko. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Estimate Object Memory Allocation in Java
  • All You Need To Know About Garbage Collection in Java
  • User-Friendly API Publishing and Testing With Retrofit
  • Top Java Collection Interview Questions for 2021

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

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: