问:
How to manage and estimate unstructured requirements received from customers
A lot of the times during the bidding phase of a project I receive a software system's requirements from our potential customers in a very unstructured format from various sources [email, word documents, excel]. It is usually a bunch of "product development" guys from the customer's side who come up with these "proposed solutions" to the business problems they have. While they are the experts at the business domain, a lot of the times they don't have the solutions right.

This results in

multiple versions of the same requirement

mixing up of two requirements into one

a few versions of the requirement later down the line, the
requirements which were combined together get separated out again,
each taking with it some of the new additions

How do you work with such requirements coming in and sort them out into proper use cases and before development begins? What tools can we use to track a particular requirement's history, from the first time it was conceived till the time it gets crystallized into a proper use case? Estimating work against requirements received in such a fashion is a nightmare which ends up in making mistakes in understanding the requirement correctly and estimating the effort against it correctly.

Once we win the project, then the customers have given some more thought to their requirements and have been able to articulate it properly. What happens in this case is that some functionality gets dropped, some enhanced, some take a whole new turn. This basically can nullify some of the work item's estimates that were made before the project was won. I would be interested in knowing if there is any system by which we can build a tree of a particular requirement and how each branch resulted in a different estimate.

Any tips, tools, tricks to make this activity more manageable? I'm just trying to get some insights from someone more experienced than I am in requirements management and effort estimation.

