答:
In general having a chain of mocks returning other mocks is considered a code smell in tests.

That being said, the answer of whether this is good idea is of course "it depends".

About your ParserResult object - if it is a small value object then constructing it and passing it in is probably a good idea.

If it is a large object with dependancies of its own, then mocking it would be a better option. Not mocking it would increase the coupling in your tests.

Another question to ask about the design is what is the result of ParserResult.getSegment used for? Perhaps a Tell Don't Ask style might be better, can you tell ParserResult or Parser to do something with the segment information instead of extracting it and then operating on it?

Title: Returning a mock object from a mock object

Body:
I'm trying to return an object when mocking a parser class. This is the test code using PHPUnit 3.7

```<code>    //set up the result object that I want to be returned from the call to parse method
    $parserResult= new ParserResult();
    $parserResult->setSegment('some string');

    //set up the stub Parser object
    $stubParser=$this->getMock('Parser');
    $stubParser->expects($this->any())
               ->method('parse')
               ->will($this->returnValue($parserResult));

    //injecting the stub to my client class
    $fileWriter= new FileWriter($stubParser);
    $output=$fileWriter->writeStringToFile();
</code>```

Inside my writeStringToFile() method I'm using $parserResult like this:

```<code>writeStringToFile(){
   //Some code...
    $parserResult=$parser->parse();
    $segment=$parserResult->getSegment();//that's why I set the segment in the test.
}
</code>```

Should I mock ParserResult in the first place, so that the mock returns a mock?
Is it good design for mocks to return mocks?

Is there a better approach to do this all?!


问:
Do you ever read language specs?
While trying to answer questions on SO site (particularly C++ questions) I find that most of the times one person or the other includes a quote from the standard. I myself have hardly read the language spec. Even when I try to read it, I can't get my head around the language used in the specs. So, my question to become a good developer in a particular language is it essential to read its spec and know all its dusty corners which invoke undefined/implementation defined behavior? </p>

答: I used to be the unofficial "language lawyer" for C where I used to work.  I had the official ANSI X3J11 spec, and got to answer all the weird "is it supposed to do that?"-type questions.  You definitely don't need it to do 95%+ of the coding most shops do, but it can be handy in those cases where you run into some odd corner case that the compiler manual doesn't even try to explain.</p>

ContentLicense: CC BY-SA 2.5

Title: Do you ever read language specs?


问:
Is there a 'design pattern' type listing of common algorithms?
Is there a 'design pattern' styled listing of common/popular algorithms anywhere?  Specifically, something that has a similar format along the lines of:

Algorithm Name: e.g., Quick Sort, Bubble Sort, etc.

Problem: A description of the stereotypical problem the algorithm is supposed to address

Description: Description of the solution

Implementation: Code examples of the solution

Big O Rating: Self-explanatory

Similar Algorithms: Algorithms that address the same problem in different ways, or similar problems

I really like the GoF design pattern listing style, and I think it would help me learn various algorithms better/easier if I could find a resource that was similar in terms of organization.

答: This monstrosity might suit your needs if you can afford it. It includes basically everything you listed except for implementation. It's a proper CS text rather than a programming one per se.</p>

ContentLicense: CC BY-SA 3.0


问:
MVC and delegation
I am a beginning iOS programmer and use the Model-View-Controller model as a design pattern: my model doesn't know anything about my view (in order to make it compatible with any view), my view doesn't know anything about my model so they interact via my controller. A very usual way for a view to interact with the controller is through delegation: when the user interacts with the app, my view will notify my controller, which can call some methods of my model and update my view, if necessary.

However, would it make sense to also make my controller the delegate of my model? I'm not convinced this is the way to go. It could be handy for my model to notify my controller of some process being finished, for example, or to ask for extra input of the user if it doesn't have enough information to complete the task. The downside of this, though, is that my controller would be the delegate for both my controller and my model, so there wouldn't be really a proper way to notify my model of changes in my view, and vice versa. (correct me if I'm wrong.)

Conclusion: I don't really think it's a good idea to to have my controller to be the delegate of my model, but just being the delegate of my view would be fine. Is this the way most MVC models handle? Or is there a way to have the controller be the delegate of both the controller and the model, with proper communication between them?

Like I said, I'm a beginner, so I want to do such stuff the right way immediately, rather than spending loads of hours on models that won't work anyway. :)

答:
When you talk about controllers with respect to iOS, you're often talking about view controllers -- objects that are meant to manage view hierarchies. Each "screen" in an iOS application has its own view controller, and these controllers come and go as the user navigates through the app.

The model, on the other hand, is an object or graph of objects that represent the data that the app operates on, and it doesn't change just because the user moves around in the app.

If you're going to use a view controller as your model's delegate, then, you'll want to use a view controller whose lifetime is similar to that of the model. In a navigation-based app, that usually means the root view controller, which is often the object that created the model in the first place. (Another candidate is the app delegate, which is another long-lived object that sometimes creates the model.)

There's no reason that a view controller can't be the delegate of one or more views and also of the model. Just be careful to consider the lifetime issue described above. Also, consider whether your model really needs a delegate at all, and whether delegation is the right way to convey whatever messages the model might need to send. Other options include KVO and notifications.

Title: MVC and delegation


答:
NIST has operated a website called DADS (Dictionary of Algorithms and Data Structures) at http://xlinux.nist.gov/dads/

This web site is hosted by the Information Technology Laboratory of the National Institute of Standards and Technology, in collaboration with the FASTAR group.

This is a dictionary of algorithms, algorithmic techniques, data structures, archetypal problems, and related definitions. Algorithms include common functions, such as Ackermann's function. Problems include traveling salesman and Byzantine generals. Some entries have links to implementations and more information. Index pages list entries by area and by type. The two-level index has a total download 1/20 as big as this page...

We do not include algorithms particular to business data processing, communications, operating systems or distributed algorithms, programming languages, AI, graphics, or numerical analysis: it is tough enough covering "general" algorithms and data structures...

After more than a decade at NIST, this site will move to http://www.fastar.org/dads/ and be hosted by the FASTAR group...

Title: Is there a 'design pattern' type listing of common algorithms?

Body:
Is there a 'design pattern' styled listing of common/popular algorithms anywhere?  Specifically, something that has a similar format along the lines of:

Algorithm Name: e.g., Quick Sort, Bubble Sort, etc.

Problem: A description of the stereotypical problem the algorithm is supposed to address

Description: Description of the solution

Implementation: Code examples of the solution

Big O Rating: Self-explanatory

Similar Algorithms: Algorithms that address the same problem in different ways, or similar problems

I really like the GoF design pattern listing style, and I think it would help me learn various algorithms better/easier if I could find a resource that was similar in terms of organization.


答:
Try the Stony Brook Algorithm Repository.

Note SB repository really categorizes problems rather than algorithms.

For an example of particular algorithm description, take a look at 1.1.1 Dictionaries.

Of the fields you listed, the following are there, some under different names:

Algorithm Name: name is provided as a section header.

Problem

Description: "Excerpt from The Algorithm Design Manual"

Implementation: "Implementations"

Similar Algorithms: "Related Problems"

Only Big O Rating is not there. For Dictionaries section, this makes perfect sense since there is no single rating that would reasonably match different implementations.


问:
Given a project and working with 1 other person - never worked with someone before
I'm taking a class where I work with a partner to implement the link layer of the OSI model.

I've worked programmed with a partner once before and it went bad. Is the goal to divide the work up and decides who does what or should one person code and the other person reviews and switch roles after a while?

Any tips are much appreciated. Literally I know nothing about working with a partner to program so even if it's basic please tell me.

答:
Since it's school/university you'll probably better off doing pair programming. You'll be able to both correct and learn from each other.

http://www.jamesshore.com/Agile-Book/pair_programming.html


问:
What IDE(s) or editor(s) do companies like Google, Apple, IBM, etc. use?
Even though I have quite some experience in using various tools, I still can't make up my mind whether I prefer using IDE or a simple editor for code editing.

Most IDEs I have experienced are written in Java (like Eclipse) which makes them slow and bulky. What's good about them is that it provides lots of tools.

On the other hand editors are usually VERY fast. They can also be extended to become more similar to IDEs but usually I don't do that. However, there is Sublime Text 2 which has some basic code completion built-in.

My question would be whether most Enterprise companies like Google, Apple, IBM and etc (except Microsoft because they have AMAZING IDE which, I assume, is used by MS developers) force their workers to use IDEs and whether using plain editor with external tools is considered being not professional?

P.S. Not talking about cases like Android development where working without IDE barely possible.

答:
Having worked for quite a few large companies (and government departments) over the years, I can only say that there's great variety not just between but within companies. Some leave you completely free, others have extremely rigid requirements and won't allow their people to use anything else than the "company standard". Some even go as far as to make it impossible to install anything but the standard package provided by the corporate IT department, unless you go through a lot of paperwork first to get permission to request a license to be obtained after which it is installed for you by some sysadmin flunky. <br/>
On one project I was involved in, this led to the entire rebuild of the corporate IT landscape to be done as MS Office macros because the IT department would under no condition allow the project team to install IDEs and compilers on their workstations, leaving us no other option. </p>

