Safely access and parse a bool from a Dictionary [closed] - c#

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I have an application that uses a Dictionary<String,String> to store configuration.
I want to:
Check if the dictionary contains "Key"
Parse the Value of "Key" as a bool
Default to false if not found
Presently I am doing the following
bool settingBool = false
if (configDictionary.ContainsKey("Key")) {
bool.Tryparse(configDictionary["Key"], out settingBool)
}
// Do some stuff with settingBool
Are there any pitfalls or obvious issues with the above approach especially from a readability/maintainability aspect?

Are there any pitfalls or obvious issues with the above approach especially from a readability/maintainability aspect?
As an addition to #Cetin Basoz answer.
Since you want to do something with your settingsBool I personally would go with configDictionary.TryGetValue("Key", out value), because
TryGetValue
This method combines the functionality of the ContainsKey method and the Item[TKey] property.
So for your example:
var configDictionary = new Dictionary<string,string>() { { "Key" , "Value"} };
string value;
bool settingBool;
if ( configDictionary.TryGetValue("Key", out value)
&& bool.TryParse(value, out settingBool) )
{
// Do something with your settingBool
}
else
{
// Do something if "Key" is not present or Value could not be parsed.
}
Hint: You did not need to set your settingBool to false, since false is the default value. Try default(bool)

