As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
private void button1_Click(object sender, System.EventArgs e)
{
Clipboard.SetDataObject(textBox1.Text,true);
}
private void button2_Click(object sender, System.EventArgs e)
{
if(Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))
textBox1.Text = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();
else
textBox1.Text = "The clipboad does not contain any text";
}
I write this application using C# Windows Form Application
Let's talk for a second about patterns and cults.
You hear a lot about "learn design patterns" and "you suck if you don't use design patterns" and "you should use the X pattern" and all that. There's a whole patterns movement going on...a cult, even...encouraging people to patternify everything. Saying that this is how people ought to do things. That there's a pattern for everything, and by $DEITY, you should be using it.
Guess what? About 80% of it is crap. They're vastly overemphasizing the role and scope of design patterns.
Patterns are a tool. Nothing more. They are not their own reason to exist. They are not the key to world peace. They are not the solution to all problems, and you should not use them just because they are there, or because you drank the cultists' Kool-Aid. You should use them only when and because they are meant for the job you need to do, and they thus make sense.
Design patterns' entire purpose -- their only purpose -- is to reduce overall complexity.* Wherever they do not do that, they are not a good fit, and you should ignore them.
So every time you're thinking about using some particular pattern, ask yourself the one most important question: How will it simplify things?
* Note, i said overall complexity. Applying a design pattern often involves adding complexity to one part of the app in order to remove much more of it from some other part. As long as there's a net loss of complexity, the pattern's still worth looking at.
Now, as for your code.
You've asked about changing that little snippet around to use the Command pattern. I suppose it's possible; i see "copy" and "paste" actions, which could conceivably be parameterized with a reference to the text box.
Question is, though: How will it simplify things?
Without any context other than that snippet, i don't see how you'd gain from adding CopyCommand and PasteCommand classes, and code to instantiate and use them in precisely one place. Perhaps when you're doing lots of copying and pasting in other places, it might be worth it...but right now, no. It feels like you're trying to shoehorn a pattern in where it doesn't want to go.
What is the Correct way of write this using command design pattern?
First, read and understand what cHao wrote in his Answer. (He is not saying that design patterns are crap. He is saying that the way a lot of people use and talk about using design patterns is crap. I agree ...)
Your question doesn't have a good answer:
First, you need to ask yourself why you are trying to use any design pattern at all here. If you are just doing it because you've been told that using design patterns is a good thing, you are doing it for the wrong reason.
Second, repeat that question replacing "any design pattern at all" with "the Command design pattern" ... What are you trying to achieve here by applying this particular design pattern? If you can't answer that, then you need to 1) go back and review the Command design pattern, and understand what it achieves, and 2) then decide whether you actually need what it achieves in your program.
If I was to directly answer your initial and follow-up questions, I would have to say:
the example code snippet doesn't appear to use the Command design pattern,
without seeing the rest of your code, I cannot say whether it should be using that design pattern at all, and
without seeing the rest of your code, I cannot say how it should use that design pattern.
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I've read some things about this, I even found similar question, but it didn't really answer this. For me it seems that privatizing something only makes my life so much harder when I need to find a private variable in a class to use it elsewhere. So what is would the problem be if everything was public? Would it somehow slow the program itself?
You must consider the maintainability of the code. Accessing all the variables everywhere in your solution is good only if you are the only one in the project and you will be the only one that maintain and use the code. If someone else's entered into project and do completely different things they will be able to access your methods/variables and set the things to unexpected variables. You should think as a OOP design and design your classes like that.
FYI I don't believe you are supposed to ask discussion-based questions like this on SO... But the simplistic answer is this: don't limit your thinking to the logic of the code. We all know there are ten thousand ways to accomplish the same thing. You can probably rewrite a bunch of your code to avoid encapsulation. However, data encapsulation provides a few benefits when you start working on larger projects or with larger teams that go beyond just writing functional code:
(1) organization by concept: if you're coding a bike you would code a class for the wheel, a class for the frame, a class for the handlebars, etc., and you'd know where to go to resolve an issue, perhaps even after months of time away from the code;
(2) separation of implementation and interface: you can tell the world about your public interface and handle the actual implementation privately, so people don't have to know how things work in your code, they just know that it works, like a black box; and if later you have to change your private implementation you can do so freely as long as the public interface still works;
(3) simplification for humans: remember, humans read your code, so would you like to slam them with every bit of data and logic in your project? that would just make for a bunch of angry programmers.
So that's a gentle introduction to encapsulation.
This comes from the fact that, a class should not expose its members directly but must provide a proxy through which the members must be accessed. (Like getters/setters or Properties)
See this question for more info: Why it is recommended to declare instance variables as private?
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I decided to learn some Python (IronPython) syntax today. In doing so, I was impressed by a construct that it allows with its loops.
Python supports an else clause on its loops. An else on a loop basically says, "if this loop finished normally, then enter this clause".
Allow me to demonstrate using C#.
This code:
Something something = SomeCallToSetThisUp();
bool isCompatable = false;
foreach (Widget widget in widgets)
{
isCompatable = widget.IsCompatableWithSomething(something);
if (!isCompatable)
break;
}
if (isCompatable)
compatableSomethings.Add(something);
could become this code (not valid C#):
Something something = SomeCallToSetThisUp();
foreach (Widget widget in widgets)
{
if (!widget.IsCompatableWithSomething(something));
break;
}
else
compatableSomethings.Add(something);
Having never seen this, it struck me as cool. And once you learn it, it seemed as readable as any code I have seen.
While not universally needed (sometimes you want to affect every item in the list), I do think that it would be useful.
So, my question is: Why isn't this in C#?
I have a few ideas why:
break can make debugging harder, so the designers did not want to encourage it.
Not everything that is shiny can make it into the language. (limited scope).
But those are just guesses. I am asking for an actual canonical reason.
The usual answer is because no-one asked for it or the cost of developing and maintaining it outweights the benefits.
From Eric Lippert's blog:
I've already linked several times to Eric Gunnerson's great post on
the C# design process. The two most important points in Eric's post
are: (1) this is not a subtractive process; we don't start with C++ or
Java or Haskell and then decide whether to leave some feature of them
out. And (2) just being a good feature is not enough. Features have to
be so compelling that they are worth the enormous dollar costs of
designing, implementing, testing, documenting and shipping the
feature. They have to be worth the cost of complicating the language
and making it more difficult to design other features in the future.
After we finished the last-minute minor redesigns of various parts of
C# 3.0, we made a list of every feature we could think of that could
possibly go into a future version of C#. We spent many, many hours
going through each feature on that list, trying to "bucket" it. Each
feature got put into a unique bucket. The buckets were labelled:
Pri 1: Must have in the next version
Pri 2: Should have in the next version
Pri 3: Nice to have in the next version
Pri 4: Likely requires deep study for many years before we can do it
Pri 5: Bad idea
Obviously we immediately stopped considering the fours and fives in
the context of the next version. We then added up the costs of the
features in the first three buckets, compared them against the design,
implementation, testing and documenting resources we had available.
The costs were massively higher than the resources available, so we
cut everything in bucket 2 and 3, and about half of what was in bucket
1. Turns out that some of those "must haves" were actually "should haves".
Understanding this bucketing process will help when I talk about some
of the features suggested in that long forum topic. Many of the
features suggested were perfectly good, but fell into bucket 3. They
didn't make up the 100 point deficit, they just weren't compelling
enough.
http://blogs.msdn.com/b/ericlippert/archive/2008/10/08/the-future-of-c-part-one.aspx
Additionally, you need to weight if the feature will be easily understood by existing / new developers. IMHO else on loop is not very readable, especially since the keyword for 'execute this block if the previous one finished OK' is finally.
What is more, I think Enumerable.Any / Enumerable.All methods are much better in this scenarios.
Looping through a collection and checking a condition are different things, so they should be separate language constructs.
Because for else loops are a hack from languages like python. If you feel like you need a for else loop, you should probably put that code in a separate function.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I know this might be a stupid question, but here it goes.
I always wrote my private members like privateMember and I've been reading a lot about naming conventions in C# because I noticed that a lot of the automatic generated code in visual studio use _variableName for private members. Everywhere I read, even in Microsoft documents, that you should use privateMember.
So, my question is, if the good practices says that I should write privateMember, as I do now, Why the heck Visual Studio generates classes with private members using underscore (_privateMember)?
Microsoft Code Conventions actually recommend against using underscores altogether. It is really personal preference. I would not use generated code as inspiration for my coding convention standard.
Do not use underscores, hyphens, or any other nonalphanumeric characters.
Maybe it's because it's generated code and not intended to be read by humans. ;-)
Not so long time ago when C# was raising to the market there was a concept that local variables should be leaded by a prefix _. This concept was not accepted by the community as in pure C the _ leads system variable/functions and the metadata are lead by __. So after few years, they now discourage to use that. But still you will find some believer that use this notation not because it is a fanatic but a lot of old C# applications contain this convention.
Why this is in VisualStudio ?
This might be related to the time gap it was designed. In those time this approach was suggested by language designers. So it is probably that no one changed that in the configuration for latest version.
Naming conventions aren't 100% agreed upon. This is one of those that some people like, some people are indifferent to, and some people hate. Certain people consider it better for instance variables to stand out, via their name, and this is one way to do that. Other people use this.instanceVariable rather than instanceVariable all of the time so that instance variables stand out, other people prepend something other than a '_' character, and some people just don't go out of their way to use any special distinction.
At the end of the day what's important is that you, and the other members of your team agree on a standard and are consistent with it. What the rest of the world chooses to do doesn't need to affect you.
It's also worth mentioning that the code snippets generated by Visual Studio, in most cases, can be configured to be in line with your team's coding practices.
It's just a convention they use, I do it too. You can ultimately name your private fields whatever you want. Prefixing it with an underscore just makes it easier to read IMO.
As a convention private fields were/is used as with underscore e.g. string _name;
The link will give you more info on guidelines for naming coventions by MS http://msdn.microsoft.com/en-us/library/ms229045.aspx
It's just the C# language convention so that in constructor you can use _varable instead of this.variable, when the constructor and field name is the same.
there are all c# naming conventions in
http://msdn.microsoft.com/en-us/library/ms229002.aspx
It's a mather of you if you follow the convention of the generated code.
Besisdes the recomendations many programmers use the same convention as the generated code.
Some programs that help you refactor the code also sugests you to follow that name convention for field names.
The underscore at the beginning is VS's way of showing that it is a privateMember. We keep the underscore at the beginning as a rule, but it is really a personal preference as to what naming convention you use. Just pick one and stick with it so you don't confuse yourself or anyone else that might look at your code.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
What is the optimal amount of lines in method shold be used?
Curly braces doesn't count.
What code is better? Code is runing in Main()
//1st
string line;
while ((line = Console.ReadLine()).ToLower() != Break)
{
commandAnalyzer.AnalyzeAndRun(line);
}
// or 2nd
RunTextualInterface(commandAnalyzer);
private static void RunTextualInterface(TextCommandAnalyzer commandAnalyzer)
{
while (notBreakCommand())
{
analyzeCommandWithHelpOf(commandAnalyzer);
}
}
private static void analyzeCommandWithHelpOf(TextCommandAnalyzer commandAnalyzer)
{
commandAnalyzer.AnalyzeAndRun(readNewLine());
}
private static bool notBreakCommand()
{
return readNewLine() != Break;
}
private static string readNewLine()
{
return Console.ReadLine().ToLower();
}
// result just the same
P.S I am asking cause out teacher said that every method must have maximum 6 lines.(Curly braces dosn't count)
I think first approach would be better in this case. Too many method will decrease the readability when the logic involved is not too complex and not that large that it should be a separate method. Also it will make sense to make different methods if this logic has to be used by other parts of program as well. But again as the methods are so small, it doesn't even makes sense to me to make a separate method in this case
You want to reduce the amount of code you need to maintain without reducing readability. I like your first answer. Read Steve Yegge on how code size is Code's Worst Enemy.
Strive to keep everything the reader of your code will need to understand your code as local as possible. Use abstractions (e.g. refactoring stuff to methods) where they help. Avoid abstractions (e.g. inventing new names for operations your reader is already familiar with) where they don't help.
As to the various rules on method sizes: They aren't rules. They are guidelines. Whenever your method gets too long, stop. It could be a sign of a bad design. But it doesn't have to be - use the rule to trigger a closer look at your code.
Develop a sense of style. This will change all the time as you progress. Don't be afraid to update your style all the time - though do try to keep the same style during a project. Try out different styles and gain experience. It is the only true path.
If you're interested in that kinda questions, I'd suggest reading:
Code Complete 2nd Edition
The book has a chapter about that:
"Creating high quality code" -> "How long can a routine be?"
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Here is an example of the type of article I'm talking about:
http://support.microsoft.com/kb/319401
I assume these articles are written by people who work for Microsoft and that the code in the articles will always be rock solid and never contain any malicious code. I just want to make sure I can explain to my boss that this is an ok place to copy code from (I've been told never to copy code from the internet, but this seems like a safe source).
I would trust them not to be malicious, but they're not always good code. (MSDN samples are sometimes pretty awful.)
For example, here's some code in the sample you gave:
compareResult = ObjectCompare.Compare
(listviewX.SubItems[ColumnToSort].Text,
listviewY.SubItems[ColumnToSort].Text);
// Calculate correct return value based on object comparison
if (OrderOfSort == SortOrder.Ascending)
{
// Ascending sort is selected, return normal result of compare operation
return compareResult;
}
else if (OrderOfSort == SortOrder.Descending)
{
// Descending sort is selected, return negative result of compare operation
return (-compareResult);
}
else
{
// Return '0' to indicate they are equal
return 0;
}
Now, there are two issues here:
Why is it deemed valid to have a comparer with no sort order? This should be a constructor parameter, validated at the point of construction IMO.
You should not just negate the result of one comparison to perform a "reverse comparison". That breaks if the result of the first comparison is int.MinValue - because -int.MinValue == int.MinValue. It's better to reverse the arguments used to perform the original comparison.
There are other things I'd take issue with in this code, but these two should be enough to make my point.
I heartily agree with the other answers too, in terms of:
- Check the copyright / licence etc of any code you want to use
- Make sure you understand anything you want to use
Your boss probably wouldn't mind if you only copied the code into a test project that you use to test and understand the code. You can then use what you've learned to write the production code.
And while I don't think anyone outside of Microsoft knows the names of the people who write those support articles, they come from the same vendor that your toolchain does, so if you don't trust the support articles, then you can't trust the tools you've bought either.
Microsoft Knowledgebase articles show safe (as in non-malicious but not necessarily secure) code, but usually the example provides the most basic use case possible. There's a good chance that you'll have to tweak the code a bit for it to work the way you want.
You should also pay attention to the date of the articles. For example, the article you link to is almost three years old. There's definitely a better way to handle that situation now.
Be aware that most codes in articles are there to help you understand the concepts. They are not "production ready". Learn the concepts instead and implement your own.
Have you been told not to copy code from the internet because of rights issues? If so then you don't have to worry about this Microsoft code.
I would advise you not to use any code you don't understand. If you can't say if the code is malicious or not don't use it.
MSDN and kb support articles are written by MS employees that are part of the given product's UX team (user experience). These are people who typically have a background in technical writing, but are not necessarily developers themselves (although some are). It's very common for the UX team to collaborate with developers on the product to ensure their code samples are correct. However this collaboration in my experience is one of the lowest priorities a typical MS developer has and can go ignored, and so it can at times lead to poor code getting out.
With that said, I completely agree with Carl Norum's comment. Copying code you do not understand is done at your own risk. Make sure you understand any code you place in your product!
I've always found the Microsoft articles to be of the highest quality (sadly not their products).
However, there's always the danger of a spoofing site.
Explain that you carefully read the article to understand the information in there, and only copy code that you understand.
If you don't understand the code, then even if the code is correct it may not be doing what you actually need done, thus your program will be incorrect.
You also will have a hard time debugging and maintaining code if there are parts that you don't understand.