Body:
Having worked for quite a few large companies (and government departments) over the years, I can only say that there's great variety not just between but within companies. Some leave you completely free, others have extremely rigid requirements and won't allow their people to use anything else than the "company standard". Some even go as far as to make it impossible to install anything but the standard package provided by the corporate IT department, unless you go through a lot of paperwork first to get permission to request a license to be obtained after which it is installed for you by some sysadmin flunky.

On one project I was involved in, this led to the entire rebuild of the corporate IT landscape to be done as MS Office macros because the IT department would under no condition allow the project team to install IDEs and compilers on their workstations, leaving us no other option.


问:
How ad retargeting works?
Recently, I read that Facebook ads are moving towards retargeting and got interested deeper into subject. Essentially, retargeting is technique advertisers use that tracks purchase intent by putting cookies into your browser and when you visit another website within ad network you will see ad for item you "wanted to buy".

In order this to for, both publisher and advertiser need to work together. Publisher needs add couple of lines of javascript and publisher need to be able to read this info across sites. In most cases, javascript inserts iframe from adnetwork domain. Iframe script sets cookies for both host domain and remote adnetwork domain.

However, Same Origin policy do not let iframes read/set content from parent domain. Is there something I'm missing here? Can someone explain how this technique actually works?

答:
The javascript already calls the advertising company (through httpxml requests I guess) to serve the ads. No reason it can't also call that company to post data to their servers about where and who it's calling from (in fact they've been doing that for a long time, that's how Google amasses their gigabytes of data about your browsing behaviour).

The calculations are all done on the server, not the browser. All the browser does is send the extra information to the server of the advertising agency, together with the ip address and whatever else it can fish out of your computer (usernames, passwords, who knows what).

Title: How ad retargeting works?


答:
Part of what you will learn from this exercise is ensuring you have a good, clearly communicated design with your team mate.

Working alone you could "wing it" to some extent, by coming up with some "design" but then changing it at will, since it will only affect your own work.