答:
I would look at this as an iterative process. Step 1 is to gather requirements. Step 2 is to sort them. Step 3 is to prioritize them. Step 4 is the break each down into small enough bits to estimate effort. Step 5 is to coalesce these bits into a global effort bucket (let's say 84 person-days). Step 6 is to map the effort to resources (84 person-days / 2 devs = 42 days).

So right now you are stuck between step 1 and step 2. You have requirements, but you don't have them in the form you need.

Say you have multiple versions of the same requirement. Are these essentially the same? If so, pick what appears to be the clearest and use it. If they vary in details, pick what seem to be the most logical and use that one. Then send a message to the client asking them to verify the requirement. You may have to go back-and-forth and number of times to get the requirement right. Don't give up or get discouraged. Many a project has failed due to poor requirements.

Use Microsoft project to keep the work and schedule in synch with the changing requirements. If the client requests a change, spec out the additional work, plug that into your model, and tell them about the new date. Don't get sucked into believing you can just bring on new devs at random intervals to pick up the slack. Your schedule must account for ramp up time whenever a new resource is added. You'll only be able to model this properly if you pay attention to each project and learn from it. Say you brought Bob on board project X after it was churning along for 4 months. How productive was he in the 1st month? The 3rd?

You should revisit the project model weekly, making updates wherever required. Keep a historical record of the changes. This will help you provide better estimates in the future.

doug


问:
Why make the login page to a single page application a separate page?
I am wondering why it seems to be popular to have the login page of an SPA be a separate page that is not part of the SPA (as in loaded and send data through ajax requests)?

The only thing I can think of is security, but I can't think a specific security reason.  I mean the only thing that comes to mind is that if your login page is part of the SPA, it sends the username/password through ajax which can be seen by such tools like firebug or web inspector; however, even if you send it as a normal POST request, there are other tools that can easily capture this data (like fiddler, httpscoop, etc.).

Is there something I am missing?

答:
I think there are some reasonable arguments for or against, and i'd say technology also plays a role in the decision.

One could argue having a separate login "page" enables the use of "Directory Security". Generally anyone can see the login "page", but only authenticated users can view the application "page"'s and it's "directory". Route's can also be locked down, where /Account/ is different than /App/ and each has it's own security "profile".

Also, if you're using a SPA approach and you're mixing authentication with application experience the logic could get convoluted. Instead of assuming the user is "logged in because they're here", you have to constantly check their authentication status and ask "should this user be here".

Also, the login page is generally on the consumer facing site.. you go to www.yourapp.com and it has some about info, contact, support, etc.. and a "login" page.. from the login page, after authentication, you could redirect to a whole host of targets..

The reason i keep a separate login page, and why I actually have an entirely different app for my "consumer facing" site is because i can expose very little to the unauthenticated. By chance some moron starts banging on my login page, i don’t want that to affect the app side of things.. even if the login is only doing a simple auth lookup.. it kind of helps me keep the bozo's from affecting my users experience.. Worst case, my consumer site goes down and no one can login, but at least the logged in users wont know and their experience wont start slowing.. I'm not saying that's the bullet proof choice.. but at least i've isolated the risk to the unauthenticated area..

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
REST API rule about tunneling
Just read this in the REST API Rulebook: GET and POST must not be used to tunnel other request methods.

Tunneling refers to any abuse of HTTP that masks or misrepresents a message’s intent and undermines the protocol’s transparency. A REST API must not compromise its design by misusing HTTP’s request methods in an effort to accommodate clients with limited HTTP vocabulary. Always make proper use of the HTTP methods as specified by the rules in this section. [highlights by me]

But then a lot of frameworks use tunneling to expose REST interfaces via HTML forms, since <form> knows only about GET and POST. My most recent example is a MethodRewriteMiddleware for flask (submitted by the author of the framework): http://flask.pocoo.org/snippets/38/.

Any ways to comply to the "Rule" without hacks or add-ons in web frameworks?

答:
No, there isn't. So if you need to, break the rule anyway.

I don't know what the big deal is. Protocols encapsulate other protocols all the time. TCP/IP for example has four layers of such abstraction.

Of course, the better path is for clients to get with the program and support the HTTP verbs properly. But it's not a perfect world.

Title: REST API rule about tunneling


问:
Do non-manager coders in their forties or older out there sometimes regret about not being managers?
And why do most programmers quit coding and become managers so early compared to other areas? You can work as a construction worker, a lawyer, researcher, writer, architect, movie director for decades if not your whole life, without quitting the favorite thing you are doing. And yet most programmers think being a manager, or better, a non-coding manager is a cool thing and the ultimate goal of the software career. It's so rare to see an ordinary coder in his 40s or 50s (or 60s!) in a typical software company. Why?

(And I am for being a coder for as long as you love doing it.)

答:
This may answer your question - the Deep Dark Secret of Silicon Valley:

http://techcrunch.com/2010/08/28/silicon-valley%E2%80%99s-dark-secret-it%E2%80%99s-all-about-age/

EDIT: In response to @gnat's request: this article explains why there aren't that many "older" programmers in the tech industry. Many tech companies want younger, cheaper talent - when they can get a fresh graduate for $70k and train them, why pay six-figures for an older tech worker who probably won't be willing to pull allnighters?

ContentLicense: CC BY-SA 2.5


问:
Large enterprise application - clients wish to use duplicate e-mails addresses?
I'd like to know people's opinions, reactions to clients and technical work arounds (if applicable), to the issue of an enterprise application where a client wishes to use duplicate e-mail addresses?

To clarify, when I say duplicate e-mail addresses I mean within the same client system, having multiple users that have the same e-mail address. So not just using generic e-mail addresses but using the e-mail address of another user.

e.g.

Bob Jenkins: bjenkins@myorg.com

James Jeffery: bjenkins@myorg.com

Context

To give this some further context, in the e-learning sector it is common that although all staff in an organisation must complete e-learning - they may not have their own e-mail address so they choose to use their managers e-mail address.

Albeit against good practice in public sites... it's a requirement we've over and over again where an organisation is split between office based staff and perhaps e.g. staff in a warehouse.

Where problem lies

Mr Steak, good point, the problem lies in password resets and perhaps in situations where semi-personal information could be sent (not confidential enough to worry about the insecurities of email). Perhaps reminders for specific system actions, which would be confusing for the unintended party to see (if perhaps misreading the e-mail's intended recipient)

Possible solutions

System knowing the difference between a "for the attention of" and direct to the person e-mails, including this in the body text.

Using alternative communication such as SMS

Simply not having e-mails sent to people who are not the intended recipient.

Providing an e-mail service ourselfs (not really viable for a corporate IT dept)

Thoughts?

答:
It sounds like you are conflating user identity with email address.  If that's the case, then insist on it.  Users who don't have a personal email address can easily get one.  Or you can easily provide one as part of your service.

In view of the inherent unreliability and complexity of getting email to work "for everyone", an alternative would be to design your interactions to be self contained and not require email for routine interactions, or ideally not needed at all.


问:
Vocabulary: Should I call this apply or map?
So, I'm tasked with organizing the code and building a library with all the common code among our products.

One thing that seems to happen all the time and I wanted to abstract is posted below in pseudocode, and I don't know how to call it (different products have different domain specific implementations and names for it)

```<code>list function idk_what_to_name_it ( list list_of_callbacks, value common_parameter ):
  list list_of_results = new list
  for_each(callback in list_of_callbacks)
    list_of_results.push(callback(common_parameter))
  end for_each
  return list_of_results
end function
</code>```

Would you call this specific construct a

```<code>list ListOfCallbacks.Map( value value_to_map)
</code>```

method or would it better be

```<code>value Value.apply(list list_of_callbacks)
</code>```

I'm really curious about this kind of thing. Is there a standard guide for this stuff?

答: It doesn't follow the classic meanings for either 'map' or 'apply'.  Map calls the same function on each element from a list, and returns a list of the results.  'Apply' calls a function passing the elements of a list as function arguments.  Your function is closer to 'map', but since it passes the same argument to a list of functions, instead of repeatedly calling a single function, I would give it a different name.


答:
To my mind, the word "map" implies some kind of association (e.g. a 'dictionary'), although there doesn't appear to be any association or pairing of data happening in your algorithm.

The result of your function is a generated list of values, so I would suggest that it's important that the name of your function puts a certain amount of emphasis on the end result and/or any side-effects the algorithm may have on state (It doesn't appear to have side-effects so more emphasis on the result/output).

e.g. The C++ standard library is equipped with some vaguely similar algorithms which contain the word generate - their purpose is to generate multiple data elements based on the input arguments.

Title: Vocabulary: Should I call this apply or map?

Body:
So, I'm tasked with organizing the code and building a library with all the common code among our products.

One thing that seems to happen all the time and I wanted to abstract is posted below in pseudocode, and I don't know how to call it (different products have different domain specific implementations and names for it)

```<code>list function idk_what_to_name_it ( list list_of_callbacks, value common_parameter ):
  list list_of_results = new list
  for_each(callback in list_of_callbacks)
    list_of_results.push(callback(common_parameter))
  end for_each
  return list_of_results
end function
</code>```

Would you call this specific construct a

```<code>list ListOfCallbacks.Map( value value_to_map)
</code>```

method or would it better be

```<code>value Value.apply(list list_of_callbacks)
</code>```

I'm really curious about this kind of thing. Is there a standard guide for this stuff?


答:
I don't know if that is the standard name (or if that is what you would really like to call it), but in Clojure, function that does this is called juxt (short of juxtaposition)

```<code>Usage: (juxt f)
       (juxt f g)
       (juxt f g h)
       (juxt f g h & fs)
Takes a set of functions and returns a fn that is the juxtaposition
of those fns.  The returned fn takes a variable number of args, and
returns a vector containing the result of applying each fn to the
args (left-to-right).
((juxt a b c) x) => [(a x) (b x) (c x)]
</code>```

Source: http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/juxt

Your example is a special case of juxt with exactly one parameter (and type related stuff you mentioned, due to the implementation details).

Body:
I don't know if that is the standard name (or if that is what you would really like to call it), but in Clojure, function that does this is called juxt (short of juxtaposition)

Usage: (juxt f)
       (juxt f g)
       (juxt f g h)
       (juxt f g h & fs)
Takes a set of functions and returns a fn that is the juxtaposition
of those fns.  The returned fn takes a variable number of args, and
returns a vector containing the result of applying each fn to the
args (left-to-right).
((juxt a b c) x) => [(a x) (b x) (c x)]

Source: http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/juxt

Your example is a special case of juxt with exactly one parameter (and type related stuff you mentioned, due to the implementation details).


答:
There is no real standard for this, in fact not even a common convention.  You may want to browse through APIs of programming languages and toolkits that do a lot of list juggling: Ruby, Python, Linq, Matlab, Maple, C++ STL, ...  Take a look and you'll see that each program/lib has its own conventions.

In fact the mentioned languages/libs even have contradicting naming conventions:

Ruby:

```<code>doubled = [1,2,3].map{|x| 2*x}
</code>```

Linq:

```<code>var doubled = new int[] { 1, 2, 3}.Select(s => 2 * x);
</code>```

(In Ruby select filters items from a list.)

Maybe you want to call your function applyMaps?  This is what Maple does:

```<code>map(apply, [sin, cos, tan], Pi)
</code>```

produces:

```<code>[0, -1, 0]
</code>```

Body:
There is no real standard for this, in fact not even a common convention.  You may want to browse through APIs of programming languages and toolkits that do a lot of list juggling: Ruby, Python, Linq, Matlab, Maple, C++ STL, ...  Take a look and you'll see that each program/lib has its own conventions.

In fact the mentioned languages/libs even have contradicting naming conventions:

Ruby:

doubled = [1,2,3].map{|x| 2*x}

Linq:

var doubled = new int[] { 1, 2, 3}.Select(s => 2 * x);

(In Ruby select filters items from a list.)

Maybe you want to call your function applyMaps?  This is what Maple does:

map(apply, [sin, cos, tan], Pi)

produces:

[0, -1, 0]


答:
I'd call it fire_callbacks, call_callbacks, apply_callbacks, or something like that.

I've usually had such a method as part of a signal or observable object.


答:
This is a map. In haskell it would be written as

```<code>map ($ param) listOfFunctions
</code>```

this would take each function and execute it with the single param, returning a list of the results.

I don't recognize the language you used but I think something like this makes sense

```<code>list function map ( callback functionToMap, list list_of_callbacks ):
  list list_of_results = new list
  for_each(callback in list_of_callbacks)
    list_of_results.push(functionToMap(callback))
  end for_each
  return list_of_results
end function
</code>```

Then you would use it as:

```<code>value function execute_with_parameter( callback function_to_execute ):
  return function_to_execute(whatever_parameter_you_want)
end function

map(execute_with_parameter, list_of_callbacks)
</code>```

Mapping over a list of items means using a normal function to map over it, mapping over a list of functions means using a higher order function to map over it, but it's a map all the same.

Body:
This is a map. In haskell it would be written as

map ($ param) listOfFunctions

this would take each function and execute it with the single param, returning a list of the results.

I don't recognize the language you used but I think something like this makes sense

list function map ( callback functionToMap, list list_of_callbacks ):
  list list_of_results = new list
  for_each(callback in list_of_callbacks)
    list_of_results.push(functionToMap(callback))
  end for_each
  return list_of_results
end function

Then you would use it as:

value function execute_with_parameter( callback function_to_execute ):
  return function_to_execute(whatever_parameter_you_want)
end function

map(execute_with_parameter, list_of_callbacks)

Mapping over a list of items means using a normal function to map over it, mapping over a list of functions means using a higher order function to map over it, but it's a map all the same.


问:
Should concrete classes avoid calling other concrete classes, except for data objects?
In Appendix A to The Art of Unit Testing, Roy Osherove, speaking about ways to write testable code from the start, says,

An abstract class shouldn't call concrete classes, and concerete classes shouldn't call concrete classes either, unless they're data objects (objects holding data, with no behavior). (259)

The first half of the sentence is simply Dependency Inversion from SOLID. The second half seems rather extreme to me. That means that every time I'm going to write a class that isn't a simple data structure, which is most classes, I should write an interface or abstract class first, right? Is it really worthwhile to go that far in defining abstract classes an interfaces? Can anyone explain why in more detail, or refute it in spite of its benefit for testability?

答:
The Gang of Four also imply that an abstract class or interface should be defined for every concrete class. Right after introducing the principle Program to an interface, not an implementation—and thus, as a direct consequence of it—they say (18):

Don't declare variables to be instance of particular concrete classes.

This is not possible unless for every concrete class that is instantiated, an abstract class or interface exists.

Thus, it would appear that this is a case where designing for testability promotes what was already considered good object-oriented design. Given that Design Patterns came out almost two decades ago, I would say that the concurrence of the Gang of Four with Osherove is a sign that all that unit testing hasn't made him sick in the head. Rather, he is simply promoting good design.

Design Patterns is one of the most highly respected books in object-oriented design, even now. So though, like with other programming principles, there is no reason to adhere to Osherove's advice with a legalism that looses site of other aspects of good design such as KISS, his advice obviously stands in a tradition of well-respected thought on object-oriented design.


问:
Do you use debugging in rails application? Why, when and how?
In Java, C and C++ I see people using intensively debugging strategies (because mostly they don't know about TDD). On the other hand, debugging too can help to understand software abstractions. So, when and how do you use debugging in Rails applications?</p>

答: Its the same as everything else, you need a debugger when you don't really know where the problem is. This may be more rare if you are using TDD, but if your application is fairly complex you will never have 100% test coverage. I do find with Rails that I don't really need an integrated debugger, the console is enough.</p>


问:
Why don't research papers that mention custom software release the source code?
Is there a reason why the source code of software mentioned in research papers is not released? I understand that research papers are more about the general idea of accomplishing something than implementation details, but I don't get why they don't release the code.

For example, this paper ends with:

Results

The human line drawing system is implemented through the Qt framework in C++ using OpenGL, and runs on a 2.00 GHz Intel dual core processor workstation without any additional hardware assistance. We can interactively draw lines while the system synthesizes the new path and texture.

Do they keep the source code closed intentionally because of a monetization they intend to make with it, or because of copyright ?

答:
Incentives matter and the incentives of researchers are generally to ensure that they can produce a steady stream of papers the incrementally build on each other.  Graduate students generally need 3-5 published papers that they can turn into individual chapters of their thesis in order to graduate.  Junior faculty need to generate as many publications as they can before their tenure review. For that reason, most academic papers are really paper n in a series. For example, the paper you reference builds on a paper the same group published a year before and discusses the ground the next paper is likely to cover.

Publishing the source code potentially allows another researcher in a different group to produce paper n+1 before the original author does or at least to produce a paper that covers a significant fraction of the ground that the author was expecting to cover as part of this research stream.  If that happens, the graduate student could easily find him or herself spending another 6-12 months in grad school in order to produce enough research output to graduate.  The faculty member may end up with one fewer published paper when tenure review time comes around.  Both of these are obviously large blows to the careers of the researcher.  Add in the fact that academic applications are often part of the research efforts of multiple people within a research group (either directly or because they share certain components) and there is pressure within the research group not to release code that might end up hurting someone that you work with every day.

You often get similar sorts of discussions in fields where gathering raw data is time consuming and highly distributed.  In astronomy, for example, a research group may spend years gathering data before they have enough information to publish one paper.  But they'll then use that data to produce a series of papers.  Research groups are very reluctant to share more of their data sets than absolutely necessary because it becomes too easy for other groups to free-ride on the time that was invested gathering the data in order to reap the rewards of actually analyzing the data.

Eventually, a lot of this code will get released just like the astronomical data eventually gets released.  That often comes when the author reaches the end of that series of papers or when most of the research groups that are working on similar topics have similar engines so releasing the code no longer gives a new researcher a competitive advantage.

It would be ideal for science if the data and code was released more quickly.  But that would often harm the scientific researcher and that is whose incentives matter in this case.


问:
How do operating systems… run… without having an OS to run in?
I'm really curious right now. I'm a Python programmer, and this question just boggled me: You write an OS. How do you run it? It has to be run somehow, and that way is within another OS?

How can an application run without being in an OS? How do you tell the computer to run, say, C, and execute these commands to the screen, if it doesn't have an OS to run in?

Does it have to do with a UNIX kernel? If so, what is a Unix kernel, or a kernel in general?

I'm sure OSes are more complicated than that, but how does it work?

答:
You write an OS. It has to be run somehow, and that way is within another OS?

Your application is running within an OS. This Operating System provides services to your application, things like opening a file and writing bytes to it. These services are usually provided via system calls.

The Operating System is running within the hardware. The hardware provides services to the Operating System, things like setting the baud rate of a serial port and writing bytes to it. These services are usually provided via memory mapped registers or I/O ports.

To give a very simplified example of how this works:

Your application tells the operating system to write something to a file. To your application, the operating system provides concepts like files and directories.

On the hardware, these concepts do not exist. The hardware provides concepts like disks divided in fixed blocks of 512 bytes. The operating system decides which blocks to use for your file, and some other blocks for metadata like the file name, size, and location on the disk. It then tells the hardware: write these 512 bytes to the sector with this number on the disk with that number; write these other 512 bytes to the sector with this different number on the disk with that same number; and so on.

The way the operating system tells the hardware to do that varies a lot. One of the functions of an operating system is to shield the applications from these differences. For the disk example, on one kind of hardware, the operating system would have to write the disk and sector number to an I/O port, and then write the bytes one by one to a separate I/O port. On another kind of hardware, the operating system would have to copy the whole 512 bytes of a sector to an area of memory, write the location of that area of memory to a special memory location, and write the disk and sector number to yet another special memory location.

Today's high-end hardware is extremely complicated. The manuals giving all their programming details are doorstoppers with thousands of pages; for instance, the latest Intel CPU manual is seven volumes, with a total of over 4000 pages—and that's only for the CPU. Most other components expose blocks of memory or I/O ports, which the operating system can tell the CPU to map to addresses within its address space. Several of these components expose even more things behind a few I/O ports or memory addresses; as an example, the RTC (Real Time Clock, the component which keeps the computer's time while it is powered off) exposes a few hundred bytes of memory behind a pair of I/O ports, and that is a very simple component dating back to the original PC/AT. Things like hard disks have whole separate processors, which the operating system talks to via standardized commands. GPUs are even more complicated.

Several people in the comments above suggested the Arduino. I agree with them, it is much simpler to understand—the ATmega328, which does everything on the Arduino Uno except exposing the USB connector as a serial port, has a manual with only a few hundred pages. On the Arduino, you run directly on the hardware, with no operating system in between; just a few small library routines, which you do not have to use if you do not want to.


问:
Delphi Conversion to Prism?
At my office, we are about to embark on an epic journey of converting an old Delphi 5 application to something more modern.  One of our options is to convert to Delphi Prism, but we want to see what options are available to help us.  So far, all I've found is Oxidizer (last worked on 2 years ago).  Are there any other options for helping us convert reasonably quickly to Prism?  Thanks.</p>

答:
As many comments suggest and encourage, rewrite, yes.  Why?  Many of those reasons have been mentioned in comments, notably the declining degree of direct language and tooling support, 3rd party component support, but also not mentioned is a decline in available talent to keep the ship going.  It is the same problem that many of the mainframe era and direct derivative projects face: talent and interest in those types of systems is waning.

One of the biggest challenges for a migration effort isn't what language or platform or toolset to go to, especially today: there are lots of good options, some better than others depending on what one is trying to accomplish and expect from the resulting effort.  Today the biggest challenge, as it has been for years, is finding the right talent to translate the old system into the new, or at least translate it well enough and efficiently enough for others to build in the new.

In the OP's case, it sounds like that they have not only skilled practitioners in not only the legacy language and tooling, but also to a degree are highly familiar with the customer and the domain.  That is a big advantage.

What I suggest, based on my experience with genuine legacy migration projects, is take a bigger jump while there is expertise on the originating end.  It becomes monumentally harder when those builders and maintainers leave.

System usage and stability assessment.  Is the system doing the things the customer needs, no more and no less?  Are their particular pieces that can be isolated to a degree?  Are there pieces that have plagued development because they are prone to breakage or get frequent complaints about?  Are there pieces from the user's perspective that are missing (use cases that would fit the system scope that haven't otherwise been identified)?  And so on...

Use that information from the usage and stability assessment to initiate a spin-off, incubation project for coming to a more mainstream platform that tooling and training will be plentiful for in the foreseeable future.  Use a mix of architecting/re-engineering and straight porting to get off the ground.

Prove out the new pieces using phased, selective deployment to users.

Evaluate progress to effort spent.

Ramp up migration if everything is going as planned.

EDIT:

Personal recommendations:

C# on a Windows or web platform as it provides familiarity in a lot of ways to Delphi, and it will be the draft horse of Microsoft for a while.

Possibly a foray into mobile.  It depends on what the customer needs and wants as this could change how I would prioritize it.  One of the things the ThoughtWorks Radar suggest is many companies are moving to a mobile-first strategy for new projects.  I personally would be most inclined to suggest the route of Android if looking at native apps, primarily because it's pervasive, but also in OP's case, mobile Java would be a fairly comfortable transition from Delphi.  Google is definately not going away from this anytime soon.

Ada.  Just kidding.

Possibly Python or Ruby.  I am somewhat agnostic about both, but they certainly have some merit.

Title: Delphi Conversion to Prism?


答:
I see a few reasons to do this:

I can use normal path-based access control rules in web.xml.

I can never be sure I have protected my whole Ajax application properly, and I need to do extensive tests to be confident.

I can delegate authentication to a framework (like Spring Security), a third-party application, or an SSO solution (like CAS or JOSSO).

I can let the browser cache username and (optionally) passwords for the user.

Title: Why make the login page to a single page application a separate page?

Body:
I am wondering why it seems to be popular to have the login page of an SPA be a separate page that is not part of the SPA (as in loaded and send data through ajax requests)?

The only thing I can think of is security, but I can't think a specific security reason.  I mean the only thing that comes to mind is that if your login page is part of the SPA, it sends the username/password through ajax which can be seen by such tools like firebug or web inspector; however, even if you send it as a normal POST request, there are other tools that can easily capture this data (like fiddler, httpscoop, etc.).

Is there something I am missing?


问:
Tips about how to spread Object Oriented practices
I work for a medium company that has around 250 developers. Unfortunately, lots of them are stuck in a procedural way of thinking and some teams constantly deliver big Transactional Script applications, when in fact the application contains rich logic. They also fail to manage the design dependencies, and end up with services which depend on another large number of services (a clean example of Big Ball of Mud).

My question is: Can you suggest how to spread this type of knowledge?

I know that the surface of the problem is that these applications have a poor architecture and design. Another issue is that there are some developers who are against writing any kind of test.

A few things I'm doing to change this (but I'm either failing or the change is too small are)

Running presentations about design principles (SOLID, clean code, etc).

Workshops about TDD and BDD.

Coaching teams (this includes using sonar, findbugs, jdepend and other tools).

IDE & Refactoring talks.

A few things I'm thinking to do in the future (but I'm concern that they might not be good)

