Good way to define a method - c#

What is the best / good way to implement method calls.
For eg: From the below which is generally considered as best practice. If both are bad, then what is considered as best practice.
Option 1 :
private void BtnPostUpdate_Click(object sender, EventArgs e)
{
getValue();
}
private void getValue()
{
String FileName = TbxFileName.Text;
int PageNo = Convert.ToInt32(TbxPageNo.Text);
// get value from Business Layer
DataTable l_dtbl = m_BLL.getValue(FileName, PageNo);
if (l_dtbl.Rows.Count == 1)
{
TbxValue.Text = Convert.ToInt32(l_dtbl.Rows[0]["Value"]);
}
else
{
TbxValue.Text = 0;
}
}
Option 2 :
private void BtnPostUpdate_Click(object sender, EventArgs e)
{
String FileName = TbxFileName.Text;
int PageNo = Convert.ToInt32(TbxPageNo.Text);
int Value = getValue(FileName, PageNo);
TbxValue.Text = Value.ToString();
}
private int getValue(string FileName, int PageNo)
{
// get value from Business Layer
DataTable l_dtbl = m_BLL.getValue(FileName, PageNo);
if (l_dtbl.Rows.Count == 1)
{
return Convert.ToInt32(l_dtbl.Rows[0]["Value"]);
}
return 0;
}
I understand we can pass parameters directly without assigning to a local variable... My question is more about the method definition and the way it is handled.