Working in a team (2 or more people) means you should both work together to properly design what you are writing, and ensure that your "interfaces" or contracts are properly defined. I put "interfaces" in quotes, since they may not be proper OO interfaces, depending on the language you are using.
(In school, it's a good idea to work together on the design, whereas in the real world it will often be one person doing the design, and assigning modules out to the team)

Once you have this properly thought out design, each person in the team can then develop a part of the whole system (a class, or a discrete area of functionality), and as long as they program to the agreed interface/contract the modules of the application should slot together.

One approach you may wish to use is the Feature-Driven Development approach, which means that 1 developer is responsible for an entire feature of the whole application, and as long as it fitted into the application "core" which glued the whole application together, they were more or less free to develop it as they saw fit. (this also makes it easier for lecturers to mark it, since they can clearly see which student wrote which piece)

NB While I am a big fan of pair programming, and use it regularly in my day-to-day job, I'm not sure if I agree that it would be of benefit in this situation, since it's too easy for 1 developer to just "tune-out" of the development. This is something which I usually only recommend for a complex piece of code, that can benefit from several pairs of eyes to get right.

Title: Given a project and working with 1 other person - never worked with someone before

Body:
I'm taking a class where I work with a partner to implement the link layer of the OSI model.

I've worked programmed with a partner once before and it went bad. Is the goal to divide the work up and decides who does what or should one person code and the other person reviews and switch roles after a while?

Any tips are much appreciated. Literally I know nothing about working with a partner to program so even if it's basic please tell me.


问:
Prerequisites to compiler theory?
It's not meant to be subjective or get advice on what would be the best path to take, but an objective list of things that must be known in order for me to pick up a book on compiler theory and understand it.

What level of mathematics, and related skills are required?

答:
Use different compilers and understand what a compiler can do, as a black box, before you adventure into writing one. Try to use different compilers from command line, see what options they have and what are the effects, what do they have in common, etc.

After that, you need to know a few things:

Basic arithmetic

Data structures

Graph theory

Computer architecture

Formal languages (might or might not be covered in detail by the compiler book)

Some advanced math might be required if you adventure in code optimization

Title: Prerequisites to compiler theory?


问:
Is Reading the Spec Enough?
This question is centered around Scheme but really could be applied to any LISP or programming language in general.

Background

So I recently picked up Scheme again having toyed with it once or twice before. In order to solidify my understanding of the language, I found the Revised^5 Report on the Algorithmic Language Scheme and have been reading through that along with my compiler/interpreter's (Chicken Scheme) listed extensions/implementations.

Additionally, in order to see this applied I have been actively seeking out Scheme code in open source projects and such and tried to read and understand it.

This has been sufficient so far for me understanding the syntax of Scheme and I've completed almost all of the Ninety-nine Scheme problems (see here) as well as a decent number of Project Euler problems.

Question

While so far this hasn't been an issue and my solutions closely match those provided, am I missing out on a great part of Scheme?

Or to phrase my question more generally, does reading the specification of a language along with well written code in that language sufficient to learn from? Or are other resources, books, lectures, videos, blogs, etc necessary for the learning process as well.

答:
Would reading a book on English grammar bell you everything there is to know about using English? Of course not. It might teach you enough to get by, but you'll have a deeper appreciation if you read some Shakespeare, etc.

If you can understand enough about Scheme (or any language) from reading the spec, great! That may be all you need to know. If you're really interested in the language, though, you'll probably want to read more about it, see how other people use it, and enjoy the process of discovering more. The spec tells you what the language is and how it works, experience (your own and other people's) informs what you decide to write and how you decide to write it.

Title: Is Reading the Spec Enough?


问:
Why was Android's ContentProvider created?
The title sums up my question, but to elaborate basically what I want to understand is why the Android designers want apps that need to work with shared data to use a Content Provider rather than just accessing the SQLite database directly?

The only reason I can think of is security because certain files can by accessed only be certain processes and in that way the Content Provider is the gatekeeper that ensures each app has the proper privileges before allowing read and/or write access to the database file. Is that the primary reason why ContentProvider was created?

答: The ContentProvider also abstracts out all of the inter-process communication that is required in order to communicate with other third-party applications. Having to write this code yourself would be a huge pain.


问:
Using "Google Guava" in coding interviews
I attended a in-person interview recently and performed well. But surprisingly I got rejected. When I asked the HR for reason, he contacted the technical interviewer and told me that I was syntactically wrong while coding.

I used Google Guava for coding. So my code looked like this:

List<String> items  = Lists.newArrayList()

instead of

List<String> items  =new ArrayList<String>();

I know that the code will compile and work as expected.Is it ok to use third party libraries like Google Guava in interviews?

答:
Would adding an import at the top help in showing what lib/class you are using?</p>

```<code>import com.google.common.collect.Lists;

List<String> items = Lists.newArrayList();
</code>```

Body:
Would adding an import at the top help in showing what lib/class you are using?

import com.google.common.collect.Lists;

List<String> items = Lists.newArrayList();


问:
Is it ever ok to have an empty catch statement?
I thought about it and could not come up with an example. Why would somebody want to catch an exception and do nothing about it? Can you give an example? Maybe it is just something that should never be done.</p>

答:
It is ok in situation when some sequence must be executed no matter what with most critical piece placed at the end.

For example. In motion control communication of host to controller. In emergency situations there is a number of preparation steps to abort movement, stop trajectory generation, decelerate motors, enable breaks, disable amplifier and after this you must kill bus power. All must happen sequentially and if one of steps fails rest of steps must be executed anyway even with accepted risk of damaging hardware. Say even if all above fails, the kill bus power must happen anyway.


答:
Is the goal to divide the work up and decides who does what or should one person code and the other person reviews and switch roles after a while?

Unless your instructor explicitly told you how to share the task, it is up to you and your partner to decide. So I would start by discussing this with him/her. This includes a rough assessment of your qualities and skills - nothing bad, just to see whether you are more or less on the same level, or one of you is more skilled / experienced in some aspect of the work. This quite strongly influences your options.

If the two of you are on about the same level, probably the best is to attempt to solve at least the most fundamental tasks - fleshing out a rough design and implementing a skeleton application in code - together.* You don't need to make a shiny perfect design up front - it takes a lot of experience to succeed with this. It is better to just try to come up with ideas, discuss how the program could work the way it is expected, and if in doubt, write code to verify your ideas. The outcome of this is a skeleton, containing all the main parts of the program and capable of some very simple functionality to demonstrate that the system is working end to end. E.g. the skeleton of a word processor would be able to open a very simple file, display it in an editor window, then save it. A skeleton web server would be able to respond to the most basic HTTP GET request by sending back a "200 OK" response with some hard-coded content. Etc etc.

Once you are ready with this, you may start dividing up tasks between the two of you if you prefer so. In fact, the second main aim of creating the skeleton is to allow multiple people to work on the code in parallel. Which implies that putting everything into a single source code file is not the best idea here ;-)

One (possibly obvious) note: if you haven't used a version control system before, now is the time to start using one.

If, OTOH, one of you is noticeably more skilled / interested in some area, it may be obvious to give related task to him/her. The other may want to watch and follow though, or to get a presentation afterwards, to learn that skill too. At a later point in time, when both of you already are familiar with the basics of teamwork and solving problems, you may choose to do the opposite, letting the lesser skilled one to do a specific task in order to even out your skillset.

*Side note: This process may or may not include pair programming. If both of you are open to the idea of pair programming, why not give it a try. However, make sure that you are really working together, with both of you participating and switching roles frequently. If one of you is dominating and the other is just trying to stay awake, this does not help either of you, and just gives a bad experience.

So if you don't like the idea of pair programming, and/or you have some bad experience (as you seem to have mentioned in your post), and/or you feel it would be one thing too much to learn at this point, you may leave it off. Still you need lots of cooperation between the two of you, so make sure you meet, discuss and share your results with each other frequently.


答:
Compilers are much, much simpler than they're usually perceived. You do not need any advanced knowledge. Understanding some basics of the graph theory might help (but it is certainly not a prerequisite). Understanding the term rewriting systems would also be beneficial. But the best approach is to just start learning the compilers theory and pick up what is missing on the way.

Many things that are discussed in detail in the popular compilers textbooks are totally irrelevant to the real world practice and even to the bleeding edge modern compilers research. Chances are, you'll never need to touch the formal languages (alas, parsing is overrated). There is no need to understand the computer architecture in detail (although it might help). No complicated data structures are required, besides very simple trees and DAGs.

Title: Prerequisites to compiler theory?

Body:
It's not meant to be subjective or get advice on what would be the best path to take, but an objective list of things that must be known in order for me to pick up a book on compiler theory and understand it.

What level of mathematics, and related skills are required?


答:
Jean-Paul Sartre in his play No Exit, famously said, "Hell is other people."  Of course, for everyone on this planet, except you, you are other people, so there is a lot to work on.

Team projects in school and in the work place can be filled with challenges.  There are some helpful tools you can use:

Start early.

Create some goals for yourself about what you would like to learn and do on the project.

Spend more time that you expect selecting partners.

Keep your team small.

Understand your differences.

Seek out people with complementary strengths, contrasting ideas, diverse backgrounds.

Understand and manage group dynamics.

Understand communication and thinking styles (external - talk it through, internal - plan it out, write it down).

Pick someone who is equally serious about the class or project as you.

Work with people who have a compatible schedule.

Create a shared understanding of what the professor (or manager or scrum master) expects.

Communicate frequently.

Try to make things an equal partnership.

Don't quibble about who is working or accomplishing more.

Be attentive and accommodating.

Show appreciation early and often.

Be happy and positive about working together even if problems arise.

Expect to have tough days, so use easy days to build working relationships.

Bite your tongue if you are tempted to say things like "I hate you, I would never work with you again" because after that happens, everything will get harder and you won't have the career long friend that you should make in college.  Our business is not so large we won't make or accept job applications to/from that person later, particularly since the advent of Linked In.

If your partner is stuck, provide help.

If you are stuck, ask for help.

Use collaboration tools.

Be as aware as possible of the work others are doing.  Your interest is motivating to the other person.

Peer review each others work.  Recommend, but steer clear of criticism that is personal, permanent, or pervasive ("you always screw up everything" is not helpful).

Understand what constitutes plagiarism and take steps to insure that your work and the work of other members of your team is original and properly attributes the work of others.

Enjoy the work.

Understand what worked and what didn't.

Share the credit for the success, but don't recriminate if things didn't meet expectations.


问:
How can I bind an interface to a class decided by an xml or database configuration at the launch of the application?
I'm re-working on the design of an existing application which is build using WebForms. Currently the plan is to work it into a MVP pattern application while using Ninject as the IoC container.

The reason for Ninject to be there is that the boss had wanted a certain flexibility within the system so that we can build in different flavor of business logic in the model and let the programmer to choose which to use based on the client request, either via XML configuration or database setting.

I know that Ninject have no need for XML configuration, however I'm confused on how it can help to dynamically inject the dependency into the system?

Imagine I have a interface IMember and I need to bind this interface to the class decided by a xml or database configuration at the launch of the application, how can I achieve that?

答:
This is pretty much explained in the Ninject-wiki It has this example of doing individual bindings based on some condition:

```<code>class WeaponsModule : NinjectModule
{
   private readonly bool useMeleeWeapons;
   public WeaponsModule(bool useMeleeWeapons) {
      this.useMeleeWeapons = useMeleeWeapons;
   }

   public void Load()
   {
      if (this.useMeleeWeapons)
         Bind<IWeapon>().To<Sword>();
      else
         Bind<IWeapon>().To<Shuriken>();
   }
}

class Program
{
   public static void Main()
   {
       bool useMeleeWeapons = false;
       IKernel kernel = new StandardKernel(new WeaponsModule(useMeleeWeapons));
       Samurai warrior = kernel.Get<Samurai>();
       warrior.Attack("the evildoers");
   }
}
</code>```

If you don't need this much granularity, you could have different Modules that are loaded based on some condition.

Body:
This is pretty much explained in the Ninject-wiki It has this example of doing individual bindings based on some condition:

class WeaponsModule : NinjectModule
{
   private readonly bool useMeleeWeapons;
   public WeaponsModule(bool useMeleeWeapons) {
      this.useMeleeWeapons = useMeleeWeapons;
   }

   public void Load()
   {
      if (this.useMeleeWeapons)
         Bind<IWeapon>().To<Sword>();
      else
         Bind<IWeapon>().To<Shuriken>();
   }
}

class Program
{
   public static void Main()
   {
       bool useMeleeWeapons = false;
       IKernel kernel = new StandardKernel(new WeaponsModule(useMeleeWeapons));
       Samurai warrior = kernel.Get<Samurai>();
       warrior.Attack("the evildoers");
   }
}

If you don't need this much granularity, you could have different Modules that are loaded based on some condition.


答:
Generally, programming language specifications are not very good tutorials.  They are worded so as to be prescriptive rather than descriptive, although I think the best specifications identify discrete, separable requirements in simple, disjoint shall statements that are pretty easy to evaluate, and are further documented with a description and an example.

Bjarne Stroustrup weighs in on just this question about the recent C++ standards work in his C++ FAQ.

Be warned that the standard is not a tutorial; even expert programmers
  will do better learning about C++ and new C++ features from a
  textbook.

Title: Is Reading the Spec Enough?

Body:
This question is centered around Scheme but really could be applied to any LISP or programming language in general.

Background

So I recently picked up Scheme again having toyed with it once or twice before. In order to solidify my understanding of the language, I found the Revised^5 Report on the Algorithmic Language Scheme and have been reading through that along with my compiler/interpreter's (Chicken Scheme) listed extensions/implementations.

Additionally, in order to see this applied I have been actively seeking out Scheme code in open source projects and such and tried to read and understand it.

This has been sufficient so far for me understanding the syntax of Scheme and I've completed almost all of the Ninety-nine Scheme problems (see here) as well as a decent number of Project Euler problems.

Question

While so far this hasn't been an issue and my solutions closely match those provided, am I missing out on a great part of Scheme?

Or to phrase my question more generally, does reading the specification of a language along with well written code in that language sufficient to learn from? Or are other resources, books, lectures, videos, blogs, etc necessary for the learning process as well.


问:
Is C# development effectively inseparable from the IDE you use?
I'm a Python programmer learning C# who is trying to stop worrying and just love C# for what it is, rather than constantly comparing it back to Python.

I'm caught up on one point: the lack of explicitness about where things are defined, as detailed in this Stack Overflow question. In short: in C#, using foo doesn't tell you what names from foo are being made available, which is analogous to from foo import * in Python -- a form that is discouraged within Python coding culture for being implicit rather than the more explicit approach of from foo import bar.

I was rather struck by the Stack Overflow answers to this point from C# programmers, which was that in practice this lack of explicitness doesn't really matter because in your IDE (presumably Visual Studio) you can just hover over a name and be told by the system where the name is coming from. E.g.:

Now, in theory I realise this means when you're looking with a text editor, you can't tell where the types come from in C#... but in practice, I don't find that to be a problem. How often are you actually looking at code and can't use Visual Studio?

This is revelatory to me. Many Python programmers prefer a text editor approach to coding, using something like Sublime Text 2 or vim, where it's all about the code, plus command line tools and direct access and manipulation of folders and files. The idea of being dependent on an IDE to understand code at such a basic level seems anathema. It seems C# culture is radically different on this point. And I wonder if I just need to accept and embrace that as part of my learning of C#.

Which leads me to my question here: is C# development effectively inseparable from the IDE you use?

答:
Visual Studio is so convenient that after working with it for a while it is difficult to use a different IDE. It has a lot of handy tools and a bunch of plugins available, so practically it has every feature you would need.

On the other hand, whatever language you learn, it is recommended to use command line at the beginning, so you can better understand how it works. C# isn't an exception.

is C# development effectively inseparable from the IDE you use?

Theoretically no, but practically yes. It is possible to write in C# using a text editor and command line, but if you have Visual Studio, you'd never do this. In fact very few programmers have ever executed C# code from command line.

BTW If you feel inconvenient with using foo, you can use the whole path when using a type.


答:
The idea of being dependent on an IDE to understand code at such a basic level seems anathema.

It is not a question of understanding your code: given sufficient time, you can always locate the right variable with a basic text editor or even in a printout. As far as understanding the code goes, the IDE dependency absolutely does not exist.

Locating your references efficiently is an entirely different subject: I love the ability to find usages of Java variables in Eclipse as much as I love finding declaration points in Visual Studio, for both C# and C++. I prefer spending my time coding, rather than looking for declaration points manually. This is similar to doing math: I can multiply multidigit numbers on a piece of paper, but I prefer using calculator to save myself a minute or two.

Starting at a certain "critical size" of the code, a good IDE becomes very useful regardless of the programming language. The size may vary language to language, but once you cross several thousand lines, having an IDE helps regardless of your language. This has more to do with limitations of a human mind than with a particular programming language: at some point, your short-term memory is bound to "overflow".

There are tricks letting you increase that critical size where IDE becomes useful. For example, you could follow a naming convention (Hungarian names were big in the C++ world at some point, especially among the Windows practitioners). Another common trick is qualifying instance variables with this. even in contexts where such qualification is not required.

These tricks come with trade-offs: almost inevitably, they make your program less readable by obscuring names, or inserting the explicit references the encapsulation was intended to hide. Faced with the choice, I pick clean-looking code plus an IDE over a less-clean-looking code minus an IDE. I fully recognize, however, that other people's choices may differ from mine.

Title: Is C# development effectively inseparable from the IDE you use?

Body:
I'm a Python programmer learning C# who is trying to stop worrying and just love C# for what it is, rather than constantly comparing it back to Python.

I'm caught up on one point: the lack of explicitness about where things are defined, as detailed in this Stack Overflow question. In short: in C#, using foo doesn't tell you what names from foo are being made available, which is analogous to from foo import * in Python -- a form that is discouraged within Python coding culture for being implicit rather than the more explicit approach of from foo import bar.

I was rather struck by the Stack Overflow answers to this point from C# programmers, which was that in practice this lack of explicitness doesn't really matter because in your IDE (presumably Visual Studio) you can just hover over a name and be told by the system where the name is coming from. E.g.:

Now, in theory I realise this means when you're looking with a text editor, you can't tell where the types come from in C#... but in practice, I don't find that to be a problem. How often are you actually looking at code and can't use Visual Studio?

This is revelatory to me. Many Python programmers prefer a text editor approach to coding, using something like Sublime Text 2 or vim, where it's all about the code, plus command line tools and direct access and manipulation of folders and files. The idea of being dependent on an IDE to understand code at such a basic level seems anathema. It seems C# culture is radically different on this point. And I wonder if I just need to accept and embrace that as part of my learning of C#.

Which leads me to my question here: is C# development effectively inseparable from the IDE you use?


答:
To answer your question:  although it's slowly changing, the Microsoft development environment has largely been a monoculture.  </p>

<p>This approach has many positives and negatives, which could be argued at length (e.g. consider the pros and cons of open and closed platforms, such as PCs vs an Xbox), but at the end of the day, the tooling from Microsoft is what most people use.  The company has also shown that their decision making is often a kind of "give the most value to the majority of our users" process, always looking for practical compromises (most recently - consider Typescript).  So basically, I wouldn't be surprised to find that the development of C# was / is done with the tooling (VS) in mind.  </p>

Body:
To answer your question:  although it's slowly changing, the Microsoft development environment has largely been a monoculture.

This approach has many positives and negatives, which could be argued at length (e.g. consider the pros and cons of open and closed platforms, such as PCs vs an Xbox), but at the end of the day, the tooling from Microsoft is what most people use.  The company has also shown that their decision making is often a kind of "give the most value to the majority of our users" process, always looking for practical compromises (most recently - consider Typescript).  So basically, I wouldn't be surprised to find that the development of C# was / is done with the tooling (VS) in mind.


答: My understanding was that in Python, "everything's public" or something to that effect.  In C#, the module designer decides what is public and what isn't, so when you do an import you only get the public API anyway.  That could be a reason for the difference you're describing.


问:
Are long methods always bad?
So looking around earlier I noticed some comments about long methods being bad practice.

I am not sure I always agree that long methods are bad (and would like opinions from others).

For example I have some Django views that do a bit of processing of the objects before sending them to the view, a long method being 350 lines of code. I have my code written so that it deals with the parameters - sorting / filtering the queryset, then bit by bit does some processing on the objects my query has returned.

So the processing is mainly conditional aggregation, that has complex enough rules it can't easily be done in the database, so I have some variables declared outside the main loop then  get altered during the loop.

```<code>variable_1 = 0
variable_2 = 0
for object in queryset :
     if object.condition_condition_a and variable_2 > 0 :
     variable 1+= 1
     .....
     ...
     .
      more conditions to alter the variables

return queryset, and context
</code>```

So according to the theory I should factor out all the code into smaller methods, so That I have the view method as being maximum one page long.

However having worked on various code bases in the past, I sometimes find it makes the code less readable, when you need to constantly jump from one method to the next figuring out all the parts of it, while keeping the outermost method in your head.

I find that having a long method that is well formatted, you can see the logic more easily, as it isn't getting hidden away in inner methods.

I could factor out the code into smaller methods, but often there is is an inner loop being used for two or three things, so it would result in more complex code, or methods that don't do one thing but two or three (alternatively I could repeat inner loops for each task, but then there will be a performance hit).

So is there a case that long methods are not always bad? Is there always a case for writing methods, when they will only be used in one place?

UPDATE:
Looks like I asked this question a over a year ago.

So I refactored the code after the (mixed) response here, split it into methods. It is a Django app retrieving complex sets of related objects from the database, so the testing argument is out (it would have probably taken most of the year to create relevant objects for the test cases . I have a "this needs done yesterday" type work environment before anyone complains).
Fixing bugs in that part of the code is marginally easier now, but not massively so.

before :

```<code>#comment 1
bit of (uncomplicated) code 1a
bit of code 2a

#comment 2
bit of code 2a
bit of code 2b
bit of code 2c

#comment 3
bit of code 3
</code>```

now:

```<code>method_call_1
method_call_2
method_call_3

def method_1
    bit of (uncomplicated) code 1a
    bit of code 2a

def method_2
    bit of code 2a
    bit of code 2b
    bit of code 2c

def method_3
    bit of code 3
</code>```

答:
The point of a method is to help reduce code regurgitation. A method should have a specific function that it is responsible for. If you end up rehashing code in numerous places you run the risk of code having unexpected results if specifications the software is designed to address are changed.

For a method to have 350 lines would suggest that a lot of the tasks that it is carrying out are replicated elsewhere as it is unusual to require such a large amount of code to carry out a specialised task.

ContentLicense: CC BY-SA 4.0

Title: Are long methods always bad?


问:
Does your team function well without following a work methodology (such as scrum)?
I've worked in a number of small teams over the last 9 years. Each had the obvious good practices, such as short meetings, revision control, continuous integration software, issue tracking and so on.

In these 9 years, I've never heard much about development methodologies; for example, there's never been a "we're doing scrum", or "lets do agile", or anything more than a passing reference. All of the teams seemed to function fine, without following much process, we were just freeflowing and just naturally worked well.

Has anyone else progressed for long periods of time without encountering scrum/agile/etc?

The only exposure I've had to these is through sites like this one. I read questions like Sprint Meetings - What to talk about ... and all the talk seems to describe almost robotic like people who follow a methodology finite state machine. Is it really (though exaggerated) like that? I wonder if the  people posting on the internet just loud supporters of "best practice", with similar textbook views, not really reflecting how people work... Or that I've encountered some teams making their processes up naturally.

Furthermore (I am in the UK, which may be relevant)... I think if a methodology were introduced to any of the teams I'd work on, they'd just reject it as being silly and unnecessary... then carry on. I'd tend to agree, following processes seems a bit unnatural. Is this typical or common?

答:
Honestly, if your small team has been working without major incidents well for all these years without thinking of process, you were probably doing some form of agile.  All an agile process means is that it complies with the "Agile Manifesto" http://agilemanifesto.org/ which has surprising little to say about iterative, story boards, etc.  The very first tenant of agile is that you prefer "Individuals and interactions over processes and tools".  Any team that works well together doesn't really need to think hard about process.

The different brands of agile (like Scrum, etc.) are very useful if you have a brand new team that isn't used to working with each other.  They kind of set the framework for how to build a cohesive team, which in turn will build a cohesive product.

If what you are doing is working, keep doing it.  If you are constantly late with deliverables, having to routinely pull overtime, or having to fix major bugs after you deployed something--then something is wrong.  That's when you make a series of small changes to fix the problems.

OwnerDisplayName: Sam


答:
No, long methods are not always bad.

In the book Code Complete, it is measured that long methods are sometimes faster and easier to write, and don't lead to maintenance problems.

In fact, what is really important is to stay DRY and respect separation of concerns. Sometime, the computation is just long to write, but really won't cause issue in the future.

However, from my personal experience, most long methods tend to lack separation of concern. In fact, long methods are an easy way to detect that something MAY be wrong in the code, and that special care is required here when doing code review.

EDIT:
As comments are made, I add an interesting point to the answer. I would in fact also check complexity metrics for the function (NPATH, cyclomatic complexity or even better CRAP).

In fact, I recommend to not checking such metrics on long functions, but to include alert on them with automated tools (such as checkstyle for java for instance) ON EVERY FUNCTION.

Title: Are long methods always bad?

Body:
So looking around earlier I noticed some comments about long methods being bad practice.

I am not sure I always agree that long methods are bad (and would like opinions from others).

For example I have some Django views that do a bit of processing of the objects before sending them to the view, a long method being 350 lines of code. I have my code written so that it deals with the parameters - sorting / filtering the queryset, then bit by bit does some processing on the objects my query has returned.

So the processing is mainly conditional aggregation, that has complex enough rules it can't easily be done in the database, so I have some variables declared outside the main loop then  get altered during the loop.

```<code>variable_1 = 0
variable_2 = 0
for object in queryset :
     if object.condition_condition_a and variable_2 > 0 :
     variable 1+= 1
     .....
     ...
     .
      more conditions to alter the variables

return queryset, and context
</code>```

So according to the theory I should factor out all the code into smaller methods, so That I have the view method as being maximum one page long.

However having worked on various code bases in the past, I sometimes find it makes the code less readable, when you need to constantly jump from one method to the next figuring out all the parts of it, while keeping the outermost method in your head.

I find that having a long method that is well formatted, you can see the logic more easily, as it isn't getting hidden away in inner methods.

I could factor out the code into smaller methods, but often there is is an inner loop being used for two or three things, so it would result in more complex code, or methods that don't do one thing but two or three (alternatively I could repeat inner loops for each task, but then there will be a performance hit).

So is there a case that long methods are not always bad? Is there always a case for writing methods, when they will only be used in one place?

UPDATE:
Looks like I asked this question a over a year ago.

So I refactored the code after the (mixed) response here, split it into methods. It is a Django app retrieving complex sets of related objects from the database, so the testing argument is out (it would have probably taken most of the year to create relevant objects for the test cases . I have a "this needs done yesterday" type work environment before anyone complains).
Fixing bugs in that part of the code is marginally easier now, but not massively so.

before :

```<code>#comment 1
bit of (uncomplicated) code 1a
bit of code 2a

#comment 2
bit of code 2a
bit of code 2b
bit of code 2c

#comment 3
bit of code 3
</code>```

now:

```<code>method_call_1
method_call_2
method_call_3

def method_1
    bit of (uncomplicated) code 1a
    bit of code 2a

def method_2
    bit of code 2a
    bit of code 2b
    bit of code 2c

def method_3
    bit of code 3
</code>```


答: Long methods are always bad, but are occasionally better than the alternatives.</p>

Title: Are long methods always bad?


答:
There is something what we call Functional Decomposition implying to break up your longer methods into smaller ones wherever possible. As you mentioned that your method involves sorting / filtering then you better have separate methods or functions for these tasks.

Precisely, your method should be focussed on perforimng 1 task only.

And if it needs to call another method dor some reason then do so otherwise carry on with the one you are already writing. Also for readability pruposes, you can add comments. Conventionally, programmers use multi-line comments (/**/ in C, C++, C# and Java) for method descriptions and use single-line comments (// in C, C++, C# and Java). There are also good documentation tools available as well for greater code readability (eg. JavaDoc).
You can also look into XML based comments if you are a .Net developer.

Loops do impact program performance and may cause application overhead if not used properly. The idea is to design your algorithm in such a that you use nested loops as little as possible.

Title: Are long methods always bad?


问:
The C++ web stack, is there one?
Java would be jsps and servlets (or a framework such as Spring) running on the JVM and tomcat (or glassfish etc).

C# would be asp and C# running on dot.net framework and IIS ? (I have no experience with this please correct and improve my terminology)

Is there an equivalent for C++ ? I could happily call some C++ from a java servlet/controller but was wondering if there are existing frameworks and libraries out there specifically for creating business logic in  C++ with a web front end.

答:
C++ have nothing related to networking in it's current standard but there are works in this way.

I would recommand taking a look at:

CPPCMS (which is not a cms but you can build one with)

cpp-netlib which is a library which will be a proposal to the c++1y standard

casablanca (which is not finished yet) which is Microsoft's proposal to C++1y - I don't know if current implementation is cross-platform yet though.

So there is not something as complete as Django for Python or ROR for Ruby yet, but some people in the CPPCMS mailing list said they were working on such kind of framework. CPPCMS is certainly the closest to what you are looking for.

Title: The C++ web stack, is there one?


答:
Long methods are a code smell.  They usually indicate that something's wrong, but it's not a hard-and-fast rule.  Usually, cases where they are justified involve lots of state and fairly complex business rules (as you have found).

As to your other question, it's frequently helpful to segregate chunks of logic into separate methods, even if they're only called once.  It makes it easier to see the high-level logic and can make exception handling a little cleaner.  Just as long as you don't have to pass in twenty parameters to represent the processing state!

Title: Are long methods always bad?


答: Long methods can be more computationally and space efficient, it can be easier to see the logic and easier to debug them. However these rules only really apply when only one programmer touches that code. The code is going to be a pain to extend if it is not atomic, essentially the next person will have to start from scratch and then debugging and testing this will take for ever as it is not using any known good code.</p>

Title: Are long methods always bad?


答:
Long methods aren't always bad. They usually are a sign that there might be a problem.

On the system I'm working on we have a half a dozen or so methods that are more than 10,000 lines long. One is currently 54,830 lines long. And it's OK.

These ridiculously long functions are very simple and are autogenerated. That big 54,830 line long monster contains the daily polar motion data from January 1 1962 to January 10, 2012 (our last release). We also release a procedure by which our users can update that autogenerated file. That source file contains the polar motion data from http://data.iers.org/products/214/14443/orig/eopc04_08_IAU2000.62-now , auto-translated to C++.

Reading that web site on the fly is not possible in a secure installation. There is no connection to the outside world. Downloading the web site as a local copy and parsing in C++ isn't an option either; parsing is slow, and this has to be fast. Downloading, auto-translating to C++, and compiling: Now you have something that is fast. (Just don't compile it optimized. It's amazing how long an optimizing compiler takes to compile 50,000 lines of extremely simple straight line code. It takes over half an hour on my computer to compile that one file optimized. And the optimization accomplishes absolutely nothing. There's nothing to optimize. It's simple straight line code, one assignment statement after another.)

Title: Are long methods always bad?


答:
Most of the focus here seems to be around the word always.  Yes, absolutes are bad, and software engineering is almost as much art as it is science, and all that...  but I'm going to have to say that for the example you gave, the method would be better if it was split up.  These are the arguments I'd typically use to justify splitting up your method:

Readability: I'm not sure about others, but I can't read 350 lines of code quickly.  Yes, if it's my own code, and I can make many assumptions about it, I could skim through it very rapidly, but that's besides the point.  Consider how much easier that method would be to read, if it consisted of 10 calls to other methods (each with a descriptive name).  Doing this, you've introduced a layering in the code, and the high-level method gives a short, sweet outline to the reader regarding what's going on.

Edit - to put that in a different light, think about it is like this:  how would you explain that method to a new team member?  Surely it has some structure that you can summarise along the lines of "well, it starts off doing A, then B, then sometimes C, etc".  Having a short "overview" method calling other methods makes this structure obvious.  It's exceedingly rare to find 350 lines of code which do not benefit; the human brain is not meant to be dealing with lists 100s of items long, we group them.

Reusability: Long methods tend to have low cohesion - they often do more than one thing.  Low cohesion is the enemy of reuse; if you combine multiple tasks into one method, it's going to end up being re-used in fewer places than it should have been.

Testability and cohesion: I mentioned cyclomatic complexity in a comment above - it's a pretty good measure of how complex your method is.  It represents the lower bound of number of unique paths through your code, depending on the inputs (edit: corrected as per MichaelT's comment).  It also means that to properly test your method, you'd need to have at least as many test cases as your cyclomatic complexity number.  Unfortunately, when you put together pieces of code that aren't really dependent on each other, there's no way to be sure of this lack of dependency, and the complexity tends to multiply together.  You can think of this measure as an indication of the number of different things you are trying to do.  If it's too high, it's time to divide and conquer.

Refactoring and structure: Long methods are often signs that some structure is lacking in the code.  Often, the developer couldn't figure out what the commonalities are between the different parts of that method, and where a line could be drawn between them.  Realising that a long method is a problem, and trying to split it into smaller methods is the first step on a longer road to actually identifying a better structure for the whole thing.  Perhaps you need to create a class or two; it's not necessarily going to be more complex in the end!

I also think that in this case, the excuse for having a long method is "... some variables declared outside the main loop then get altered during the loop".  I'm not an expert on Python, but I'm fairly certain that this problem could be trivially fixed by some form of passing by reference.

Title: Are long methods always bad?


问:
What are unique aspects of a software Lifecycle of an attack/tool on a software vulnerability?
At my local university, there is a small student computing club of about 20 students.  The club has several small teams with specific areas of focus, such as mobile development, robotics, game development, and hacking / security.

I am introducing some basic agile development concepts to a couple of the teams, such as user stories, estimating complexity of tasks, and continuous integration for version control and automated builds/testing.

I am familiar with some basic development life-cycles, such as waterfall, spiral, RUP, agile, etc., but I am wondering if there is such a thing as a software development life-cycle for hacking / breaching security.  Surely, hackers are writing computer code, but what is the life-cycle of that code?  I don't think that they would be too concerned with maintenance, as once the breach has been found and patched, the code that exploited that breach is useless.

I imagine the life-cycle would be something like:

Find gap in security

Exploit gap in security

Procure payload

Utilize payload

What kind of differences (if any) are there for the development life-cycle of software when the purpose of the product is to breach security?

答:
Life-Cyle is never code dependent. It is rather dependent upon other factors like:

Time

Budget

Nature of Customer

Nature of Product

In your scenario, the Agile Life Cyle methodology would be most useful. Reason being that you need to involve your customer during development and have to verify the acceptable quality parameters of your product. Agile Methodology would help you immensely to improve your Hacking Software via gathering your customer's feedback and then gradually working on incremental basis.


答:
I don't see why there should be any specifically different development life-cycle depending on the purpose of the product.

Software that is developed to breach security can have as long a life as any other type of software and will require the same amount of maintenance and work.

Different creators of such software will adopt different life-cycles depending on their needs.

Title: What are unique aspects of a software Lifecycle of an attack/tool on a software vulnerability?

Body:
At my local university, there is a small student computing club of about 20 students.  The club has several small teams with specific areas of focus, such as mobile development, robotics, game development, and hacking / security.

I am introducing some basic agile development concepts to a couple of the teams, such as user stories, estimating complexity of tasks, and continuous integration for version control and automated builds/testing.

I am familiar with some basic development life-cycles, such as waterfall, spiral, RUP, agile, etc., but I am wondering if there is such a thing as a software development life-cycle for hacking / breaching security.  Surely, hackers are writing computer code, but what is the life-cycle of that code?  I don't think that they would be too concerned with maintenance, as once the breach has been found and patched, the code that exploited that breach is useless.

I imagine the life-cycle would be something like:

Find gap in security

Exploit gap in security

Procure payload

Utilize payload

What kind of differences (if any) are there for the development life-cycle of software when the purpose of the product is to breach security?


答:
The development models that you specify are just that - development models. They are extremely useful when you are doing engineering development - when you have requirements, when you have to create or modify system architectures or component designs, when you need to build or modify a product and associated tests, and when you release to a customer.

I'm not sure that these models can be directly applied to more research-oriented projects, where you are trying to answer questions or learn more about a system (or the system's security weaknesses, in your particular case).

