Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to prevent death by parentheses?

Occasionally, I will write some code with way more parentheses than I like.

 if(!(new Day((((new Date()) / millisecondsPerDay) % 75)) instanceof oldDay))) { 
    // Bonus points if that condition made any sense to you
 }

It is hard to keep track of how many parentheses I need to put, especially when I'm not using an IDE that immediately tells me when something is wrong. In fact, I bet the above example doesn't match the parentheses correctly. I've been pegged with errors from death by parentheses more than I would like to admit.

I was wondering if there was a way to circumvent this. What techniques can I use to avoid having to wrap things with so many parentheses?

Are there any languages with a mechanism that prevent the need for so many parentheses? For example, I thought adding special characters that automaticall close parentheses and one that automatically opens them might help. (< and > in the following example)

if(!(new Day<new Date()) / millisecondsPerDay) % 75> instanceof oldDay>
like image 539
Peter Olson Avatar asked Aug 26 '11 19:08

Peter Olson


2 Answers

One viable alternative is to precompute the parenthesized values before the conditional loop. Take your code for example:

if(!(new Day((((new Date()) / millisecondsPerDay) % 75)) instanceof oldDay))) { 
    // Bonus points if that condition made any sense to you
 }

Let's start breaking it up.

Date d1 = new Date();
var factor1 = (d1 / millisecondsPerDay ) % 75;
Day day1 = new Day (factor1);

if (!day1 instanceof oldDay) {
// do something
}

Remember that code is written for humans to read and only afterwards for machines to execute. If you find giant conditionals, then start preprocessing them and break it up. If it takes more than a second to figure out what your condition is checking, then it's probably too long.

like image 138
BlackJack Avatar answered Sep 28 '22 19:09

BlackJack


Well, first of all i always like to refactor this kind of code. If i can, i extract part of expression to the variable (or function, whichever suites best), then you can make more sense to the code itself, and you would'nt need to make such a mess

bool isOldDay(int someFactor)
{
    if(someFactor instanceof oldDay) 
    {
        return true;
    }
    return false;

}

var today = new Date();
var particularFactor = today/millisecondsPerDay;
var someFactor = particularFactor % 75
var day = new Day(someFactor);


if(!isOldDay(day)) //Do something

EDIT: By the way if you want to do something without parentheses you can try something like this: Reverse Polish Notation

Which you can make 5 + ((1 + 2) * 4) − 3 into this thing : 5 1 2 + 4 * + 3 - .Of course this form may be very close to stack representation of calculations in compilators.

like image 45
Igoris Azanovas Avatar answered Sep 28 '22 17:09

Igoris Azanovas