Form a team of OO evangelists, who disseminate an OO way of thinking in differet teams (these people would need to change teams every few months).

Running design review sessions, to criticise the design and suggest improvements (even if the improvements are not done because of time constraints, I think this might be useful)

.

Something I found with the teams I coach, is that as soon as I leave them, they revert back to the old practices. I know I don't spend a lot of time with them, usually just one month. So whatever I'm doing, it doesn't stick.

I'm sorry this question is spattered with frustration, but the alterative to write this was to hit my head on the wall until I pass out.

答:
This should have been a comment, but since I'm apparently not yet able to comment on stuff, might as well be an answer.

The most important thing ever in this kind of breakthroughs (be it OOP or any other paradigm-shifting, say, functional programming or whatever comes out in the next year) is DO CODE REVIEWS AND PEER PROGRAMMING. Accompany them, walk the teams into a different way of doing stuff that will help them.

My personal path to object oriented programming started when some random asshat doing code reviews chastised me for doing stuff in a modular way and mantaining state without going full C++ OO; think code like

```<code>extern float clients_total;

void client_add(float sum);
void client_substract(float sum);
float client_get_total();
</code>```

(note that clients_total may be entirely redundant, being a particularly poorly planned example)

And I ended up doing this only when more senior coworker just pointed at my screen and said "look, if you write the same thing more than once, use a procedure or a function and just call it over and over".

Talks and meetings and optional practices won't make them make a paradigm shift or introduce a new practice, since there's no real drive to do it besides pure curiosity. On the other hand, making not doing it a bad or just generally frowned upon thing increases the adoption rate really well.

Be prepared for the whining and class-oriented development that will ensue until they incorporate proper design into what they're doing though. You'll see plenty stuff that'll make you die inside a bit, but that's how the path to learning looks like.

Body:
This should have been a comment, but since I'm apparently not yet able to comment on stuff, might as well be an answer.

The most important thing ever in this kind of breakthroughs (be it OOP or any other paradigm-shifting, say, functional programming or whatever comes out in the next year) is DO CODE REVIEWS AND PEER PROGRAMMING. Accompany them, walk the teams into a different way of doing stuff that will help them.

