Good idea to predefine multiple parameters in method [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 6 years ago.
Improve this question
I was wondering about coding practices, and came up witha question. Is it a good idea to predefine multiple parameters within one method - so when you call that method you don't have to pass values if the value is predefined and correct.
i.e.
private void ErrorMessage
(bool isEmpty = false, bool fromAccEmpty = false, bool toAccEmpty = false){}
So when you call it you can either call it via
ErrorMessage();
or
ErrorMessage(true, false, true);

I think this will be an alternate for you:
public class ErrorMessage
{
public bool isEmpty = false;
public bool fromAccEmpty = false;
public bool toAccEmpty = false;
}
private void ShowErrorMessage(ErrorMessage errorObject)
{
//Do your stuff here
}
Why i suggest this:
Consider the op's code:
# If we call the method as he stated in the question (Positional arguments) we cannot call the method by specifying value for second parameter without giving value to the first one.
# This can be avoided by using Named arguments as like the following:
ErrorMessage(fromAccEmpty :true);
Hence we can assign value to the second parameter only, others will be default. We can simply use the suggested method without these issues and confusions; consider the following snippets:
ErrorMessage errorBoject = new ErrorMessage();
ShowErrorMessage(errorBoject);// All default values ware assigned
errorBoject.toAccEmpty = true;
ShowErrorMessage(errorBoject); // call with value for last parameter only rest are default
errorBoject.isEmpty = true;
ShowErrorMessage(errorBoject); // only the second value is default rest of them have values

one thing to think about is this. When you see
ErrorMessage(true, false, true, false);
in the code 2 yrs from now. What does it mean? Also did you get the flags in the correct order. Although its more long-winded maybe
FribbleErrorMessage(); // some flag = true
FrobbleErrorMessage(); // some flag = false
....
is clearer. (Yes I know you would need 16 methods for all combinations or 4 flags - but maybe there are common ones to be called out, and reduce the number of flags)
Another idea is replace the bools by enums
ErrorMessage(IsError.True, EmptyAcc.False,..);
Now you can see what they mean and the compiler will ensure you pass the correct things
Or un-lucky's suggestion of passing a parameter block of some sort
ErrorMessage(new ErrorControl{IsEmpty=true});
Note that many people (including me) fronw on default arg values as opposed to overloads. Why? Because if you want to change the default behavior you have to recompile the callers, maybe not a problem for you but in general is makes encapsulation a little weaker (Same reason why you should have public get;set; accessors instead of naked public fields)

Related

How can I test if an objects property is below 0 without changing its value C# [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 24 days ago.
Improve this question
This is the start of a very simple banking application.
I have abstract base class which this class inherits from.
public class CheckingAccount : AccountBase
{
public override bool Withdraw(float withdrawAmount)
{
if ((Balance -= withdrawAmount) < 0)
{
return false;
}
else
{
Balance -= withdrawAmount;
return true;
}
}
}
The withdraw function has an if statement which checks if the balance minus the withdraw amount would be less than 0. If it is less than 0 it returns false and does not do the operation. If it is more than 0 then it moves to the else block and does the operation and returns true.
When I test this in the main function, like this:
CheckingAccount cAccount = new CheckingAccount();
cAccount.Deposit(300);
cAccount.Withdraw(500);
Console.WriteLine(cAccount.Balance.ToString());
The final output is still -200. When I place breakpoints in the code, I see that it is going through the correct path with it not directly changing the Balance property as it just returns false however, the comparison in the if statement is still changing the actual property. i know that classes are reference types however I do not know how to pass this by value instead as I just want to check if it would be less than 0 and not actually change to stored value in the property.
I tried to do a simple comparison however this comparison ended up actually changing the property. I've tried changing around things here but nothing's really working. I'm new to programming still so this might be a silly question but I can't find any answers.
Just change -= to -. -= is a distinct binary operator that mutates the value of the first operand by subtracting the amount of the second operand. If you just want to compare the difference between the two, just use -.

How to deal with a massive amount of conditions [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 3 years ago.
Improve this question
Intro
I am trying to build a system that will give information to the front-end which elements should and shouldn’t be shown.
But the problem i am running into is that i have to deal with massive amount of conditions, these could vary from rights to which modules are available and even which data is available.
So i was expecting that someone else would also have run in to this problem, but i couldn’t find anything.
What i have tried
I first start searching for design patterns that could possibly deal with this problem but i couldn’t find any that did. Then i went to source making and read all the descriptions of possible patterns but to me none of them seemed to be the solution to my problem.
Afterwards i just searched around if someone had encounter a similar problem and once again i did not seem to find any close comparisons to my problem.
So are their any suggestion how i could improve searching
Or did i overlook something?
I would suggest that you take a look to something like the Rules design pattern
Effectively, this would be a large set of predicates.
Steps needed to accomplise this:
1. Change boolean logic to predicates and extentions
2. Create interfaces that provide the proper logic and transformations
With the Rules Pattern there is an Evaluator class that loops through a collection of rules and executes them. It evaluates the result and decides what action to take. In the simplest case it just executes all the rules, but it is also possible to add some selection logic to each rule that allows the Evaluator class to decide whether or not to run the rule (such as the IsMatch() method on the IRule interface above).
You can put your if statements into method which return bool value. For example:
public void GetMeal(Behavior behavior)
{
if (isAnimal(behavior))
GetMilk();
else
ChangeBattery();
}
private bool isAnimal(Behavior behavior)
{
if (behavior.HasVoice
&& behavior.HasVoice
&& !behavior.HasBattery )
return true;
return false;
}
public class Behavior
{
public bool HasVoice { get; set; }
public bool HasName { get; set; }
public bool HasBattery { get; set; }
}
I would suggest replacing those statements with commands. Here is a link with more info. The code is not in C# tho but I think you can understand the main idea from it.
https://scrutinizer-ci.com/docs/refactorings/replace-conditional-dispatcher-with-command

Boolean naming convention: statement or questionn? [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
(questionn is misspelled on purpose: stackoverflow does not allow the word "question" in the title)
Consider a property SomethingHasChanged
This can be read as a statement, SomethingHasChanged!, or a question, SomethingHasChanged?
What are the conventions (C#) for naming booleans? As statements or as questions?
Background
All code of a client I work for, is written in Dutch. In Dutch there is a slight difference between these two forms that in English does not exist. Therefore we need to make a decision between the two forms. Example: ErIsIetsGewijzigd! vs IsErIetsGewijzigd?
Many boolean properties start with Is or Has , e.g.:
this.IsRed = this (object) is red
this.HasChildren = this (object) has children
Your name doesn't really fit this convention well:
this.SomethingHasChanged = this (object) has something that has changed.
To match this convention, I'd rename your property IsDirty or similar.
A Boolean variable or property is an outcome of an expression, therefore, it is not a question, but a statement.
If, instead, you are asking a question, which requires an operation to answer it, than it should be a method and may be named as such.
It depends on whether you want to communicate you read state or determine it on request. A property bool HasChanged {get; set; } can be called twice and it should result in the same stored value. However a method bool HasChanged() communicates it is going to determine it for you on demand.
Finally, as I am Dutch as well, ErIsIetsGewijzigd sounds like a command, therefore as I read it, it should set the property, i.e. ErIsIetsGewijzigd(true);.

Is it "wrong" for properties to call methods or start events [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
Naming conventions imply that (typically) properties are nouns, methods are verbs. Now, I know these are guides, not rules, but it's something best to follow a guide when you can.
This means, the following
Person.Name = "Dave";
should only set the Name property. I would not expect the property to look like
public string Name
{
set
{
UpdateDatabase(value);
}
}
My question is pretty much exactly the example above but in relation to DependencyProperties.
My application has a UserControl, it looks like
<uc:MyControl MyControlMyValue="{Binding RelativeSource={RelativeSource AncestorType=userControls:MyOtherControl}, Path=MyValue, Mode=OneWayToSource}" />
So, as you can see in the above, when the MyControlMyValue property is updated, it updates the MyValue property. The problem I have is when this property is updated I need it to perform more logic than simple binding!
At the moment, I'm voting to ignore the guide and implement something like
private double _myValue;
public double MyValue
{
get { return __myValue; }
set
{
if (value == __myValue)
return;
__myValue= value;
LookAtMeHiddenAway();
OnPropertyChanged("MyValue");
}
}
Is there a better approach as it does feel very wrong to me?
Well, it depends.
If we are talking about general programming guideline, I would say no. Do not call methods inside properties, as I and others when we use properties (write/read) we expect of storing and retrieving data. So if you are going to change something, change it by calling a method, that manifests by declaration its behavior.
In case, instead, of WPF that is actually an expected behavior. So in case of WPF properties are suitable for changing data inside and are expected to behave in that way.
Bottom line: there are no strong restrictions on subject, but suggested guideline that is based on expected behavior of the code in the given environment.
I would create an event called OnMyValueChanged and anything that needs to update when that property changed would register a handler to that event. Or handle the PropertyChanged event. It's the same thing really, but it avoids putting logic in the setter that is not directly applicable to the property (eg constraining the value).

Way of coding in C# [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
Sometimes I have to write big code in a class, so what I do is something like this,
Class ABC //it's a web service class
{
Public void Method-1() //used "-" for easy to read
{
//DoSomething and get something from database
Method-2(pass parameters that i got from database);
}
Public void Method-2(parameters)
{
DoSomething again and get data from another database. and some other source
do some processing by calling web services (just as example)
Method-3(parameter);
}
Public void Method-3(parameters)
{
DoSomething again and get data from another database. and some other source
do some processing by calling web services (just as example)
Method-4(parameter);
}
// and it keeps going
}
Another way
Class ABC //it's a web service class
{
Public void Method-1() //used "-" for easy to read
{
Method-2();
Method-3();
Method-4();
// so on....
}
}
Is this the right way of doing it and if not then what would be best way of doing it ?
Edit
#Sayse I am trying to get information from different sources and trying to build a big XML file which made me get use 4, 5 foreach loops to get data from sql etc.. so using nested methods
Both ways are good in different cases. If you have single functionalities, you should keep them separate. Second approach - calling method from method should be used when one method is part of 'outer' functionality.
Examples:
repairVehicles() {
repairCar();
repairBike();
repairTrain();
}
... but:
repairCar() {
...
repairEngine();
...
}
repairEngine() {
...
takeEngineOut();
....
}
takeEngineOut() {
...
unscrewBolts();
...
}
There cannot be a straight forward answer to your question.
First of all you should note that one method should perform one functionality. If it is true, then you can call it either way depending on your requirement.
Example:
If you have a base method takes a mathematical expression as input. And that expression contains Add, Subtract, Multiply and divide then you will call it the first way.
public int GetExpressionResult(string someExpression)
{
Divide();
Multiply();
Addition();
Subtraction();
return result;
}
in the above example the result is dependant on all four methods, so it is fine to call it like this.
now in your example 2 if the methods are totally independant of each other than you should the way you have done.
Conclusion:
There is no hard and fast rule for this, You should call the way your application demands.
As far as I understood your question, what you are describing is basically a pipeline. There is a very interesting blog (in two parts here and here) about how to elegantly tackle situations as yours.
At the end, it depends on what you're trying to do and applies, IMHO, not only to C#.
Your first option should be applied when method<i+1> is a helper for method<i>, or is included in it. I can't find an example for such a scenario.
Your second example, which is far more readable to me, should be applied when you have a long sequence of actions that need to take place. Let say:
void mainMethod()
{
ConnectToDB(); //if can't connect, log it and exit
GetUserInfo(...); //if null, log it and exit
ShowUserInfo(...);
}
In the example above, it's hard (for me) to imagine a division to methods like in your first scenario.

Categories

Resources