If you're subscribing to the event automatically, I don't think it's particularly bad to have a method with the event handler signature which just delegates to a method which has the "real" signature you need (in this case, no parameters).
If you're subscribing manually, you can use a lambda expression instead:
postUpdateButton.Click += (sender, args) => PostUpdate();
and then do the work in PostUpdate. Whether you then split up the PostUpdate into two methods, one to deal with the UI interaction and one to deal with the BLL interaction is up to you. In this case I don't think it matters too much.
How you structure UI logic to make it testable is a whole different matter though. I've recently become a fan of the MVVM pattern, but I don't know how applicable that would be to your particular scenario (it's really designed around Silverlight and WPF).
A couple of other comments though:
Conventionally, parameters should be camelCased, not PascalCased
Do you genuinely believe you're getting benefit from prefixing local variables with l_? Isn't it obvious that they're local? Personally I'm not keen on most of the variable names shown here - consider naming variables after their meaning rather than their type.
Using a DataTable to return information is a somewhat error-prone way of doing things. Why can the BLL not return an int? to indicate the value (or a lack of value)?

here is what i like to to if i don't implement mvc. and i'm assuming web here.
I'd do option 2 first but instead of having the buttons code set the text id create a property to set the text boxs value.
I do this because if something else sets the textbox value then you are going to duplicate code. bad if you change a name or control type.

According to your example, option 2 is the way to go. Option 1 knows about your form and how to display data on it, which violates the SRP.

Related

Change Textbox object to Static

I have little experience in C#, mostly playing with it as a hobby, and I was wondering what I needed to do to change a textbox from non-static to static.
In Visual Studio 2012, I'm trying to add a line of text using the method textbox1.AppendText("Text");, and it won't work because the textbox isn't static, while the method trying to write the code is static. I can't find the line of code where the textbox is initialized in my code, nor have I found an option in the properties that allows me to change that.
Is there a work-around, or do I need to make it static? And if I need to make it static, how would I do that? I'm at a loss.
Thank you for your help!
EDIT: adding code sample. The method below is called from a second form, same from which the value of x is determined.
public static void getMethod(int x)
{
if (x > 4)
{
textbox1.AppendText("Text");
}
else
{
textbox1.AppendText("Other text");
otherVariable = x;
}
}
It's not clear from your post which GUI framework you're using. Both Winforms and WPF have a TextBox class.
But, to the point of your question: you could in the object where the TextBox is declared and created, also have a static field to which you assign that reference. But that would be a poor design choice, IMHO.
It's not clear what your static code is doing, where it's declared, or who called it (another failing of your question is that you did not provide any code, never mind a concise, complete code example), but assuming the static method is not in the UI object that owns the TextBox instance itself (if it is, then you just need to make the method non-static), the the correct way to address this would be for the UI object that does know about the TextBox instance to have some public method or property used to set the text, and then for the code that invokes your static method to pass the reference of that UI object to the static method, so that it can use the member you added.
For example:
class Form1 : Form
{
public string FieldText
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
}
and elsewhere:
static void SomeMethod(Form1 form)
{
// ...do some stuff...
form.FieldText = "some text";
// ...do some other stuff...
}
In your specific scenario, you seem to have two forms: one containing the textbox1 member, and another that passes an int value to a method, where you want to be able to add some text to the TextBox1 based on the value.
In that case, it would look more like this:
class Form1 : Form
{
public void AppendFieldText(string text)
{
textbox1.AppendText(text);
}
}
and in the static method:
public static void getMethod(int x, Form1 form)
{
if (x > 4)
{
form.AppendFieldText("Text");
}
else
{
form.AppendFieldText("Other text");
otherVariable = x;
}
}
Naturally, the caller of the getMethod() method will need the reference for the form parameter; you will have to pass that somehow to that second form which is calling this method, so that it can pass it to the method.
Note that in both of my examples, I have not exposed the TextBox object itself. You should follow this example, exposing only the minimum amount of functionality needed in order to get the job done. This helps ensure that the TextBox object doesn't wind up getting used in appropriately by some other code, and especially helps ensure that your classes remain reasonably decoupled.
On that latter point, I will mention that your code example is still pretty bare. There are other techniques which can solve this problem with even less coupling between the types. But again, lacking a good code example, it's not possible to know for sure what would work, never mind what would be best.
The above example is appropriate, given the information you've shared.
If you would like to edit your question to provide better, more specific detail, a better, more specific answer could be provided.
you can do something like below
private void button3_Click(object sender, EventArgs e)
{
getMethod(textBox1,5);
}
public static void getMethod(TextBox textbox1,int x)
{
if (x > 4)
{
textbox1.AppendText("Text");
}
else
{
textbox1.AppendText("Other text");
otherVariable = x;
}
}
Textboxes aren't static. And you can't make them static, they are all instanciated. The name of your textbox is the instance name.
So just use the text property on the instance of the text box.
textbox1.Text = "Text";
If you want to Append one just do:
textbox1.Text = String.Concat(Textbox1.Text, "more text");
same thing about could also be seen as:
textbox1.Text = textbox1.Text + "more text";

WPF validation of input (on-the-fly) and unit test. Best practice for design

I want to add a new form to an existing solution. The solution already has a Validator class, so I want to expand this class.
The Form I want to create contains a Textbox (for the input) and a Button. When the input is the correct format the submit button is enabled. The input must adhere to a certain regular expression: "^[A-Za-z]{2}[0-9]{5}$". I'm checking the input (on-the-fly) in the Form class like this:
private void inputTbx_TextChanged(object sender, TextChangedEventArgs e)
{
SubmitButton.IsEnabled = Validator.IsInputValid(inputTbx.Text, RegexExpression);
}
I've put the regular expression as a variable in the Form class. I put it here because it is relevant to the textbox of this form only.
private const string RegexExpression = "^[A-Za-z]{2}[0-9]{5}$";
Here's the validation code:
public static bool IsInputValid(string inputToBeChecked, string regexExpression)
{
if (inputToBeChecked == null || regexExpression == null)
{
return false;
}
var regex = new Regex(regexExpression, RegexOptions.None);
return regex.IsMatch(inputToBeChecked);
}
So far so good. It seems to work fine. But I want to unit test it like so:
[TestCase("aZ13579")]
public void ValidateInputOkTest(string input)
{
Assert.IsTrue(Validator.IsInputValid(input, RegexExpression));
}
But to do it like this I have to have a string in my ValidatorTest class similar to the Regular-expression used in the Form class. This doesn't seem like the right way to do it. What I really want to do is get the Regex expression from the form class, so I am sure it's the correct Regex-expression that I'm using. Otherwise the Regex-expressions could easily get out of sync.
Here are the questions:
What is best practice here?
How do I get to this expression? I've tried doing it using Reflection, but I get a Threadstat error because it's a GUI component. Should I move the Regular-expression? If so where to?
I'm thinking there must be a smart way to do this. A smart design perhaps. Suggestions and comments are welcome.
You're probably going to want to back up a step and start to research the 'MVVM' design pattern. When you hear people talk about putting no code in the code behind, testing like this is one of the big benefits (among many others).
MVVM is too big a topic to handle in a simple answer like this. I'd search around on the web, and I'm sure other people have some good tutorials.
Just to be clear, it can be a big learning curve, but it's totally worth it. MVVM is what makes WPF much much (MUCH) better than WinForms, rather than merely different.
Just to address your question a little more specifically, you won't be testing a GUI object like a Window or UserControl. You'll be testing a view model which is just a regular class.
Here's a simplified version of what you might see
public class MyScreenViewModel : INotifyPropertyChanged
{
private const string RegexExpression = "^[A-Za-z]{2}[0-9]{5}$";
public bool UserInputIsValid { get { stuff; } set { stuff; }}
public string UserInput { get { stuff; } set { stuff; ValidateUserInput();} }
private void ValidateUserInput()
{
if (UserInput == null)
{
return false;
}
var regex = new Regex(RegexExpression, RegexOptions.None);
UserInputIsValid = regex.IsMatch(UserInput);
}
}
A view model in MVVM is the real logic of your screen. It will expose simple properties that the view can bind to for display/input, but the view isn't necessary for testing the logic.
Then your test looks something like:
[TestCase("aZ13579")]
public void ValidateInputOkTest()
{
var vm = new MyScreenViewModel();
vm.UserInput = "SomeValidText";
Assert.IsTrue(vm.UserInputIsValid);
}
[TestCase("aZ13580")]
public void ValidateInputNotOkTest()
{
var vm = new MyScreenViewModel();
vm.UserInput = "SomeInvalidText";
Assert.IsFalse(vm.UserInputIsValid);
}

Checking for a condition in the calling scope or inside the function

i have the following 3 examples which does the same thing
//case1 do it if the condition is valid
private void SetMultiplePropertyValues()
{
if (Keyboard.GetKeyStates(Key.CapsLock) == KeyStates.Toggled)
{
//do somthing
}
}
//case 2 return if the condition is not valid
private void SetMultiplePropertyValues()
{
if (Keyboard.GetKeyStates(Key.CapsLock) != KeyStates.Toggled) return;
//do somthing
}
//case 3 checking the condition in the calling scope
if (Keyboard.GetKeyStates(Key.CapsLock)== KeyStates.Toggled)
SetMultiplePropertyValues())
private void SetMultiplePropertyValues()
{
//do somthing
}
which one would you go with and why
They do not do the same thing because in the first two cases the name of the method is a lie; the method name should be SetValuesIfTheKeyStateIsToggled or TryToSetValues or some such thing. Don't say you're going to do a thing and then not do it. More generally: separate your concerns. I would choose a fourth option:
public void TryToFrob()
{
if (CanFrob()) DoFrob();
}
private bool CanFrob()
{
return Keyboard.GetKeyStates(Key.CapsLock) == KeyStates.Toggled;
}
private void DoFrob()
{
// frob!
}
Notice what is public and what is private.
This is a silly looking example because each one is so simple, but one can easily imagine a situation in which these methods are complex. Keep your policies and your mechanisms logically separated. The mechanism is "is the keyboard in a particular state?" The policy is "I have some conditions under which I can frob; we must never frob unless those conditions are met".
First of all, as we can see at code comments, they don't do the same thing. So I think that you're talking about code architecture rather than functionality.
Second, here in SO isn't about giving opinions, but I'll try say to you concrete things about these differences.
1- Common if approach
if (true == false)
{
return true;
}
vs.
2 - Single line if approach
if (true == false) return true;
Most of code convetions says to use the option 1, because they're easier to read and understant code, and avoid some mistakes. We need to also understand that convetions are not rules! so they're just convetions, but really try to avoid option 2 in most of the cases.
One more thing, some code convetions also says that's ok using option 2 when you need something very simple, like this given example which is really easy to read and understand. But take this like an exception from the 'rules'.