I would suspect that the iterative/incremental models, such as the agile methods and the Spiral model would be the most useful to form a basis. In each iteration, you can work toward answering questions or defining more parameters to work with, which might or might not include writing any code. Perhaps various scientific research methods might also provide an interesting foundation.


答:
Hacking has recently seen a strong professionalization, away from single hackers doing it "for the lulz" or to gain fame, towards collaboration between specialists with the goal of making money. The result have been fully-fledged commercial "hacking kits" like the Blackhole exploit kit where specific software weaknesses can be easily integrated like plugins. I'd assume that such products are developed pretty much exactly like any other software products.

There is also apparently a developing market for zero-day exploits.


问:
Would Using a PHP Framework Be Beneficial in My Context?
I've just started work at a small start-up company who mainly uses PHP to develop their front-end apps. I had no prior PHP experience before joining, and this has led to my apps becoming large pieces of spaghetti code. I essentially started by adding code to implement an initial feature, and then continued to hack in more code to implement further features – without much thought for the overall design.

The apps themselves output XML to render on small mobile devices.

I recently started looking into frameworks that I could use. I reckon an advantage would be that they seem to force developers to modularise their programs using good-practice design patterns. This seems great for someone in my position. The extra functions they provide, for example: interfacing with databases in such a way as to make SQL injection impossible, would be very useful too.

