Method lines amount. Clean code [closed] - c#

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?"

Related

Why doesn't C# allow an else clause on loops? [closed]

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.

best use for Regions and Inner Regions [closed]

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 have see alot of old code and from a lot of developers.
#region #endregion
can be helpful some times but if is use well.
how is the best way to use it to keep my code organized and easy to read?
It doesn't mean anything special if that's what you're asking. The only special effect it has is within Visual Studio for code folding.
If you have a large class that performs a few tasks, it may be best to region it out by separating your properties, different groups of methods, interface implementations, and whatever else you think may be important. There are no strict rules.
class MyReallyBigClass : IAwesome, INotAsAwesome
{
#region Public Properties
public string Test { get; set; }
// ..
#endregion
#region IAwesome Implementation
public void IAwesome.BeAwesome()
{
// ..
}
public int IAwesome.AwesomeLevel()
{
// ..
}
#endregion
#region INotAsAwesome Implementation [[...]]
#region Internal Fields
private int _whatever;
// ..
#endregion
}
Of course in practice, you wouldn't really get a class so large that you'd need to separate it out, but I normally do find myself using it around properties and interface implementations at the least.
It's purely to aid readability in the IDE. It's effectively stripped out on compilation.
That said, I tend to defer to Microsoft's style guidelines with regards to usage: grouping methods, properties, constructors, etc. - rarely, if ever, inside a method, and never between a brace construct (if, for, etc) and the opening brace.

C# Programming Best Practices For Mathematical Calculations [closed]

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.
Can anyone let me know where can I read the best practices to write an application that relies heavily on mathematical calculations? For example, suppose I was asked to write a C# application that generates 100 even numbers. I would write the following:
public void GenerateEven() {
for (int i=0;i<100;i++) {
Console.WriteLine(i * 2);
}
}
However that is not the best practice to do. The best way to generate even number would be, for example:
public void GenerateEven() {
int i=0;
while (i <200) {
if (i % 2 == 0) {
Console.Writeline(i);
}
}
}
If you're after expressiveness, take a page from functional programming:
public static IEnumerable<int> EvenNumbers(int start = 0)
{
while (true)
{
yield return start;
start += 2;
}
}
Then to get your sequence:
var firstHundredEvenNumbers = EvenNumers().Take(100);
It really depends upon your goal. If you're looking for composition, the above is great. If you're looking for raw speed, then you should mash all the logic into one ball and tune the heck out of it -- but it'll be harder to work with.
What makes you think the second method is the best way to do it? If I were asked to do that problem, then I would do this, so I only loop 100 times.
for (int i = 0; i < 200; i += 2)
Console.WriteLine(i);
As for your more general question, there is no one document or book that gives you best practices on how you should form loops or approach mathematical problems. This is where a computer science education comes in handy to analyze your problem and try to find an optimal solution.
In your sample problem each one of the solutions proposed (including the ones proposed by me) come down to a big O of N, so the computational differences between these solutions are negligible. The growth is linear with respect to N. The only advantage my solution provides is that it only loops over the necessary items to generate the output, instead of skipping items that do not meet the criteria.
Actually you may be looking for The Art of Computer Programming by Donald Knuth
Its called the bible of all fundamental algorithms and contains many kinds of programming algorithms and their analysis. But it does not cover any language specific moments.
If you want to generate numbers, you can use Enumerable.Range thus:
Edit: (rotem)
var a = Enumerable.Range(1,100/ 2+ 1).Select((X) => X * 2).ToList();

Would you make this method Static or not? [closed]

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.
During a code review I presented a method quickly to the team that I had made static and one person agreed that there was no reason for it to not be static and a person disagreed saying that he would not make it static because it wasn't necessary and just to be on the safe side for future modifications and testing.
So I did quite a bit of research and obviously it's a specialized case but I would like to know what you would do in this situation and why?
(Its basically a helper method I call from a few different methods, a very low traffic page. More for my knowledge and learning on Static.)
private IEnumerable<Category> GetCategoryByID(int id, Context context)
{
var categoryQuery = from selectAllProc in context.SelectAll_sp()
where selectAllProc.CategoryID == id
select selectAllProc;
return categoryQuery;
}
Making private methods static is a form of micro-optimization; the method call is slightly faster. But the difference is almost too small to be meaningful.
Generally speaking, you should mark a method static when it:
Doesn't interact in any way with instance members, and
You would like to have the ability to call it without instantiating the class, as in Class.Method()
Ordinarily, methods like your example would go into their own static helper class, if they are used in more than one place.
If I were you I would ask my self the following questions.
Is it something which is related to type or instance of type?
If the answer is yes, I would be slightly inclined to make it static else, make it non static.
If you can give us some more information, the community can come up with some good options.
The first remark that comes to my mind is that by declaring this method static and possibly using it in multiple places in your code you are introducing a Service-locator kind of dependency.
As far as I know the main problem with it is that implicit dependencies are introduced, i.e. they can't be inferred by looking at method signatures.
As a consequence it can be much harder to assess the impact of a modification of your static method on the rest of your system.

Why can't you call methods with c# object initializer syntax? [closed]

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.
Why can't you call methods with c# object initializer syntax?
It seems to me that the property setters are called in the order that they are set in the syntax, so why not allow calls to methods as well? If there is a good reason, I'm missing it.
EDIT
I realize the semantic differences between methods and properties and the technical similarities. The purpose of this question is to probe for a good technical reason that they did not include the feature.
this. __curious_geek, I hear what you are saying, but I'm sure there are some features they haven't included because it wasn't technically feasable.
That's all I'm after. The overwhelming unwelcoming tone is heard loud and clear. Stackoverflow is no longer a "Question and Answer site" but instead a "Defend your question site".
Edit 2
Sample usage:
var mySuperLongVariableNameThatIDontWantToTypeOverAndOverAgainAndIsntThatTheWholePointAnyway = new Thingy
{
Name = "Marty McFly",
AddChildren("Biff","Big Bird","Alf"),
// 1000 other properties and method calls.....
}
The answer is in the name -- object initializer syntax is syntactic sugar to visually group the object's initial state. Methods change the object state, so once it's changed, it's no longer the initial state.
For example: say you buy a car. It is a red coupe with 55,000 miles on it. Then, you decide to drive it. It ends up with 55,500 miles on it. It has changed from its initial state:
var c = new Car() {Color = "Red",
Style = Styles.Coupe,
Mileage = 55000};
// c.Mileage is 55,000
c.Drive();
// c.Mileage is 55,500
In this somewhat contrived example, the method has a side effect and thus changes the object from its initial 55,000mi state to a 55,500mi state. This is not the same thing as buying a car with 55,500 miles on it.
If you really want to do this, you could cheat I suppose...
class C {
int BadProperty {
set {
SomeMethod(value);
}
}
void SomeMethod(int value) {
// here is where you do really, really bad things
}
}
Then call it like this!
var fail = new C { BadProperty = 1 };
what if the method fails ? The basic idea is, it's just a syntactic sugar. Eric Lippert is many time asked about "Why does C# not support feature X?". His answer is always
"because no one designed, specified,
implemented, tested, documented and
shipped that feature." - Eric Lippert.
This is all about orders, the Class have to be initialized with all the fields and all declared methods, before it can be guaranteed to run a method safely.
You can call methods with named parameters, if that is what you are asking about:
someMethod(param1: "Hello World", param2: "Some Other Value");

Categories