Best "not is" syntax in C# [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
It is important to me that my syntax does not make other developers confused.
In this example, I need to know if a parameter is a certain type.
I have hit this before; what's the most elegant, clear approach to test "not is"?
Method 1:
void MyBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
if (!(e.parameter is MyClass)) { /* do something */ }
}
Method 2:
void MyBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
if (e.parameter is MyClass) { } else { /* do something */ }
}
Method 3:
void MyBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
var _Parameter = e.parameter as MyClass;
if (_Parameter != null) { /* do something */ }
}
Method 4:
void MyBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
var _Type = typeof(MyClass);
switch (e.parameter.GetType())
{
case _Type: /* do nothing */; break;
default: /* do something */; break;
}
}
[EDIT] Method 5:
void MyBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
if ((e.parameter is MyClass) == false) { /* do something */ }
}
Which is the most straight-forward approach?
This is obviously a matter of personal opinion and style, so there's no right answer, but I think this is clearest:
void MyBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
if ((e.parameter is MyClass) == false) { /* do something */ }
}
The == false is just more obvious than the !
I would go for 3 if you need the variable later or 1 if you don't need the variable.
2 is ugly because of the empty block.
However I think they all are straight-forward.
I would think just making an extension method would be a clear way of doing it:
public static bool CannotBeCastAs<T>(this object actual)
where T: class
{
return (actual as T == null);
}
You then simply make a check like so:
if(myObject.CannotBeCastAs<SomeClass>())
{
}
Methods 1 and 3 would be my picks, depending on what I actually wanted.
Method 1 "does something" if and only if the passed object is not of the expected type. This means the passed object could be null and still pass.
Method 3 "does something" if the passed object is not of the expected type, OR if the object is null. This is basically a one-pass check that you have a "valid" instance of the class to work with further.
So, whether I wanted 1 or 3 depends on what I was planning to do. Usually, when the variable isn't of the expected type or is null, I want to throw an exception. If I were happy with throwing just one type of exception (say just an ArgumentException), I'd use method 3. If I wanted to check for null separately and throw an ArgumentNullException, I'd use method 1 and add the null check.
Method 2 is functionally correct, but I'd rather invert the if condition as in Method 1, as an if block that does nothing is redundant.
I would never do Method 4. A switch statement taking the place of a simple if-else is unnecessary and confusing, especially in the manner you're using it.
To me, Method 1 is the most straight-forward, both on its own and by convention. This is the syntax I've seen the most if you just need to know if an object "is-a" certain class.
If you actually need to do something with the object "as-a" certain class, then Method 3 is the way to go.
Method 1 is the best in my view. It's very obvious what the code is doing and I can follow right along. Method 2 introduces unnecessary syntax that is easily corrected by Method 1. Method 3 requires me to think more than the other two (marginally, but still!), and it also uses extra space that isn't needed.
Remember code is written for people to read, and only after for machines to execute. Go with clarity every time.
If you want elegance and readability:
void MyBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
bool isMyClass = e.parameter is MyClass;
if (!isMyClass) // or isMyClass == false
{
/* do something */
}
}
I've always tried my best not to put too much logic in a single line of code, specially if conditions. I think the type check and negation operator might be annoying to parse on first glance.
Method #5 (a different spin)
public static class TypeExtensions
{
public static bool IsNotTypeOf<T, X>(this T instance, X typeInstance)
{
return instance.GetType() != typeInstance.GetType();
}
}
// ...
if(e.parameter.IsNotTypeOf(MyClass)) { /* do something */ } ;
I would be of the opinion that braced functionality should always match whatever brace pattern is in use in your application. For instance, in the case of iteration or conditional blocks, if you use:
If (foo != bar)
{
//Do Something
}
well then this should be how you use brace patterned functionality at all times. One of my biggest bugbears with reading other peoples code (and this is especially true if they use CodeRush or Resharper) is the unnecessary terseness people add for no other reason than to display wizardry.
I am not saying the above is the best brace matching pattern however, use whatever one you feel comfortable with, what I would like to get across is that the pattern does not matter so much as the consistency of its use.
Personally, since C# is a terse language in comparison to, say VB.Net I would use long form statements or assignments (with the exception of var initialising) over more condense syntax to help aid later readability.
I like an approach used by one of the NUnit Assert's:
Assert.InstanceOf<MyType>(objectInstance);
BTW,
If you have a set of checks whether object is of specific type like:
if(objectInstance is TypeA)
{
// ...
}else
{
if(objectInstance is TypeC)
{
// ...
}
}
There should be some design issues like tied coupling between few types, so consider an other approach like injected map of associations or map like algorithm method per type
IDictionary<Type, Func<TParameter>>