The downside I can see is that there will be a lot of overhead for me in terms of the time taken to learn the framework itself (while still getting to grips with PHP itself). I'm also worried that it will be overkill for the scale of the apps we develop. They tend to be programs that interface with a fairly simple back-end DB, and will generate about 5 different XML screens. Probably around 1 or 2 thousand lines of code. The time it takes just to configure the frameworks may not be worth it. The final problem I can see is that developers in the company – who have to go over my code, and who do not know the PHP framework I may use – will have a much harder time understanding it.

Given those pros and cons, I'm still not sure on what the best course of action will be; so any advice will be greatly appreciated.

答:
The first step should be to consult the more experienced PHP developers at your company. Possibly they already use some framework, or at least have a standard pattern for code organization. They might be able to guide you to a framework that's particularly suitable for your app.

Personally, being new to the development environment, I wouldn't feel comfortable making a unilateral decision to use a new framework.


答:
Let's just say there are good and bad ways to break up a long method.  Having to "[keep] the outermost method in your head" is a sign that you're not breaking it up in the most optimal way, or that your submethods are poorly named.  In theory, there are instances where a long method is better.  In practice, it's extremely rare.  If you can't figure out how to make a shorter method readable, get someone to review your code, and ask them specifically for ideas on shortening the methods.

As for multiple loops causing a supposed performance hit, there's no way to know that without measuring.  Multiple smaller loops can be significantly faster if it means everything it needs can stay in cache.  Even if there is a performance hit, it's usually negligible in favor of readability.

