Sujet : Re: Code guidelines
De : thiago.adams (at) *nospam* gmail.com (Thiago Adams)
Groupes : comp.lang.cDate : 03. Sep 2024, 17:23:49
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vb7d6l$3d5mv$1@dont-email.me>
References : 1 2 3 4 5
User-Agent : Mozilla Thunderbird
On 03/09/2024 11:53, David Brown wrote:
On 03/09/2024 16:12, Thiago Adams wrote:
On 03/09/2024 10:33, Thiago Adams wrote:
...
For instance:
>
The first sample my create confusion (is name optional?)
>
void f(struct user* user)
{
if (user->name && strcmp(user->name, "john") == 0)
{
//...
}
}
>
But :
void f(struct user* user)
{
assert(user->name);
if (user->name && strcmp(user->name, "john") == 0)
{
//...
}
}
>
would show redundancy but making clear the contract still "name should not be null"
>
Redundant code can either indicate a programmer's mental confusion
Yes.
or serve as a way to address potential contract violations.
No.
If specification violations are realistic (from untrusted code, or code under development), then a /single/ check looks for violations. /Redundant/ checks are pointless at best, and (as I have explained) often worse than useless.
Computers are not humans that might miss something on the first glance, then see it on the second time. Do the same check twice in the code and you will get the same answer each time - the second check gives no benefits.
>
I believe the objective is to ensure that runtime checks are not questioning the contract but rather functioning as redundant safeguards.
>
In other words, the programmer must demonstrate that they understand the contract and are not messing it.
>
A safeguards for a very low risk situation also may indicate a mental confusion about the risks involved. For instance, assert(2 + 2 == 4);
>
A redundant check is, by definition, a very low risk situation.
I will give a sample
In my code I have
if (obj->member1 &&
obj->member1->member2 &&
obj->member1->member2->member3)
{
}
The contract is
* obj->member1 CAN be null
* obj->member1->member2 CANNOT be null
* obj->member1->member2->member3 CAN be null
So I can write just
if (obj->member1 &&
obj->member1->member2->member3)
{
}
but...maybe, is better to be a little redundant here?
I think I prefer to leave "obj->member1->member2 && " even if I know
it should not be null.
if (obj->member1 &&
obj->member1->member2 &&
obj->member1->member2->member3)
{
}