My personal path to object oriented programming started when some random asshat doing code reviews chastised me for doing stuff in a modular way and mantaining state without going full C++ OO; think code like

extern float clients_total;

void client_add(float sum);
void client_substract(float sum);
float client_get_total();

(note that clients_total may be entirely redundant, being a particularly poorly planned example)

And I ended up doing this only when more senior coworker just pointed at my screen and said "look, if you write the same thing more than once, use a procedure or a function and just call it over and over".

Talks and meetings and optional practices won't make them make a paradigm shift or introduce a new practice, since there's no real drive to do it besides pure curiosity. On the other hand, making not doing it a bad or just generally frowned upon thing increases the adoption rate really well.

Be prepared for the whining and class-oriented development that will ensue until they incorporate proper design into what they're doing though. You'll see plenty stuff that'll make you die inside a bit, but that's how the path to learning looks like.


问:
Why doesn't "object reference not set to an instance of an object" tell us which object?
We're launching a system, and we sometimes get the famous exception NullReferenceException with the message Object reference not set to an instance of an object.

However, in a method where we have almost 20 objects, having a log which says an object is null, is really of no use at all. It's like telling you, when you are the security agent of a seminar, that a man among 100 attendees is a terrorist. That's really of no use to you at all. You should get more information, if you want to detect which man is the threatening man.

Likewise, if we want to remove the bug, we do need to know which object is null.

Now, something has obsessed my mind for several months, and that is:

Why doesn't .NET give us the name, or at least the type of the object reference, which is null?. Can't it understand the type from reflection or any other source?

Also, what are the best practices to understand which object is null? Should we always test nullability of objects in these contexts manually and log the result? Is there a better way?

Update:
The exception The system cannot find the file specified has the same nature. You can't find which file, until you attach to the process and debug. I guess these types of exceptions can become more intelligent. Wouldn't it be better if .NET could tell us c:\temp.txt doesn't exist. instead of that general message? As a developer, I vote yes.

答:
It really should show exactly what you are trying to call. It's like saying "There's a problem. You need to fix it. I know what it is. I'm not going to tell you. You go figure it out" Bit like half the answers on this Stack Overflow, ironically.

So how useful would it be, for example, if you got this...

```<code>Object reference (HttpContext.Current) not set to instance of an object
</code>```

...? To have to go into the code, step through it, and work out that the thing you are trying to call is null is fine, but why not just give us a little helping hand?

I agree that it is usually useful to step through the code to get to the answer (because you will probably find out more), but often a lot of time and frustration would be saved if the NullReferenceException text was more like the example above.

Just sayin.

Body:
It really should show exactly what you are trying to call. It's like saying "There's a problem. You need to fix it. I know what it is. I'm not going to tell you. You go figure it out" Bit like half the answers on this Stack Overflow, ironically.

So how useful would it be, for example, if you got this...

Object reference (HttpContext.Current) not set to instance of an object

...? To have to go into the code, step through it, and work out that the thing you are trying to call is null is fine, but why not just give us a little helping hand?

I agree that it is usually useful to step through the code to get to the answer (because you will probably find out more), but often a lot of time and frustration would be saved if the NullReferenceException text was more like the example above.

Just sayin.


问:
Is it a good idea to appoint one of the scrum team member or scrum master as Product Owner?
Lately we had a project, in which client was busy touring. As usual scrum team was formed, management decided to appoint our analyst as Product owner since Client won’t be able to participate actively. Analyst was the one who worked closely with client for requirement analysis and specification drafting.

Client doesn’t have the time to review first two releases. Everything went smoothly until, client saw third release; he wasn’t satisfied with some functionalities, and those was introduced by make shift Product Owner (our analyst).

We were told to wait till design team finished mock-up of all pages and client checked each one and approved to continue working. Scrum team is there, but no sprints – we finished work almost like classic waterfall method.

Is it a good idea to appoint scrum team member or master as product owner? Do we need to follow scrum in the absence of client/product owner participation?

答:
It was only a few weeks ago that Mike Cohn wrote about combining scrum master and product owner roles on his blog.  I don't think I can put it any better than he did, but my short summary of his post is this:

it's a bad idea