I will say that often long methods are easier to write, even though they're more difficult to read.  That's why they proliferate even though no one likes them.  There's nothing wrong with planning from the start to refactor before you check it in.

Title: Are long methods always bad?


问:
Do you ever read language specs?
While trying to answer questions on SO site (particularly C++ questions) I find that most of the times one person or the other includes a quote from the standard. I myself have hardly read the language spec. Even when I try to read it, I can't get my head around the language used in the specs. So, my question to become a good developer in a particular language is it essential to read its spec and know all its dusty corners which invoke undefined/implementation defined behavior? </p>

答:
Depends how big the Spec is. The C# Spec is big and has a lot of complicated language, so I've never read it.

I did learn C# through the usual ways of Experimenting and Googling and only after I got a good understanding I read small parts in the spec, mainly about Bitwise operators because I needed it.

At some point I decided that I want to write a compiler for .net, so I did read large parts of the CIL/CLR spec (and forgot about most of it again).

On the other hand, I did read the Lua spec prior to using it, mainly because it was cheap ($17 as a printed book) and very small, with only ~100 pages that are also written in 'easier' english.

But then again, Lua is much much simpler than C#.

Title: Do you ever read language specs?


问:
Is it a bad practice to write shell script with many if-else statment and for loops?
I am maintaing several data process shell scripts which are full of if-else statements and for loops . I try to make the scritps tidy and easy to debug.

When I read some suggestions about shell code best practice, it seems that is is not a best practice to have many if-else and for loop statements.

So what should I do, to write a python or c++ script instead of those logical process?