If one liner is needed or adding if the value parseable as bool then you can use && :
bool settingBool = false;
if (configDictionary.ContainsKey("Key") && bool.TryParse(configDictionary["Key"], out settingBool)
{
}
else {} // what if not? Then wouldn't you accept as false?
If default would be false when not found or not parseable to bool:
bool settingBool = false;
settingBool = configDictionary.ContainsKey("Key") &&
bool.TryParse(configDictionary["Key"], out settingBool)
&& settingBool;
The latter could be used to get with Linq to get multiple bool settings.
Note: bool.TryParse can parse limited strings as bools (it doesn't parse Yes, No, Y/N, 1/0 ... as bools).

Related

If I have multiple if else statement like this how do you consider refactor it? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
If I have multiple if else statement like this how do you consider refactor it?
var a = DoSomethingToGetA();
if (UserPreviouslySignedIn)
{
var b = DoSomethingToGetB();
if (a == b && !string.IsNullOrWhiteSpace(a))
{
Validate(a);
}
else
{
Validate(b);
}
}
else
{
Validate(a);
}
You could invert ifs and do early return to reduce nesting. Since you're doing the same call just with a different argument, you could also just determine the argument first and do a single call, something like this would do the same as your code I believe:
var a = DoSomethingToGetA();
if (!UserPreviouslySignedIn)
{
Validate(a);
return;
}
var b = DoSomethingToGetB();
var toValidate = (a == b && !string.IsNullOrWhiteSpace(a)) ? a : b;
Validate(toValidate);
But if you're checking whether a == b before validating a, and otherwise b, it would just give you the same result if you always validated b. If it is equal to a, then you're just validating a, but named b, if they're not, you're validating b anyway.
So the only differing factor here would be the UserPreviouslySignedIn boolean. Which would mean it could be boiled down to a ternary assignment and single Validate call as such:
var toValidate = !UserPreviouslySignedIn ? DoSomethingToGetA() : DoSomethingToGetB();
Validate(toValidate);

Common Code Convention for not equal in conditional statements [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I've been coming across not equal != or !condition in conditional statements ever since I started programming. Maybe it's because my brain is pre-conditioned in the English language to overthink multiple negation. But I have been wondering, is there a common development community accepted practice when it comes to evaluating for true in conditional statements? Or rather, the way I see it sometimes: evaluating for not false.
Maybe there are exceptions where != cannot be completely unavoidable?
For Example:
This might be a very simple and trivial, but is this preferred
string myStringVar = "dogs";
if (myStringVar != "dogs") //In my mind, "False this is not true"
{
//code
}
else if (myStringVar != cats) //In my mind, "True this is false"
{
//code
}
Or is this preferable
if (myStringVar == "dogs")
{
//"True"
}
else if (myStringVar == "cats")
{
//"False"
}
Then there's
bool MyBoolMethod()
{
return false;
}
if (!MyBoolMethod()) // True this method does not return true
{
//code
}
This is a very trivial and simplified example, I just want to know how to write readable, maintainable code. Does anyone else have a somewhat difficult time reading conditionals like this or is it just me?
"None of the above."
Since you're using strings, the assumption is that myStringVar can be anything. If I say:
string myStringVar = "Aardvark";
Then your first example, it will run the myStringVar != "dogs" section of code; In the second example, neither will be executed. So they're not equivalent pieces of code.
The only way they would be equivalent is if you were using Enums (in which case I would suggest using a case statement).
In your third example, it would depend on what MyBoolMethod() was named, and how easy it was to understand by a future coder. To use an example,
bool isDog()
{
return false;
}
is is easy to understand. The question then becomes is
if(!isDog()) ...
more clear than
if(isNotDog()) ...
I would argue that the first is more clear than the second. There are other situations, however, where that is not the case.
Equality and inequality are just something one needs to get comfortable with and choose in context. If the logical problem requires looking to test against equality use equality if it is looking to disqualify use inequality.
The readability and maintainability can be reinforced through good design as you started to allude to with your mybool method.
Exmaple
public class Animal
{
public static Enum AnimalType
{
Dog,
Cat
}
private _animalType;
public Animal(Enum AnimalType type)
{
AnimalType = _animalType;
}
public bool isOfType(Enum AnimalType type)
{
return _animalType == type ? true : false;
}
}
public someothermethod()
{
//doing inclusion
If(MyAnmialObject.isOfType(Animal.AnimalType.Dog))
{
//if type matches
}
//Doing exclusion
If(!MyAnmialObject.isOfType(Animal.AnimalType.Dog))
{
//if type does not match
}
}
You still have to get used to inequality but you know it is checking for isOfType and the named type.

Check if a string contains not defined characters [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a pre defined string as Follows.
string preDefined="abc"; // or i can use char array in here
string value="ac";
string value1="abw";
I need some function to compare value with preDefined.
(value.SomefunctionContains(preDefined)
this function needs to return
value -> true;
value1 -> false
I knew that i can't use contains() or Any(). so plz help
You are just looking for if value has any character that is not in predefined, so this should do it:
!value.Any(x => !predefined.Contains(x))
Or it's more clear using All:
value.All(predefined.Contains);
private bool SomeFunction(string preDefined, string str)
{
foreach (char ch in str)
{
if (!preDefined.Contains(ch))
{
return false;
}
}
return true;
}
You can implement the following method to get the result :
private static bool DoesContain(string predefined, string value)
{
char[] c_pre = predefined.ToCharArray();
char[] c_val = value.ToCharArray();
char[] intersection = c_pre.Intersect(c_val).ToArray();
if (intersection.Length == c_val.Length) {
return true;
}
else {
return false;
}
}
Please not that this solution is a generalized implementation. IT also returns true even if the characters are not in the same order, unless ther include all.

Is it readable or non-effective in C# to declare conditions before using IF [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
When writting codes, using if by following way
int something = 5;
bool possible = false;
if( something>0 && !possible){
doSomething();
}
and
int something = 5;
bool possible = false;
bool condition1 = something > 0;
bool condition2 = !possible;
if( condition1 && condition2){
doSomething();
}
Which is more readable?
Which is more effective?
I assume 2nd is better when case like
if( Something > (SomeOtherThing + SomeSomeThing) && !Something.Something.Possible)
I know this doesn't directly concern with c# but want to know especially in c#!
There is no hard and fast rule, but quite often the code can be much more readable if you extract to speaking variable names or method calls. In the following example the condition is absolutely clear.
bool UserIsAdmin() { ... }
bool UserOwnsItem() { ... }
bool UserMayAccessItem {
return UserIsAdmin() || UserOwnsItem();
}
// ..
if (UserMayAccessItem()) {
// do something here
}
On the other hand there certainly may be simple cases where adding variables does not increase readability.
It basically is a matter of style and preference. Just keep in mind that the code should be easily readable and speak for itself.
The first option is preferable, not only because of shortcut evaluation, but also for maintainability.
I guarantee you that you or someone else will eventually change the conditions, without bothering to adapt the variable names, too, for example.
It is non-effective.
When condition1 is false, it is not required to calculate condition2 in your example. Sometimes this calculation eats resources (request to DB for example). In this case 2nd option is non-effective.
However it is readable, particularly when you name condition variables in more convenient way, for example:
bool somethingIsPositive = somithing > 0;
bool itIsImpossible = !possible;
if(somethingIsPositive && itIsImpossible)
...
Also you can leverage Lazy class (if you use C#) to not claculate condition2 all the time (even when condition1 is false), so this is really more readable and hasn't performance problems (when condition2 takes time to calculate, not in your case :) ):
int something = GetNumber();
bool possible = GetPossibility();
var somethingIsPositive = new Lazy<bool>(() => something > 0);
var itIsImpossible = new Lazy<bool>(() => !possible);
if( somethingIsPositive.Value && itIsImpossible.Value){
doSomething();
}

How to properly use the IF Statement [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Which one is correct and WHY
in both examples we have a function that determines if a certain string is valid...
(using some other function that's not defined here)
private Validator = new Validator();
public Boolean IsValid(String foo)
{
if (Validator.Validate(foo))
{
return true;
}
else
{
return false;
}
}
in the second scenario we have a function that ends with a TRUE statement and with no else.
private Validator = new Validator();
public Boolean IsValid(String foo)
{
if (!Validator.Validate(foo))
{
return false;
}
return true;
}
NOW INB4 please dont say that you can simply do it this way
return Validator.Validate(foo);
How to save a few lines its not what i want to know...but the implications and unknown consecuences ( to me ) of using one method or the other.
Because both IsValid() methods do nothing else they are equivalent.
All 3 are correct. The third is my preference because it's less code and still very readable in this case.
I think that the best solution is:
public bool IsValid(String foo)
{
return (Validator.Validate(foo))? true : false;
}
In addition the conditional expression is easy to understand and it's inline

Categories