SM and PO perform very different kinds of tasks ("star tasks" and "guardian tasks" in Cohn's words)

the person combining the two roles is unlikely to be a good fit for all tasks involved in both roles

the team may be hurt by the combined SM/PO neglecting the tasks they are not the best at.

I think there is nothing wrong per se with taking any member of a scrum team and moving him/her to Product Owner.  But you have to realize that it's like a promotion or an internal transfer; it creates a hole in the team and the hole needs to be filled.  Maybe the team can "self-reorganize" to fill the hole; maybe it needs to hire a new employee to fill the vacant position.


答:
My opinion, In this situation we can have two Emails (Db Columns - PersonalEmail & AdminEmail):

Personal Email- Queries will be sent to the respected user.

Admin/Support Email (For who doesn't have personal company email) - Queries will be sent to the company Systems Administrator/Support team who is responsible for the user accounts and who can also solve the user related queries within the organisation.

Cheers!

Title: Large enterprise application - clients wish to use duplicate e-mails addresses?

Body:
I'd like to know people's opinions, reactions to clients and technical work arounds (if applicable), to the issue of an enterprise application where a client wishes to use duplicate e-mail addresses?

To clarify, when I say duplicate e-mail addresses I mean within the same client system, having multiple users that have the same e-mail address. So not just using generic e-mail addresses but using the e-mail address of another user.

e.g.

Bob Jenkins: bjenkins@myorg.com

James Jeffery: bjenkins@myorg.com

Context

To give this some further context, in the e-learning sector it is common that although all staff in an organisation must complete e-learning - they may not have their own e-mail address so they choose to use their managers e-mail address.

Albeit against good practice in public sites... it's a requirement we've over and over again where an organisation is split between office based staff and perhaps e.g. staff in a warehouse.

Where problem lies

Mr Steak, good point, the problem lies in password resets and perhaps in situations where semi-personal information could be sent (not confidential enough to worry about the insecurities of email). Perhaps reminders for specific system actions, which would be confusing for the unintended party to see (if perhaps misreading the e-mail's intended recipient)

Possible solutions

System knowing the difference between a "for the attention of" and direct to the person e-mails, including this in the body text.

Using alternative communication such as SMS

Simply not having e-mails sent to people who are not the intended recipient.

Providing an e-mail service ourselfs (not really viable for a corporate IT dept)

Thoughts?


问:
What is the point of using DTO (Data Transfer Objects)?
What is the point of using DTO and is it an out dated concept? I use POJOs in the view layer to transfer and persist data. Can these POJOs be considered as an alternative to DTOs?</p>

答:
DTO is a pattern and it is implementation (POJO/POCO) independent. DTO says, since each call to any remote interface is expensive, response to each call should bring as much data as possible. So, if multiple requests are required to bring data for a particular task, data to be brought can be combined in a DTO so that only one request can bring all the required data. Catalog of Patterns of Enterprise Application Architecture has more details.

DTO's are a fundamental concept, not outdated.


答:
DTO as a concept (objects whose purpose is to collect data to be returned to the client by the server) is certainly not outdated.

What is somewhat outdated is the notion of having DTOs that contain no logic at all, are used only for transmitting data and "mapped" from domain objects before transmission to the client, and there mapped to view models before passing them to the display layer. In simple applications, the domain objects can often be directly reused as DTOs and passed through directly to the display layer, so that there is only one unified data model. For more complex applications you don't want to expose the entire domain model to the client, so a mapping from domain models to DTOs is necessary. Having a separate view model that duplicates the data from the DTOs almost never makes sense.

However, the reason why this notion is outdated rather than just plain wrong is that some (mainly older) frameworks/technologies require it, as their domain and view models are not POJOS and instead tied directly to the framework.

Most notably, Entity Beans in J2EE prior to the EJB 3 standard were not POJOs and instead were proxy objects constructed by the app server - it was simply not possible to send them to the client, so you had no choice about haing a separate DTO layer - it was mandatory.

Title: What is the point of using DTO (Data Transfer Objects)?

Body: What is the point of using DTO and is it an out dated concept? I use POJOs in the view layer to transfer and persist data. Can these POJOs be considered as an alternative to DTOs?</p>


问:
"Never do in code what you can get the SQL server to do well for you" - Is this a recipe for a bad design?
It's an idea I've heard repeated in a handful of places. Some more or less acknowledging that once trying to solve a problem purely in SQL exceeds a certain level of complexity you should indeed be handling it in code.

The logic behind the idea is that for the large majority of cases, the database engine will do a better job at finding the most efficient way of completing your task than you could in code. Especially when it comes to things like making the results conditional on operations performed on the data. Arguably with modern engines effectively JIT'ing + caching the compiled version of your query it'd make sense on the surface.

The question is whether or not leveraging your database engine in this way is inherently bad design practice (and why). The lines become blurred further when all the logic exists inside the database and you're just hitting it via an ORM.

答:
"Premature optimization is the root of all evil" - Donald Knuth

Use the tool most appropriate for the job. For data integrity, this is often the database. For advanced business rules, this is a rule-based system like JBoss Drools. For data visualisation, this would be a reporting framework. etc.

If you have any performance issues, you should then afterwards look whether any data can be cached, or whether an implementation in the database would be quicker. In general, the cost of buying extra servers or extra cloud power will be far lower than the added maintenance cost and the impact of extra bugs.


答:
Absolutely not! Just recently I learned lessons about better using DTOs rather than your business object you use (possibly bound to your ORM mapper).

However, just use them when they're appropriate to use and not just for the sake of using them because they're mentioned in some good pattern book.

A typical example which just comes to my mind is when you expose some kind of interface to 3rd parties. In such scenario you'd like to keep the exchanged objects quite stable which you can usually achieve nicely with DTOs.


问:
How is your working time distributed between coding and thinking?
...in percentage. For example 60/40 or 90/10 or 100/0.

My hypothesis is that the bigger the proportion of time you spend thinking the smaller your code can be as a result (and the less time will be needed to write it down). Think more, write less, in other words. Do you think it is true?

As a side note, I think in typical software companies thinking is not part of the culture anyway: you are usually supposed to be sitting there at your computer typing something. You will almost definitely be noticed by your managers if you wander about with a blank look thinking over your next steps with your code. Too bad.

答:
I code in last resort.

Say 50% thinking, 50% coding including 10% implementation and 40% debugging.


答:
Learn to use the debugger. This is exactly the kind of thing it is designed for. Set a break point on the method in question and away you go.

Simply step through your code and see exactly what the values of all your variables are at certain points.

Edit: Frankly I'm shocked that no one else has mentioned using the debugger yet.

Title: Why doesn't "object reference not set to an instance of an object" tell us which object?

Body:
We're launching a system, and we sometimes get the famous exception NullReferenceException with the message Object reference not set to an instance of an object.

However, in a method where we have almost 20 objects, having a log which says an object is null, is really of no use at all. It's like telling you, when you are the security agent of a seminar, that a man among 100 attendees is a terrorist. That's really of no use to you at all. You should get more information, if you want to detect which man is the threatening man.

Likewise, if we want to remove the bug, we do need to know which object is null.

Now, something has obsessed my mind for several months, and that is:

Why doesn't .NET give us the name, or at least the type of the object reference, which is null?. Can't it understand the type from reflection or any other source?

Also, what are the best practices to understand which object is null? Should we always test nullability of objects in these contexts manually and log the result? Is there a better way?

Update:
The exception The system cannot find the file specified has the same nature. You can't find which file, until you attach to the process and debug. I guess these types of exceptions can become more intelligent. Wouldn't it be better if .NET could tell us c:\temp.txt doesn't exist. instead of that general message? As a developer, I vote yes.


问:
What is the concept of software wear and tear?
I have heard that over time, software can begin to show signs of wear and tear.

What does wear and tear of software mean?

Software itself not being a physical entity, so how can there be wear and tear?

答: It could mean that, the more you add functionalities to your software the lesser its design stays clean, elegant, and further extendable - meaning at some point, you have to rewrite / refactor substantial parts of it? </p>


答: You could call it an n-dimensional pointwise Cartesian product of functions. However, that doesn't make for a short name, and might require explanation...</p>


问:
Which things I need to purchase to develop and distribute application to customer in .Net
This is the first time I got one customer and I am developing one application for him in c#.net and winforms. I want to distribute .net framework with my application since customer may not have it installed so I want to give it with my application so that while installing it will see if framework is installed or not and install it accordingly.

I want to know, if I want to distribute this application to this customer as well as several other customers in future, which things or licenses I need to purchase like .net framework, visual studio etc.

You can consider that I am going to start my small software firm and going to make more of such applications and sell them to various customers.

答:
The .NET framework is royalty-free, and you can package it with your application.

There are free versions of Visual Studio (called Express Editions).  What they are typically missing are the ability to create Setup Packages, and an integrated Unit Test suite.  Just for the Setup Packages, I suggest getting Visual Studio Professional (probably 2012 at this point).  You could get away without using Microsoft's test framework because there are so many good open source unit testing frameworks like NUnit.

Some versions of Visual Studio Pro (at least in the 2010 release) came with an MSDN subscription, and some didn't.  This was a big price difference.  I recommend looking into it to see if you want the benefits that come with it (you get a lot of other software with an MSDN subscription).

You will probably want to get something like Resharper as well.  It's a productivity plugin for Visual Studio.  I recommend it, and a lot of programmers seem to swear by it.

You'll need source control, but all the common ones (SVN, Hg, Git) are free, including the Visual Studio plugins.  If you worked on a bigger team, some like to use Microsoft's Team Foundation Server for source control and as a build server, but I don't think you'll need that.

Consider, you also may want to create some kind of test lab of different computers and different operating systems to test your install packages on.  The biggest stumbling block is usually 32-bit vs. 64-bit targets, especially when you have 3rd party DLLs.  You'll have to decide whether to create 2 setup packages (very common) or just one.  Plus having XP, Vista, and Windows 7 targets would be a bonus.  Perhaps you need a server with some virtual machines on it.  In that case, having the MSDN subscription might pay off quickly because you'll get access to all these OS versions for development purposes.

Edit:

Microsoft also has a promotion/program called BizSpark which you should at least look into.  It's for new startups.  If gives you a lot of cheap stuff in your first year.  It might be worth the money, depending on your situation.


答:
What is probably being referred to is software entropy or software rot. These are terms borrowed from or analogous to things from the physical world, but applied to software.

The idea is borrowed from thermodynamics. When applied to software, it means that as you introduce changes into a system, the system only gains disorder. There are techniques that can be used to limit the amount of disorder, such as refactoring, but over the course of its life, there will be a net increase in the disorder of the system. The amount of disorder is often tied to the ability to continue to maintain the system.

Software rot is similar. As you change any aspect of the system, from the environment that it runs in to the underlying requirements that drove the design and implementation, the state of the system changes in a way that makes it "worse". It could range from cosmetic differences (an underlying UI library is updated and behavior of the system changes) to functional (changes in CPU architecture influence the run-time characteristics of the system, leading to timing or synchronization bugs). Software rot doesn't necessarily require changes to the software system, but only in the environment in which the software is deployed.

Title: What is the concept of software wear and tear?

Body:
I have heard that over time, software can begin to show signs of wear and tear.

What does wear and tear of software mean?

Software itself not being a physical entity, so how can there be wear and tear?


答:
Over time there are many things that could happen to a code base that could cause it to deteriorate.

Multiple developers, of different skill sets editing the codebase.

Coding standards not being adhered too.

Architecture design patterns being used ignored to get quick fixes in

These could all lead to what could be called wear and tear of software.


答:
It is true in the strict sense that the software itself does not wear out. But everything else about the entire process of deploying, configuring, and using software does go through changes that can have the same effect in the impression of the user. You've listed some of them already. Others include:

Configuration: the software that worked well when running as a pristine install may start to behave unexpectedly or even exhibit defects that were not visible at first by the time users have finished tweaking the installation the way they want. Just think of the Windows registry: the richest, most powerful software company in the world is unable to reliably diagnose problems arising from too many or conflicting configuration settings in the registry; standard operating procedure is to tell the customer to reinstall the OS rather than spend more than a minimum time trying to fix it.

User expectations and habits: using the same program for any length of time habituates the user to the way it works. What was initially new and exciting becomes normal. This can work for the product, as users learn the quirks of operating things that they initially considered confusing, but it can also cause accumulating misgivings that eventually culminate in hatred.

data load: the longer a program is used, the more data it usually has to deal with. Views, reports and procedures that were acceptably fast in the beginning often degrade in performance the more data they have to deal with, until the run times for typical tasks that were once acceptable become unusably long. Again, technically this simply exposes a defect that already was in the software from the beginning (and proper load testing would have aught it), but the impression on the users is one of "wear": "It's soooo slow now!"


答:
How is your working time distributed between coding and thinking?

It depends. At this time of the year, I'm mostly doing bug fixes, so thinking is the majority of my work effort.

As a side note, I think in typical software companies thinking is not part of the culture anyway: you are usually supposed to be sitting there at your computer typing something. You will almost definitely be noticed by your managers if you wander about with a blank look thinking over your next steps with your code.

You will find that this attitude is not limited to software companies. It is a widespread phenomenon in American corporate culture. My experience is that managers who spent significant time in the military (or when younger in military styled schooling) pick up a habit of always be working. If your Seargant catches you not working (and since thinking is not visible to an external viewer, thinking == goofing off), he'll order you to scrub the sidewalks with a toothbrush (or other stupid make-work) just to keep you from goofing off. The all-time worst manager I worked for would intentionally create a crisis in order to make work for you if he catches you doing nothing - and since he was also the owner, he didn't believe that you needed to think about anything, just get it done.

Body:
...in percentage. For example 60/40 or 90/10 or 100/0.

My hypothesis is that the bigger the proportion of time you spend thinking the smaller your code can be as a result (and the less time will be needed to write it down). Think more, write less, in other words. Do you think it is true?

As a side note, I think in typical software companies thinking is not part of the culture anyway: you are usually supposed to be sitting there at your computer typing something. You will almost definitely be noticed by your managers if you wander about with a blank look thinking over your next steps with your code. Too bad.


问:
Is it OK to have multiple asserts in a single unit test?
In the comment to this great post, Roy Osherove mentioned the OAPT project that is designed to run each assert in a single test.

The following is written on the project's home page:

Proper unit tests should fail for
  exactly one reason, that’s why you
  should be using one assert per unit
  test.

And, also, Roy wrote in comments:

My guideline is usually that you test
  one logical CONCEPT per test. you can
  have multiple asserts on the same
  object. they will usually be the same concept being tested.

I think that, there are some cases where multiple assertions are needed (e.g. Guard Assertion), but in general I try to avoid this. What is your opinion? Please provide a real world example where multiple asserts are really needed.

答:
Tests should fail for one reason only, but that doesn't always mean that there should be only one Assert statement. IMHO it is more important to hold to the "Arrange, Act, Assert" pattern.

The key is that you have only one action, and then you inspect the results of that action using asserts. But it is "Arrange, Act, Assert, End of test". If you are tempted to continue testing by performing another action and more asserts afterwards, make that a separate test instead.

I am happy to see multiple assert statements that form parts of testing the same action. e.g.

[Test]
public void ValueIsInRange()
{
  int value = GetValueToTest();

  Assert.That(value, Is.GreaterThan(10), "value is too small");
  Assert.That(value, Is.LessThan(100), "value is too large");
}
```
<p>or</p>
<pre class="lang-cs prettyprint-override"><code>[Test]
public void ListContainsOneValue()
{
  var list = GetListOf(1);

  Assert.That(list, Is.Not.Null, "List is null");
  Assert.That(list.Count, Is.EqualTo(1), "Should have one item in list");
  Assert.That(list[0], Is.Not.Null, "Item is null");
}
</code>```

You could combine these into one assert, but that's a different thing from insisting that you should or must. There is no improvement from combining them.

e.g. The first one could be

Assert.IsTrue((10 < value) && (value < 100), "Value out of range");
```

But this is not better - the error message out of it is less specific, and it has no other advantages. I'm sure you can think of other examples where combining two or three (or more) asserts into one big boolean condition makes it harder to read, harder to alter and harder to work out why it failed. Why do this just for the sake of a rule?

NB: The code that I am writing here is C# with NUnit, but the principles will hold with other languages and frameworks. The syntax may be very similar too.

Body:
Tests should fail for one reason only, but that doesn't always mean that there should be only one Assert statement. IMHO it is more important to hold to the "Arrange, Act, Assert" pattern.

The key is that you have only one action, and then you inspect the results of that action using asserts. But it is "Arrange, Act, Assert, End of test". If you are tempted to continue testing by performing another action and more asserts afterwards, make that a separate test instead.

I am happy to see multiple assert statements that form parts of testing the same action. e.g.

[Test]
public void ValueIsInRange()
{
  int value = GetValueToTest();

  Assert.That(value, Is.GreaterThan(10), "value is too small");
  Assert.That(value, Is.LessThan(100), "value is too large");
}

or

[Test]
public void ListContainsOneValue()
{
  var list = GetListOf(1);

  Assert.That(list, Is.Not.Null, "List is null");
  Assert.That(list.Count, Is.EqualTo(1), "Should have one item in list");
  Assert.That(list[0], Is.Not.Null, "Item is null");
}

You could combine these into one assert, but that's a different thing from insisting that you should or must. There is no improvement from combining them.

e.g. The first one could be

Assert.IsTrue((10 < value) && (value < 100), "Value out of range");

But this is not better - the error message out of it is less specific, and it has no other advantages. I'm sure you can think of other examples where combining two or three (or more) asserts into one big boolean condition makes it harder to read, harder to alter and harder to work out why it failed. Why do this just for the sake of a rule?

NB: The code that I am writing here is C# with NUnit, but the principles will hold with other languages and frameworks. The syntax may be very similar too.


问:
How representative is Ohloh?
My colleague recently pointed me to Ohloh, a website providing statistics on FOSS based on versioning repositories. It's quite a fun procrastination tool, e.g. to compare programming languages by active projects:

Which makes me wonder: how representative is such a comparison? Can we draw conclusions from this such as "Javascript is the most used programming language in FOSS, followed closely by Python, Java and C++"? Or are there some big caveats to take into account?

答: While JavaScript is probably the most used, it crawled one of my MVC apps and said that it was a JavaScript project simply because of all the default JavaScript files that are in there by default (JQuery, Bootstrap, etc).  So if this is counting the projects as a single language (which it probably is), then it's probably accurate assuming all web projects are JavaScript projects and C#/Java/Python/Ruby projects will mostly only get categorized that way if they're console/desktop apps.</p>

Title: How representative is Ohloh?


答:
You've picked the graph with:

The lines show the count of projects with at least one line of code changed in a month

Of the four choices, this is the one saying the least about how much any language is used. The one showing the number of lines of code change and taking C into into account is a better indicator of actual popularity. It indicates that most coding in OSS is done in C, which doesn't seem surprising considering projects as the 20 MLOC sized Linux kernel.

Title: How representative is Ohloh?

Body:
My colleague recently pointed me to Ohloh, a website providing statistics on FOSS based on versioning repositories. It's quite a fun procrastination tool, e.g. to compare programming languages by active projects:

Which makes me wonder: how representative is such a comparison? Can we draw conclusions from this such as "Javascript is the most used programming language in FOSS, followed closely by Python, Java and C++"? Or are there some big caveats to take into account?


答:
It depends to which kind of representativity you are looking for. There is something like 600.000 projects taken into account by Ohioh, so you can consider it as a big enough data set. However, some of these projects are not relevant, and they are often more numberous than believed. For instance I know in Gnome (which seems to be indexed), about 60% of all the projects didn't receive any commits during the last 2-3 years. You have to throw them away if you are interested in "modern" trends.

An other point is that the number of projects is maybe a too coarse metric of the language popularity: Most of the projects are very small, and a few are very big (their sizes typically follow a Pareto distribution). So in fact you will probably be more interested in the cumulative size of the relevant projects or the projects activity. You have then to define what's a project size (number of lines of code? number of files?). If you look at the monthly evolution of the number of commits per language, you can see that C, HTML and Java are quiete close. And the C activity is slowing down since 2006. If you look the number of projects that received at least one commit per month, the C language is even in the second place, after the HTML language! The monthly number of lines of code changed is probably affected by important refactoring/restructuration in some big projects.

I fear the data are also very heterogeneous. Eclipse and Apache are probably pro-Java, since most of KDE projects will probably written in C/C++. The Linux kernel is mainly written in C. So if you focus on a particular subcommunity, the results may sharply change.

At the end of the day, the presented data can be relevant for a trend analysis, but you have to clearly define what you are looking for and adapt your observations consequently.

Title: How representative is Ohloh?


问:
Where should I define constants in scripts?
When writing scripts using a modern scripting language, e.g. Powershell or JavaScript, where should I define constants? Should I make all constants global for readability and ease of use, or does it make sense to define constants as close to their scopes as possible (in a function, for instance, if it's not needed elsewhere)? I'm thinking mostly of error messages, error IDs, paths to resources or configuration options.</p>

答:
Consts are good for just giving descriptive variable names to avoid the magic number problems, but they cause a similarly annoying problem of not being able to identify the value actually being used when the const is defined away from it's use.

My suggestion, in all languages: define consts in as close a scope as possible to their actual usage. If used in only one class; only put in that class. Multiple classes would mean make sure it's at least in the same namespace as all classes using it.

In javascript this means as close lexically in scope as it can be to all usages.


答:
As someone who has done this (on the student side) several times in the past:  oftentimes the professors writing the paper never even see the source-code themselves.  They'll have their grad students write the code, and then only ask for the final executable (or even just a confirmation of the result) when it's complete.

Also, often the code written is not very readable anyways, because the students just hacked it together to get it done, and because (though they're very bright) grad students with no real-world experience tend not to be the world's best coders...

Title: Why don't research papers that mention custom software release the source code?

Body:
Is there a reason why the source code of software mentioned in research papers is not released? I understand that research papers are more about the general idea of accomplishing something than implementation details, but I don't get why they don't release the code.

For example, this paper ends with:

Results

The human line drawing system is implemented through the Qt framework in C++ using OpenGL, and runs on a 2.00 GHz Intel dual core processor workstation without any additional hardware assistance. We can interactively draw lines while the system synthesizes the new path and texture.

Do they keep the source code closed intentionally because of a monetization they intend to make with it, or because of copyright ?


问:
Generic Adjacency List Graph implementation
I am trying to come up with a decent Adjacency List graph implementation so I can start tooling around with all kinds of graph problems and algorithms like traveling salesman and other problems...  But I can't seem to come up with a decent implementation.  This is probably because I am trying to dust the cobwebs off my data structures class.

But what I have so far... and this is implemented in Java... is basically an edgeNode class that has a generic type and a weight-in the event the graph is indeed weighted.

```<code>public class edgeNode<E> {
    private E y;
    private int weight;

    //... getters and setters as well as constructors...
}
</code>```

I have a graph class that has a list of edges a value for the number of Vertices and and an int value for edges as well as a boolean value for whether or not it is directed.  The brings up my first question, if the graph is indeed directed, shouldn't I have a value in my edgeNode class?  Or would I just need to add another vertices to my LinkedList?  That would imply that a directed graph is 2X as big as an undirected graph wouldn't it?

```<code>public class graph {
    private List<edgeNode<?>> edges;
    private int nVertices;
    private int nEdges;
    private boolean directed;

    //... getters and setters as well as constructors...
}
</code>```

Finally does anybody have a standard way of initializing there graph?  I was thinking of reading in a pipe-delimited file but that is so 1997.

```<code>public graph GenereateGraph(boolean directed, String file){
        List<edgeNode<?>> edges;
        graph g;
        try{
            int count = 0;
            String line;
            FileReader input = new FileReader("C:\\Users\\derekww\\Documents\\JavaEE Projects\\graphFile");
            BufferedReader bufRead = new BufferedReader(input);
            line = bufRead.readLine();
            count++;
            edges = new ArrayList<edgeNode<?>>();
            while(line != null){
                line = bufRead.readLine();
                Object edgeInfo = line.split("|")[0];
                int weight = Integer.parseInt(line.split("|")[1]);
                edgeNode<String> e = new edgeNode<String>((String)
                edges.add(e);
            }
            return g;
        }
        catch(Exception e){
            return null;
        }
    }
</code>```

I guess when I am adding edges if boolean is true I would be adding a second edge.  So far, this all depends on the file I write.  So if I wrote a file with the following Vertices and weights...

```<code>Buffalo | 18  br Pittsburgh | 20 br New York | 15 br D.C | 45 br
</code>```

I would obviously load them into my list of edges, but how can I represent one vertices connected to the other... so on... I would need the opposite vertices?  Say I was representing Highways connected to each city weighted and un-directed (each edge is bi-directional with weights in some fictional distance unit)... Would my implementation be the best way to do that?

I found this tutorial online Graph Tutorial that has a connector object.  This appears to me be a collection of vertices pointing to each other.  So you would have A and B each with there weights and so on, and you would add this to a list and this list of connectors to your graph... That strikes me as somewhat cumbersome and a little dismissive of the adjacency list concept?  Am I wrong and that is a novel solution?

This is all inspired by steve skiena's Algorithm Design Manual.  Which I have to say is pretty good so far.  Thanks for any help you can provide.

答:
Here's an implementation that I dug up from when I was dealing with graphs. Although it's in C#, with a few minor adjustments it could compile in Java.

To make it directed you would have to copy v.Adjacents.Add(new Edge(w, cost)); and reverse the direction, thereby taking up double the space.

I don't think it's any better than what you have though.

```<code>class Edge
{
    public Vertex Destination { get; set; }
    public double Cost { get; set; }

    public Edge(Vertex destination, double cost)
    {
        Destination = destination;
        Cost = cost;
    }

}

class Vertex
{
    public string Name { get; set; }
    public List<Edge> Adjacents { get; set; }
    public double Distance { get; set; }

    public Vertex(string name)
    {
        Name = name;
        Adjacents = new List<Edge>();
        Distance = double.MaxValue;
    }
}

class Graf
{
    private readonly Dictionary<string, Vertex> vertexmap = new Dictionary<string, Vertex>();

    public void AddEdge(string source, string dest, double cost)
    {
        var v = GetVertex(source);
        var w = GetVertex(dest);
        v.Adjacents.Add(new Edge(w, cost));
    }

    private Vertex GetVertex(string vertexname)
    {
        Vertex v;
        vertexmap.TryGetValue(vertexname, out v);
        if (v == null)
        {
            v = new Vertex(vertexname);
            vertexmap.Add(vertexname, v);
        }
        return v;
    }
}
</code>```

Body:
Here's an implementation that I dug up from when I was dealing with graphs. Although it's in C#, with a few minor adjustments it could compile in Java.

To make it directed you would have to copy v.Adjacents.Add(new Edge(w, cost)); and reverse the direction, thereby taking up double the space.

I don't think it's any better than what you have though.

class Edge
{
    public Vertex Destination { get; set; }
    public double Cost { get; set; }

    public Edge(Vertex destination, double cost)
    {
        Destination = destination;
        Cost = cost;
    }

}

class Vertex
{
    public string Name { get; set; }
    public List<Edge> Adjacents { get; set; }
    public double Distance { get; set; }

    public Vertex(string name)
    {
        Name = name;
        Adjacents = new List<Edge>();
        Distance = double.MaxValue;
    }
}

class Graf
{
    private readonly Dictionary<string, Vertex> vertexmap = new Dictionary<string, Vertex>();

    public void AddEdge(string source, string dest, double cost)
    {
        var v = GetVertex(source);
        var w = GetVertex(dest);
        v.Adjacents.Add(new Edge(w, cost));
    }

    private Vertex GetVertex(string vertexname)
    {
        Vertex v;
        vertexmap.TryGetValue(vertexname, out v);
        if (v == null)
        {
            v = new Vertex(vertexname);
            vertexmap.Add(vertexname, v);
        }
        return v;
    }
}


答:
Instead of using constants, you could use a configuration file. JavaScript allows you to have easily parsable files in json format. I don't know about PowerShell.

Configuration files have the advantage of being centralized, yet the name of the property in the function scope (when you retrieve it) allows you to maintain readability.

Title: Where should I define constants in scripts?

Body: When writing scripts using a modern scripting language, e.g. Powershell or JavaScript, where should I define constants? Should I make all constants global for readability and ease of use, or does it make sense to define constants as close to their scopes as possible (in a function, for instance, if it's not needed elsewhere)? I'm thinking mostly of error messages, error IDs, paths to resources or configuration options.</p>


答:
Many factors can conspire against a program that is considered acceptable, good, or even great to erode its reputation and ability to perform its function.

That was then, this is now.  I visited a museum in Chicago and saw the control panel in an Apollo space capsule.  At the time, it was state of the art, the best available technology.  By our standards today it would be considered to have poor human factors, clunky old switches instead of a touch screen.  Its computer was tiny and slow.  Brilliant minds created it, with some aspects of their design being completely original with no previous model to imitate.

Bowie knife to Swiss army knife.  When it was made, it had one feature and did it well with great ease of use.  It might have come in just one color (black), but it was solid and replaced a time consuming manual system that people still remember (and hated).  Over time, new versions added complex features and options.  People forgot how little the manual system did and how hard it was to use, but they are seeing hard to use again and don't like it.

The integrity of the original design is compromised.  When originally fielded, the design might have been based on a clear, simple design.  For example, in the name of improvement, the thousand line C program that had a function per feature was replaced with a C++ program that was recoded, but not rearchitected.

Orphans can get kicked around.  The original authors and original stakeholders had some goals relative to functionality, scope, return on investment, suitability for a particular purpose, and probably most importantly, the software was of high priority.  Once in maintenance, sometimes the level of resources, the amount of focus, the clarity of purpose, and the ownership and empowerment of the stakeholders floats.  The new people know less than the original people, fail to respect their written or unwritten contracts about the software, and may make quick and dirty or slow and expensive changes, quickly earning disapproval from QA or resource/project managers.

Moore's law.  If software was built to the limits of hardware (say 640K RAM of RAM and 10 MB hard drive), a few years later it may be remembered with nostalgia, but it is a relic.

New paradigms.  Pocket PC software that didn't link apps with other apps can't be nearly as versatile as an app that feeds its intents into a user selection from among several different programs (think photo sharing on an Android phone or tablet).  That text based terminal with menus selected by typing a number and hitting enter is no match for an effective web page, not just from easy of use, but for inter-connectivity, scalability and maintainability.

Competitive new designs shine by comparison.  Being first can be a hard road, and to paraphrase Newton who said he stood on the shoulders of giants, it can be painful for software if it has competitors standing on top of it.  Software that stops growing and improving is like people who stop growing and improving.  The Honda Accord has been a Car and Drivers magazine top ten pick for over twenty years, but few people would pay the new car price for a brand new copy of a twenty year old car (except maybe a Brazilian build VW bug).  In software, the problem is amplified because prices drive downward for many software based products.


问:
What is the best practice for when to check if something needs to be done?
Let's say I have a function that does x. I pass it a variable, and if the variable is not null, it does some action. And I have an array of variables and I'm going to run this function on each one.

Inside the function, it seems like a good practice is to check if the argument is null before proceeding. A null argument is not an error, it just causes an early return.

I could loop through the array and pass each value to the function, and the function will work great.

Is there any value to checking if the var is null and only calling the function if it is not null during the loop?

This doubles up on the checking for null, but:

Is there any gained value?

Is there any gain on not calling a function?

Any readability gain on the loop in the parent code?

For the sake of my question, let's assume that checking for null will always be the case. I can see how checking for some object property might change over time, which makes the first check a bad idea.

Pseudo code example:

```<code>for(thing in array) {
    x(thing)
}
</code>```

Versus:

```<code>for(thing in array) {
    if(thing not null) x(thing)
}
</code>```

If there are language-specific concerns, I'm a web developer working in PHP and JavaScript.

答:
I don't know how you populate the array, but if it is a database query, you can tell the SQL to omit the rows where that column is null. Maybe the correct thing to do is the array not having null values to begin with.

Either way, since parameter beeing null is not an error, then the first option is OK.

```<code>for(thing in array) {
    x(thing)
}
</code>```

There shouldn't be any apreciable difference in performance, etc.

Body:
I don't know how you populate the array, but if it is a database query, you can tell the SQL to omit the rows where that column is null. Maybe the correct thing to do is the array not having null values to begin with.

Either way, since parameter beeing null is not an error, then the first option is OK.

for(thing in array) {
    x(thing)
}

There shouldn't be any apreciable difference in performance, etc.


答:
If passing null is legal from the point of view of the function that you call, adding an additional check outside the loop is superfluous, and should be avoided.

The classic example is C's free function which allows NULLs: technically, null-checking before the call does no harm, but it clutters the code, and has negative impact on readability.

With that said, you can save yourself some CPU cycles when you pass other parameters that must be prepared:

```<code>var index = 0
for(thing in array) {
    if(thing not null) x(thing, prepareOtherParameters(index))
    index++
}
</code>```

is faster than the same call without a "guard", because calls to prepareOtherParameters is avoided.

Title: What is the best practice for when to check if something needs to be done?

Body:
Let's say I have a function that does x. I pass it a variable, and if the variable is not null, it does some action. And I have an array of variables and I'm going to run this function on each one.

Inside the function, it seems like a good practice is to check if the argument is null before proceeding. A null argument is not an error, it just causes an early return.

I could loop through the array and pass each value to the function, and the function will work great.

Is there any value to checking if the var is null and only calling the function if it is not null during the loop?

This doubles up on the checking for null, but:

Is there any gained value?

Is there any gain on not calling a function?

Any readability gain on the loop in the parent code?

For the sake of my question, let's assume that checking for null will always be the case. I can see how checking for some object property might change over time, which makes the first check a bad idea.

Pseudo code example:

```<code>for(thing in array) {
    x(thing)
}
</code>```

Versus:

```<code>for(thing in array) {
    if(thing not null) x(thing)
}
</code>```

If there are language-specific concerns, I'm a web developer working in PHP and JavaScript.

Body:
If passing null is legal from the point of view of the function that you call, adding an additional check outside the loop is superfluous, and should be avoided.

The classic example is C's free function which allows NULLs: technically, null-checking before the call does no harm, but it clutters the code, and has negative impact on readability.

With that said, you can save yourself some CPU cycles when you pass other parameters that must be prepared:

var index = 0
for(thing in array) {
    if(thing not null) x(thing, prepareOtherParameters(index))
    index++
}

is faster than the same call without a "guard", because calls to prepareOtherParameters is avoided.


答:
Is there any value to checking if the var is null and only calling the
  function if it is not null during the loop?

In practical terms, very little unless you're using a language that imposes incredibly high function call overhead.

If your function claims it will "do x if the thing you pass is not null, nothing if it is," then inside the function is where that behavior should be determined.  Otherwise, the first time the function is called with a null pointer, you run the risk of unpredictable or undesired behavior.  Additionally, if you want to change the function's behavior in the presence of a null, you only have to change it in one place.


问:
IValidatableObject vs Single Responsibility
I like the extnesibility point of MVC, allowing view models to implement IValidatableObject, and add custom validation.

I try to keep my Controllers lean, having this code be the only validation logic:

```<code>if (!ModelState.IsValid)
    return View(loginViewModel);
</code>```

For example a login view model implements IValidatableObject, gets ILoginValidator object via constructor injection:

```<code>public interface ILoginValidator
{
    bool UserExists(string email);
    bool IsLoginValid(string userName, string password);
}
</code>```

It seems that Ninject, injecting instances in view models isn't really a common practice, may be even an anti-pattern?

Is this a good approach? Is there a better one?

答:
Instead of injecting the ILoginValidator into your VM constructor you can use the ValidationContext (which is the arg to IValidatableObject.Validate()) to get your Validator. </p>

```<code>public IEnumerable<ValidationResult> Validate(ValidationContext vc)
{

var loginValidator = (ILoginValidator)vc.GetService(typeof(ILoginValidator));
return loginValidator.Validate();

}
</code>```

Body:
Instead of injecting the ILoginValidator into your VM constructor you can use the ValidationContext (which is the arg to IValidatableObject.Validate()) to get your Validator.

public IEnumerable<ValidationResult> Validate(ValidationContext vc)
{

var loginValidator = (ILoginValidator)vc.GetService(typeof(ILoginValidator));
return loginValidator.Validate();

}


问:
design a model for a system of dependent variables
I'm dealing with a modeling system (financial) that has dozens of variables.  Some of the variables are independent, and function as inputs to the system; most of them are calculated from other variables (independent and calculated) in the system.

What I'm looking for is a clean, elegant way to:

define the function of each dependent variable in the system

trigger a re-calculation, whenever a variable changes, of the variables that depend on it

A naive way to do this would be to write a single class that implements INotifyPropertyChanged, and uses a massive case statement that lists out all the variable names x1, x2, ... xn on which others depend, and, whenever a variable xi changes, triggers a recalculation of each of that variable's dependencies.

I feel that this naive approach is flawed, and that there must be a cleaner way.  I started down the path of defining a CalculationManager<TModel> class, which would be used (in a simple example) something like as follows:

```<code>public class Model : INotifyPropertyChanged
{
    private CalculationManager<Model> _calculationManager = new CalculationManager<Model>();

    // each setter triggers a "PropertyChanged" event
    public double? Height { get; set; }
    public double? Weight { get; set; }
    public double? BMI { get; set; }

    public Model()
    {
        _calculationManager.DefineDependency<double?>(
            forProperty: model => model.BMI,
            usingCalculation: (height, weight) => weight / Math.Pow(height, 2),
            withInputs: model => model.Height, model.Weight);
    }

    // INotifyPropertyChanged implementation here
}
</code>```

I won't reproduce CalculationManager<TModel> here, but the basic idea is that it sets up a dependency map, listens for PropertyChanged events, and updates dependent properties as needed.  I still feel that I'm missing something major here, and that this isn't the right approach:

the (mis)use of INotifyPropertyChanged seems to me like a code smell

the withInputs parameter is defined as params Expression<Func<TModel, T>>[] args, which means that the argument list of usingCalculation is not checked at compile time

the argument list (weight, height) is redundantly defined in both usingCalculation and withInputs

I am sure that this kind of system of dependent variables must be common in computational mathematics, physics, finance, and other fields.  Does someone know of an established set of ideas that deal with what I'm grasping at here?  Would this be a suitable application for a functional language like F#?

Edit

More context:

The model currently exists in an Excel spreadsheet, and is being migrated to a C# application.  It is run on-demand, and the variables can be modified by the user from the application's UI.  Its purpose is to retrieve variables that the business is interested in, given current inputs from the markets, and model parameters set by the business.

答:
Assuming you can model the dependencies as a directed acyclic graph, you can then use a Topological Sort to order them.  My understanding is that spreadsheets use this idea.

Seems like F# would be a good fit.


答:
One of the things people don't seem to realize is that doing all of your processing on the SQL server is not necessarily good, regardless of the effects on code quality.

For instance, if you need to grab some data and then compute something from the data and then store that data in the database. There are two choices:

Grab the data into your application, compute within your application, and then send the data back to the database

Craft a stored procedure or similar to grab the data, compute across it, and then store it all from a single call to SQL server.

You may think that the second solution is always the fastest, but this is definitely not true. I'm ignoring even if SQL is a bad fit for the problem(ie regex and string manipulation). Let's pretend you have SQL CLR or something similar to have a powerful language in the database even. If it takes 1 second to make a round trip and get the data and 1 second to store it, and then 10 seconds to do the computation across it. You're doing it wrong if you're doing it all in the database.

Sure, you shave off 2 seconds. However, had you rather waste 100% of (at least) one CPU core on your database server for 10 seconds, or had you rather waste that time on your web server?

Web servers are easy to scale up, databases on the other hand are extremely expensive, especially SQL databases. Most of the time, web servers are "stateless" as well and can be added and removed at whim with no additional configuration to anything but the load balancer.

So, think not just about shaving 2 seconds off of an operation, but also think about scalability. Why waste an expensive resource like database server resources when you can use the much cheaper web server resources with a relatively small performance impact

Title: "Never do in code what you can get the SQL server to do well for you" - Is this a recipe for a bad design?

Body:
It's an idea I've heard repeated in a handful of places. Some more or less acknowledging that once trying to solve a problem purely in SQL exceeds a certain level of complexity you should indeed be handling it in code.

The logic behind the idea is that for the large majority of cases, the database engine will do a better job at finding the most efficient way of completing your task than you could in code. Especially when it comes to things like making the results conditional on operations performed on the data. Arguably with modern engines effectively JIT'ing + caching the compiled version of your query it'd make sense on the surface.

The question is whether or not leveraging your database engine in this way is inherently bad design practice (and why). The lines become blurred further when all the logic exists inside the database and you're just hitting it via an ORM.


问:
Can a recursive function have iterations/loops?
I've been studying about recursive functions, and apparently, they're functions that call themselves, and don't use iterations/loops (otherwise it wouldn't be a recursive function).

However, while surfing the web for examples (the 8-queens-recursive problem), I found this function:

```<code>private boolean placeQueen(int rows, int queens, int n) {
    boolean result = false;
    if (row < n) {
        while ((queens[row] < n - 1) && !result) {
            queens[row]++;
            if (verify(row,queens,n)) {
                ok = placeQueen(row + 1,queens,n);
            }
        }
        if (!result) {
            queens[row] = -1;
        }
    }else{
        result = true;
    }
    return result;
}
</code>```

There is a while loop involved.

... so I'm a bit lost now. Can I use loops or not?

答: You surely can use loops in a recursive function. What makes a function recursive is only the fact that the function calls itself at some point in its execution path. However you should have some condition to prevent infinite recursion calls from which your function can't return.</p>


答:
You misunderstood recursion: although it can be used to replace iteration, there is absolutely no requirement for the recursive function not to have iterations internal to itself.

The only requirement for a function to be considered recursive is the existence of a code path through which it calls itself, directly or indirectly. All correct recursive functions also have a conditional of some sort, preventing them from "recursing down" forever.

Your recursive function is ideal to illustrate the structure of recursive search with backtracking. It starts with the check of the exit condition row < n, and proceeds to making search decisions on its level of recursion (i.e. picking a possible position for queen number row). After each iteration, a recursive call is made to build upon the configuration that the function has found so far; eventually, it "bottoms out" when row reaches n in the recursive call that is n levels deep.

Title: Can a recursive function have iterations/loops?

Body:
I've been studying about recursive functions, and apparently, they're functions that call themselves, and don't use iterations/loops (otherwise it wouldn't be a recursive function).

However, while surfing the web for examples (the 8-queens-recursive problem), I found this function:

```<code>private boolean placeQueen(int rows, int queens, int n) {
    boolean result = false;
    if (row < n) {
        while ((queens[row] < n - 1) && !result) {
            queens[row]++;
            if (verify(row,queens,n)) {
                ok = placeQueen(row + 1,queens,n);
            }
        }
        if (!result) {
            queens[row] = -1;
        }
    }else{
        result = true;
    }
    return result;
}
</code>```

There is a while loop involved.

... so I'm a bit lost now. Can I use loops or not?