答:
As a perl coder (this could easily be adjusted to python) I have heard said and said myself "any shell script longer than 10 lines should be a perl script."  Shell scripts above a certain threshold in size/complexity often become nightmarish to maintain.  Switching to a preferred scripting language can drastically simplify this (and get away from using repeated calls grep, awk, and sed (or other lesser known applications).

Language choice aside, another comment I have heard is "if the function requires the word 'and' to describe its functionality, it is too big/complex." It isn't a problem to have nested statements, but if the logic around the statements becomes complex one should consider to extract parts of it so that it is something one can keep in their head while debugging and be able to simply test the functionality of it.


答:
It's not really the long methods that are bad practice it's more leaving them like that that is bad.

I mean that the actual act of refactoring your sample from:

```<code>varaible_1 = 0
variable_2 = 0
for object in queryset :
     if object.condition_condition_a and variable_2 > 0 :
     variable 1+= 1
     .....
     ...
     .
      more conditions to alter the variables

return queryset, and context
</code>```

to

```<code>Status status = new Status();
status.variable1 = 0;
status.variable2 = 0;
for object in queryset :
     if object.condition_condition_a and status.variable2 > 0 :
     status.variable1 += 1
     .....
     ...
     .
      more conditions to alter the variables (status)

return queryset, and context
</code>```

and then to

```<code>class Status {
    variable1 = 0;
    variable2 = 0;

    void update(object) {
        if object.condition_condition_a and variable2 > 0 {
            variable1 += 1
        }
    }
};

Status status = new Status();
for object in queryset :
     status.update(object);
     .....
     ...
     .
      more conditions to alter the variables (status)

return queryset, and context
</code>```

you are now well on the way to not just a much shorter method but a much more useable and understandable one.

Title: Are long methods always bad?

Body:
It's not really the long methods that are bad practice it's more leaving them like that that is bad.

I mean that the actual act of refactoring your sample from:

varaible_1 = 0
variable_2 = 0
for object in queryset :
     if object.condition_condition_a and variable_2 > 0 :
     variable 1+= 1
     .....
     ...
     .
      more conditions to alter the variables

return queryset, and context

to

Status status = new Status();
status.variable1 = 0;
status.variable2 = 0;
for object in queryset :
     if object.condition_condition_a and status.variable2 > 0 :
     status.variable1 += 1
     .....
     ...
     .
      more conditions to alter the variables (status)

return queryset, and context

and then to

class Status {
    variable1 = 0;
    variable2 = 0;

    void update(object) {
        if object.condition_condition_a and variable2 > 0 {
            variable1 += 1
        }
    }
};

Status status = new Status();
for object in queryset :
     status.update(object);
     .....
     ...
     .
      more conditions to alter the variables (status)

return queryset, and context

you are now well on the way to not just a much shorter method but a much more useable and understandable one.


问:
How to visualize the design of a program in order to communicate it to others
I am (re-)designing some packages for R, and I am currently working out the necessary functions, objects, both internal and for the interface with the user. I have documented the individual functions and objects.

So I have the description of all the little parts. Now I need to give an overview of how the parts fit together. The scheme of the motor so to say.

I've started with making some flowchart-like graphs in Visio, but that quickly became a clumsy and useless collection of boxes, arrrows and-what-not. So hence the question:

Is there specific software you can use for vizualizing the design of your program

If so, care to share some tips on how to do this most efficiently

If not, how do other designers create the scheme of their programs and communicate that to others?

Edit: I am NOT asking how to explain complex processes to somebody, nor asking how to illustrate programming logic. I am asking how to communicate the design of a program/package, i.e.:

the objects (with key features and representation if possible)

the related functions (with arguments and function if possible)

the interrelation between the functions at the interface and the internal functions (I'm talking about an extension package for a scripting language, keep that in mind)

So something like this :

But better. This is (part of) the interrelations between functions in the old package that I'm now redesigning for obvious reasons :-)

PS : I made that graph myself, using code extraction tools on the source and feeding the interrelation matrix to yEd Graph Editor.

答:
There are a variety of tools to convey the design of a program in general. Tools like UML and Object Diagram should be sufficient for you.

Also include comments in your code as and when needed.


答:
Is there specific software you can use for vizualizing the design of your program

Where I work, we use Visio, mostly.

If so, care to share some tips on how to do this most efficiently

With flowcharts, for program flow. For program organization, UML-like (probably not strictly conformant to UML standards, but no one's too worried about that ;) ) diagrams are used.

For diagrams as complex as yours, using a tool to generate a full-system diagram such as this might be a good starting point, just to get a feel for what things look like, but I'd suggest breaking it up into many smaller diagrams, maybe one for each subsystem, which you seem to have surrounded with a box. Links to other subsystems should not point to the modules within those systems, just the name of the subsystem. In fact, I think in Visio it's even possible to create links between diagram pages so if someone clicks on the link that goes from one complex module to another, they'll be taken straight to that module. It might also help to create a diagram at a higher level - something that shows the interactions between each subsystem, and ignores each lower-level module.

I'd follow a similar divide-and-conquer strategy for flowchart diagrams of this system.

Trying to diagram a system this large in a single diagram is difficult and if the result is too complicated, it might well be useless. I have seen it done, but it's difficult to get it right, and they had to print it on special poster-sized paper for it to be readable. It was posted along 4 corridor-facing cubicle walls and it got annoying when a pack of analysts would gather around it discussing possible changes and impacts. By the end of the project it was covered in pen, pencil, and highlighter markup...

Title: How to visualize the design of a program in order to communicate it to others

Body:
I am (re-)designing some packages for R, and I am currently working out the necessary functions, objects, both internal and for the interface with the user. I have documented the individual functions and objects.

So I have the description of all the little parts. Now I need to give an overview of how the parts fit together. The scheme of the motor so to say.

I've started with making some flowchart-like graphs in Visio, but that quickly became a clumsy and useless collection of boxes, arrrows and-what-not. So hence the question:

Is there specific software you can use for vizualizing the design of your program

If so, care to share some tips on how to do this most efficiently

If not, how do other designers create the scheme of their programs and communicate that to others?

Edit: I am NOT asking how to explain complex processes to somebody, nor asking how to illustrate programming logic. I am asking how to communicate the design of a program/package, i.e.:

the objects (with key features and representation if possible)

the related functions (with arguments and function if possible)

the interrelation between the functions at the interface and the internal functions (I'm talking about an extension package for a scripting language, keep that in mind)

So something like this :

But better. This is (part of) the interrelations between functions in the old package that I'm now redesigning for obvious reasons :-)

PS : I made that graph myself, using code extraction tools on the source and feeding the interrelation matrix to yEd Graph Editor.


答:
is C# development effectively inseparable from the IDE you use?

At my previous job I was mostly using vim to code in languages such as C#, JavaScript, Powershell, Perl, C++, and quite a few developers used to do something similar. The project was just too big for Visual Studio.

That said, most C# developers deal with much smaller projects and are quite happy to use VS.


答:
Separate the graph into multiple simple, smaller ones. One should be a general overview of the key parts, another would show the interaction between two or three parts, then a graph showing one module in detail.  I personally prefer hand drawn non-formal graphs.

Each should come with a textual description and reasons behind the (re)design. Creating a FAQ at the end of the document could be helpful too (try to collect questions from people who are encountering the system for the first time).


问:
How important is the ability to touch-type?
Did you learn to touch-type when you were already working as a programmer?  If so how did it affect your productivity?  Or are you still unable to touch type and do you think it holds you back?

According to Steve Yegge it is essential,

Personally I did not notice much difference, possibly because I was spending less than 25% of my work time actually typing (I was working on a large legacy project at the time and I was spending more time on reading and debugging existing code.)

答:
Worrying about it doesn't help. Way back when, I read some book on it, and it told me where my fingers should be when "at rest", namely ASDF and JKL:. Then it's just a matter of moving the closest finger to the letter you need. I still don't have the top row down pat. Then, don't worry about it. The speed just comes, all by itself.

There was a program, "Mavis Beacon Teaches Typing". You're driving a car, and the faster you type, the faster the car goes, and when you make a mistake, a bug splats on your windsheild. That was a lot of fun and helped a lot.


问:
Looking for some OO design advice
I'm developing an app that will be used to open and close valves in an industrial environment, and was thinking of something simple like this:-

```<code>public static void ValveController
{
    public static void OpenValve(string valveName)
    {
        // Implementation to open the valve
    }

    public static void CloseValve(string valveName)
    {
        // Implementation to close the valve
    }
}
</code>```

(The implementation would write a few bytes of data to the serial port to control the valve - an "address" derived from the valve name, and either a "1" or "0" to open or close the valve).

Another dev asked whether we should instead create a separate class for each physical valve, of which there are dozens. I agree it would be nicer to write code like PlasmaValve.Open() rather than ValveController.OpenValve("plasma"), but is this overkill?

Also, I was wondering how best to tackle the design with a couple of hypothetical future requirements in mind:-

We are asked to support a new type of valve requiring different values to open and close it (not 0 and 1).

We are asked to support a valve that can be set to any position from 0-100, rather than simply "open" or "closed".

Normally I would use inheritance for this kind of thing, but I've recently started to get my head around "composition over inheritance" and wonder if there is a slicker solution to be had using composition?

答:
If each instance of the valve object would run the same code as this ValveController, then it seems like multiple instances of a single class would be the right way to go. In this case just configure which valve it controls(and how) in the valve object's constructor.

However if each valve control needs different code to run, and the current  ValveController is running a giant switch statement that does different things depending on the type of valve, then you have reimplemented polymorphism poorly. In that case rewrite it to multiple classes with a common base(if that makes sense) and let the single responsibility principle be your design guide.

Title: Looking for some OO design advice


问:
Hiring developers - listing IDE as a requirement?
I've been looking at some job postings and noticed that a fair amount of them list IDEs under the 'required skills' section, even for senior positions. This is not localized to one company either, but rather it's something that comes up once in every few postings.

I am perplexed by this job requirement, as my mentors and some of the best coders I've seen in my life were VIM/Emacs ninjas. Similarly, when I work with people I don't much care what tools they use as long as they are productive on the team.

Can someone please explain the rationale behind hiring managers making IDEs an official job requirement?

答:
In some companies the use of an IDE is standardized.

They expect all coders to use the same IDE and therefore are looking for candidates that are proficient in using it.

Some IDEs provide integrated debugging, code completions, templates, source control and more features, and as such a company may want to ensure an incoming developer known how to use the IDE effectively.

Having said that, most of the time knowing an IDE is not a hard requirement, just a nice to have, as far as the hiring managers and team are concerned. If these are listed as a "must have", I suspect the hand of people who do not code for a living (HR, recruiters etc...).


答: If the organization has standardized on a singular IDE or development environment, then they might call that out in the job description/posting since it's a skill that would separate one candidate from another during the screening and interviewing process. However, just because it's a requirement doesn't mean that it's really a requirement and companies might hire someone who doesn't meet every single identified "requirement".</p>

Title: Hiring developers - listing IDE as a requirement?

Body:
I've been looking at some job postings and noticed that a fair amount of them list IDEs under the 'required skills' section, even for senior positions. This is not localized to one company either, but rather it's something that comes up once in every few postings.

I am perplexed by this job requirement, as my mentors and some of the best coders I've seen in my life were VIM/Emacs ninjas. Similarly, when I work with people I don't much care what tools they use as long as they are productive on the team.

Can someone please explain the rationale behind hiring managers making IDEs an official job requirement?


答:
Perhaps they use a very specific IDE (provided by a niche-market vendor for niche-market technologies - I think some SAP tools might count in this area) that takes some time to get good with and they don't have time to wait for a new hire to catch up. Perhaps they do a lot of tooling/scripting specific to an IDE so they need people with that skill.

I've never actually run into these situtions myself (where IDE was listed as a must-have; I've seen it often under the "nice-to-have" skills section on a job posting), and I've never heard of such a thing being a show-stopper in the hiring process. But that's just my experience...


答: The company may have custom extensions or plug-ins specific to a particular IDE, or more often simply have their workflow defined in terms of IDE capabilities.  For example, their standard build tool may directly consume an IDE's project file, or depend on some particular directory structure.  They may also have coding standards that are enforced or checked using a specific IDE option or plug-in.</p>


答:
I wouldn't read too far into it.

Larger organizations tend to have separate HR and development departments.  HR generally has little to no understanding of what the development teams actually need in a candidate, and likewise with the hiring manager understanding what HR needs to vet candidates.

So silly things like an IDE become part of the official requirements as it's a concrete measure HR can filter against.

If it comes up during the interview, and the hiring manager can't provide a particular reason why XYZ IDE must be used for development in their shop, then consider that a red flag.


答:
I can give you one scenario... I work for a large financial corporation. We have a list of "approved" sofware that we are allowed to install on our machines. That includes development environments. It is a security issue; helps then keep track of possible problems with individual PCs and laptops.

When hiring, the managers have to take into account what IDEs will be available to new employees and of course, if they are nor experienced with what is available, they won't do much good.


答:
My major gripe is using strings for the parameter identifying the valve.

At least create a Valve class which has a getAddress in the form the underlying implementation needs and pass those to the ValveController and ensure that you can't create nonexistent valves. This way you won't have to handle wrong strings in each of the open and close method.

Whether you create convenience methods that call the open and close in ValveController is up to you, but to be honest I would keep all the communication to the serial port (including the encoding) in a single class which other classes will call when needed. This means that when you need to migrate to a new controller you only need to modify one class.

If you like testing you should also make ValveController a singleton so you can mock it (or create a training machine for the operators).

Title: Looking for some OO design advice

Body:
I'm developing an app that will be used to open and close valves in an industrial environment, and was thinking of something simple like this:-

```<code>public static void ValveController
{
    public static void OpenValve(string valveName)
    {
        // Implementation to open the valve
    }

    public static void CloseValve(string valveName)
    {
        // Implementation to close the valve
    }
}
</code>```

(The implementation would write a few bytes of data to the serial port to control the valve - an "address" derived from the valve name, and either a "1" or "0" to open or close the valve).

Another dev asked whether we should instead create a separate class for each physical valve, of which there are dozens. I agree it would be nicer to write code like PlasmaValve.Open() rather than ValveController.OpenValve("plasma"), but is this overkill?

Also, I was wondering how best to tackle the design with a couple of hypothetical future requirements in mind:-

We are asked to support a new type of valve requiring different values to open and close it (not 0 and 1).

We are asked to support a valve that can be set to any position from 0-100, rather than simply "open" or "closed".

Normally I would use inheritance for this kind of thing, but I've recently started to get my head around "composition over inheritance" and wonder if there is a slicker solution to be had using composition?


问:
Doesn't "if (0 == value) ..." do more harm than good?
This is one of the things that I hate most when I see it in someone else's code. I know what it means and why some people do it this way ("what if I accidentally put '=' instead?"). For me it's very much like when a child goes down the stairs counting the steps out loud.

Anyway, here are my arguments against it:

It disrupts the natural flow of reading the program code. We, humans, say "if value is zero" and not "if zero is value".

Modern compilers warn you when you have an assignment in your condition, or actually if your condition consists of just that assignment, which, yes, looks suspicious anyway

You shouldn't forget to put double '=' when you are comparing values if you are a programmer. You may as well forget to put "!" when testing non-equality.

答:
Ah, yes, "Yoda conditionals"  ("If zero the value is, execute this code you must!").  I always point anyone who claims they're "better" at tools like lint(1).  This particular problem has been solved since the late 70s.  Most modern languages won't even compile an expression like if(x = 10), as they refuse to coerce the result of the assignment to a boolean.

As others have said, it certainly isn't a problem, but it does provoke a bit of cognitive dissonance.


答:
What type of code are you talking about?

There are many security tools used in the process of hacking, including scanners like nmap, sqlmap, Nessus and many others. I would imagine they have the same type of software life-cycles like any other applications.

On the other hand, there are exploit codes. Codes written to take advantage of a very specific exploit & situation. I very much doubt those need any life-cycle at all. However, many exploit codes are also integrated with a larger exploitation framework like Metasploit.

After a discussion with @AviD, I would like to add in a few points.

It will be very different for specific situations.

Some exploit codes might be rushed out to take into account the window before the zero-day is patched. Code might be rushed out for other reasons as well. See: CRIME - How to beat the BEAST successor? for a great example of this. A person wrote a piece of PoC code to quickly prove his point. No software lifecycle methodology is taken into account for codes like this.

Weaponized malware like stuxnet or FLAME probably do. Packaged software like Metasploit do.

So the right answer is... it depends.


答:
For one, C# is not Python.. There are different design methodologies.

Now, to answer your question, it's completely possible to use your Python-esque using statements.

```<code>using FooBar=MyName.Foo.FooBar;
</code>```

It's just it is definitely not the norm because it's not nearly so easy. However, I think you should worry less about knowing exactly where exactly each class is coming from. I don't understand the entire point of doing it this way in Python though.

And also, C# is a language that lends itself very well to using IDEs to make it easier. Intellisense is amazingly simple to implement, especially compared to dynamic languages such as Ruby and Python. However, you don't have to be stuck to your IDE. I've heard of people using Eclipse. There also is of course MonoDevelop(which I use quite a lot), and you can even work from a command line. On my server sometimes, I'll be editing C# files with vi and then using xbuild to rebuild it... It's just that using an IDE makes things much easier compared to the command line for typical cases.

Body:
For one, C# is not Python.. There are different design methodologies.

Now, to answer your question, it's completely possible to use your Python-esque using statements.

using FooBar=MyName.Foo.FooBar;

It's just it is definitely not the norm because it's not nearly so easy. However, I think you should worry less about knowing exactly where exactly each class is coming from. I don't understand the entire point of doing it this way in Python though.

And also, C# is a language that lends itself very well to using IDEs to make it easier. Intellisense is amazingly simple to implement, especially compared to dynamic languages such as Ruby and Python. However, you don't have to be stuck to your IDE. I've heard of people using Eclipse. There also is of course MonoDevelop(which I use quite a lot), and you can even work from a command line. On my server sometimes, I'll be editing C# files with vi and then using xbuild to rebuild it... It's just that using an IDE makes things much easier compared to the command line for typical cases.


答: I heard some about Wt (www.webtoolkit.eu) and CAS (cas.havoc.ru), but never used them. CAS is used by Yandex internally, as I heard.</p>

Title: The C++ web stack, is there one?

Body:
Java would be jsps and servlets (or a framework such as Spring) running on the JVM and tomcat (or glassfish etc).

C# would be asp and C# running on dot.net framework and IIS ? (I have no experience with this please correct and improve my terminology)

Is there an equivalent for C++ ? I could happily call some C++ from a java servlet/controller but was wondering if there are existing frameworks and libraries out there specifically for creating business logic in  C++ with a web front end.


答:
I think the fact that the method is very long is something to check on, but definitely not an instant anti-pattern. The big thing to look for in huge methods is lots of nesting. If you have

```<code>foreach(var x in y)
{
    //do ALL the things
    //....
}
</code>```

and the body of the loop isn't extremely localized(ie, you could send it less than 4 parameters), then it's probably better to convert it to:

```<code>foreach(var x in y)
{
    DoAllTheThings(x);
}
...
void DoAllTheThings(object x)
{
    //do ALL the things
    //....
}
</code>```

In turn, this can vastly reduce the length of a function. Also, make sure to look for duplicate code in the function and move that into a separate function

Finally, some methods are just long and complicated and there is nothing you can do. Some problems need solutions that do not lend themselves to easy to code. For instance, parsing against a grammar of much complexity can make really long methods that you really can't do much about without making it worse.

Title: Are long methods always bad?

Body:
I think the fact that the method is very long is something to check on, but definitely not an instant anti-pattern. The big thing to look for in huge methods is lots of nesting. If you have

foreach(var x in y)
{
    //do ALL the things
    //....
}

and the body of the loop isn't extremely localized(ie, you could send it less than 4 parameters), then it's probably better to convert it to:

foreach(var x in y)
{
    DoAllTheThings(x);
}
...
void DoAllTheThings(object x)
{
    //do ALL the things
    //....
}

In turn, this can vastly reduce the length of a function. Also, make sure to look for duplicate code in the function and move that into a separate function

Finally, some methods are just long and complicated and there is nothing you can do. Some problems need solutions that do not lend themselves to easy to code. For instance, parsing against a grammar of much complexity can make really long methods that you really can't do much about without making it worse.