Is storing an object reference in a controls Tag property OK

I'm creating a group of form controls for each object in a list, is it OK to store a reference to the object in the controls Tag property?
I'm doing this so I can have a generic Click event on the controls, so when they are clicked I can update a field in the object that they represent.
So the click handler will look something like this.
private void Item_Clicked(object sender, system.EventArgs e)
{
if(sender.GetType() == typeof(System.Windows.Forms.Label))
{
System.Windows.Forms.Label label = (System.Windows.Forms.Label)sender;
MyObject myObject = label.Tag;
myObject.Value = true;
}
}
Is this an acceptable thing to do in this situation, or is there a better way to handle this?
Yes this is legal to do and is one of the patterns the Tag property was designed for.
The biggest danger here is that another peice of code attempts to use the same Tag property for their own feature. This would create a race for the Tag property and lead to runtime bugs. A safer approach would be to create a private map between a Label and MyObject using a Dictionary instance.
private Dictionary<Label,MyObject> _map = new Dictionary<Label,MyObject>();
...
private void Item_Clicked(object sender, system.EventArgs e)
{
if(sender.GetType() == typeof(System.Windows.Forms.Label))
{
System.Windows.Forms.Label label = (System.Windows.Forms.Label)sender;
MyObject myObject = _map[label];
myObject.Value = true;
}
}
This approach has the extra overhead of a Dictionary but produces more reliable code (IMHO).
It's acceptable if it works for you. I've stored things in the tag properly like this before, and it works fine. Things to consider: the size of the object you're storing and the lifecyle of the object (could it be disposed of or destroyed between accesses).
Another approach, that I have used, is to store a "hint" that would help you retreive or recreate the object. For example, if it's a database object, store the Id property (maybe an integer or Guid) which is much [potentially] much smaller than the object itself.

Categories

Resources