Here I have a sample of code.
I would like to know other way to write this code; specially I would like to know other forms for the nested if.
Also I would like your opinion about commenting (what are the best practice, is my style of commenting sufficient in professional environment?)
If this question is out of scope for SO please let me know, I will remove it please do not down vote I just try to learn about programming ;-).
// Has User expressed his preference?
if (!repositoryDevice.HasDevicePreference(userDevice)) // If not ...
{
// Save the preference
repositoryPreference.Add(userDevice.UserId, candidateId);
result = true;
}
else // If yes ...
{
// If a User has express his preference more than 1 hour ago
// allow the User to change his preference, otherwise not
if (!HasUserRecentPreference(userDevice))
{
repositoryPreference.Add(userDevice.UserId, candidateId);
result = true;
}
}
You can put else and if on the same line:
It is also possible (as someone else pointed out) to use the
&&/||operators to merge the two conditions into a single block of code. Assuming that the code in the two blocks are identical, that is of course the preferred solution: never write the same line twice.Otherwise, it looks very much good enough! 🙂 It’s generally considered a good idea to avoid source code complexity.