问:
Is using unit tests to tell a story a good idea?
So, I have an authentication module I wrote some time ago. Now I'm seeing the errors of my way and writing unit tests for it. While writing unit tests, I have a hard time coming up with good names and good areas to test. For instance, I have things like

RequiresLogin_should_redirect_when_not_logged_in

RequiresLogin_should_pass_through_when_logged_in

Login_should_work_when_given_proper_credentials

Personally, I think it's a bit ugly, even though it seems "proper". I also have trouble differentiating between tests by just scanning over them (I have to read the method name at least twice to know what just failed)

So, I thought that maybe instead of writing tests that purely test functionality, maybe write a set of tests that cover scenarios.

For instance, this is a test stub I came up with:

```<code>public class Authentication_Bill
{
    public void Bill_has_no_account()
    { //assert username "bill" not in UserStore
    }
    public void Bill_attempts_to_post_comment_but_is_redirected_to_login()
    { //Calls RequiredLogin and should redirect to login page
    }
    public void Bill_creates_account()
    { //pretend the login page doubled as registration and he made an account. Add the account here
    }
    public void Bill_logs_in_with_new_account()
    { //Login("bill", "password"). Assert not redirected to login page
    }
    public void Bill_can_now_post_comment()
    { //Calls RequiredLogin, but should not kill request or redirect to login page
    }
}
</code>```

Is this a heard of pattern? I've seen acceptance stories and such, but this is fundamentally different. The big difference is that I'm coming up with scenarios to "force" the tests out. Rather than manually trying to come up with possible interactions that I'll need to test. Also, I know that this encourages unit tests that don't test exactly one method and class. I think this is OK though. Also, I'm aware that this will cause problems for at least some testing frameworks, as they usually assume that tests are independent from each other and order doesn't matter(where it would in this case).

Anyway, is this an advisable pattern at all? Or, would this be a perfect fit for integration tests of my API rather than as "unit" tests? This is just in a personal project, so I'm open to experiments that may or may not go well.

答:
What you're describing sounds more like Behavior Driven Design (BDD) than unit testing to me. Take a look at SpecFlow which is a .NET BDD tech that is based on the Gherkin DSL.

Powerful stuff that any human can read/write without knowing anything about coding. Our test team is enjoying great success leveraging it for our integration test suites.

Regarding the conventions for unit tests, @DocBrown's answer seems solid.


问:
What should you bring to the table as a Software Architect?
There have been many questions with good answers about the role of a Software Architect (SA) on StackOverflow and Programmers SE. I am trying to ask a slightly more focused question than those. The very definition of a SA is broad so for the sake of this question let's define a SA as follows:

A Software Architect guides the
  overall design of a project, gets
  involved with coding efforts, conducts
  code reviews, and selects the
  technologies to be used.

In other words, I am not talking about managerial rest and vest at the crest (further rhyming words elided) types of SAs. If I were to pursue any type of SA position I don't want to be away from coding. I might sacrifice some time to interface with clients and Business Analysts etc., but I am still technically involved and I'm not just aware of what's going on through meetings.

With these points in mind, what should a SA bring to the table? Should they come in with a mentality of "laying down the law" (so to speak) and enforcing the usage of certain tools to fit "their way," i.e., coding guidelines, source control, patterns, UML documentation, etc.? Or should they specify initial direction and strategy then be laid back and jump in as needed to correct the ship's direction?

Depending on the organization this might not work. An SA who relies on TFS to enforce everything may struggle to implement their plan at an employer that only uses StarTeam. Similarly, an SA needs to be flexible depending on the stage of the project. If it's a fresh project they have more choices, whereas they might have less for existing projects.

Here are some SA stories I have experienced as a way of sharing some background in hopes that answers to my questions might also shed some light on these issues:

I've worked with an SA who code reviewed literally every single line of code of the team. The SA would do this for not just our project but other projects in the organization (imagine the time spent on this). At first it was useful to enforce certain standards, but later it became crippling. FxCop was how the SA would find issues. Don't get me wrong, it was a good way to teach junior developers and force them to think of the consequences of their chosen approach, but for senior developers it was seen as somewhat draconian.

One particular SA was against the use of a certain library, claiming it was slow. This forced us to write tons of code to achieve things differently while the other library would've saved us a lot of time. Fast forward to the last month of the project and the clients were complaining about performance. The only solution was to change certain functionality to use the originally ignored approach despite early warnings from the devs. By that point a lot of code was thrown out and not reusable, leading to overtime and stress. Sadly the estimates used for the project were based on the old approach which my project was forbidden from using so it wasn't an appropriate indicator for estimation. I would hear the PM say "we've done this before," when in reality they had not since we were using a new library and the devs working on it were not the same devs used on the old project.

The SA who would enforce the usage of DTOs, DOs, BOs, Service layers and so on for all projects. New devs had to learn this architecture and the SA adamantly enforced usage guidelines. Exceptions to usage guidelines were made when it was absolutely difficult to follow the guidelines. The SA was grounded in their approach. Classes for DTOs and all CRUD operations were generated via CodeSmith and database schemas were another similar ball of wax. However, having used this setup everywhere, the SA was not open to new technologies such as LINQ to SQL or Entity Framework.

I am not using this post as a platform for venting. There were positive and negative aspects to my experiences with the SA stories mentioned above. My questions boil down to:

What should an SA bring to the table?

How can they strike a balance in their decision making?

Should one approach an SA job (as defined earlier) with the mentality that they must enforce certain ground rules?

Anything else to consider?

Thanks! I'm sure these job tasks are easily extended to people who are senior devs or technical leads, so feel free to answer at that capacity as well.

答:
1.What should an SA bring to the table?

"Should they come in with a mentality of 'laying down the law' ... Or should they specify initial direction and strategy then be laid back and jump in as needed to correct the ship's direction?"

A combination of both I would say. When deciding on technologies and processes, being open to opinions and suggestions can give valuable feedback/input on decisions and cause you to learn from others. Your team is (hopefully) smart; take advantage of that. But once a decision (your decision) is made, the law has been laid. Identify those who will complain about whatever wasn't their choice, and those that will just choose anything and don't care - and then ignore them.

As far as technologies: work with what you've got, if the company uses StarTeam then that's what you use. Marrying yourself to any particular product/technology/process isn't going to do anything for you.

2.How can they strike a balance in their decision making?

Listening to the team and knowing when they are right and wrong is important, and having the cojones to tell them that they're wrong and stick to your decision. Not listening will bring a lack of respect, as will flopping around on your decisions.

3.Should one approach an SA job (as defined earlier) with the mentality that they must enforce certain ground rules?

Always. If not, then the inmates will end up running the asylum, overtly or covertly. Deciding on those ground rules however, can be through talk with the team. Remember that any team may not always have the same members that it has now, so making concessions for a small group of them may hinder the team in the future once they're gone. That includes the SA.

4.Anything else to consider?

In reference to your second example: It seems that the project team formed a tightly coupled dependence on an in-house subsystem. Loosely coupled facades aren't just for third party code. Creating an abstraction for that subsystem could have allowed an easier transition to using that library if the in-house solution failed. This is a logical solution for a software architect alone, but also being a form of Project Manager with the team expression concerns, it should have doubly so been an obvious solution.

In reference to your third example: It's not a bad idea to have a known architecture or process for producing software (though, admittedly, you did say 'all projects'). This is sticking to what works. With that said, there needs to be opportunities where new techniques can be attempted to see if they bring additional value. In-house-only software, or smaller-scope projects where these technologies can be attempted are ideal places. Keep in mind though, that the onus is also on the developer(s) to provide researched and convincing demonstrations/arguments for adopting technologies. And SA can't be expected to know every competing ORM and its strengths and weaknesses compared to the others.

ContentLicense: CC BY-SA 2.5


问:
Git: rebasing on top of a refactor that affects the target rebase branch
Let's say I have a feature (topic) branch that I keep rebased on top of my development branch. During the course of the project (before merging in my feature branch), I decide that I need to make a large refactor to my project (for example, after updating a 3rd part module).

So I do this large refactoring on my development branch. Now I want to rebase my feature branch so I can take advantages of my refactoring.

The problem

There are still things in my feature branch that need refactored to match the changes I made in my development branch.

Should I:

Go back through my feature branch's history trying to edit commits (with rebase -i) to make the branch look as though all of the work had been done after the refactoring.

The advantage to this is that it keeps the history clean.

The disadvantage is that this can take a whole lot of time if the changes made in the development branch cause a lot of changes to need to be made in the feature branch.

Fix the things that need to be refactored in my feature branch and make a commit for this.

The advantage here is that it will be much easier to identify and fix things that need to be fixed

The disadvantage is that now the tree will have two commits in it for the refactor. One for the refactor done for the entire development branch, and a smaller commit done for the feature branch, once merged in it will look a little funny.

Which strategy should I go with?

An Example

Lets say on the development branch I rename functionA to functionB.

Now In my feature branch I've never modified the file containing functionA (now functionB in development). So when I run rebase development while on my feature branch it rebases cleanly.

The problem is if I've ever made a call to functionA in my feature branch, it's going to fail now since it was renamed functionB.

Now, should I just do a find and replace for functionA -> functionB and make one commit on the feature branch (option 2). Or should I go back through my history, finding where I introduced the call to functionA and rewrite the commit so it is introduced as calling functionB (option 1)?

答: It seems that the git revolution has created a new neurosis called commit history anxiety. No one besides you cares what's in your commits. Just get the work done as efficiently as possible. Then you can use the time you saved to fix a bug or add a feature.</p>

ContentLicense: CC BY-SA 3.0


问:
hginit - #ifdefs ridiculous
I was reading Joel Spolsky's mercurial introduction when it struck me:

"And now what they do is this: each new feature is in a big #ifdef block. So they can work in one single trunk, while customers never see the new code until it’s debugged, and frankly, that’s ridiculous."

Why is this so ridiculous anyway, isn't this, if nothing else, simply simpler to handle? It's nothing fancy but does the trick - at least if you are already "married" with subversion.

What is the downside? I kind of don't get the argument.

答:
#ifdef'ed code is not ridiculous, but - sad and terrible. And it is (today) the diagnosis for the developer

Well, Joel selected in "Subversion Re-education" The Bad Way (tm) of argumentation - he created special, degenerated situation with specially selected users and use this use-case as a justification for the thesis "Subversion suxx"

Spaghetti-code suxx more, unmanageable and unreadable code is more dangerous, than spending some time on re-education of "Right Merge" in Subversion - "Merge often, morons!!!" Branching and bidirectional merge was possible and usable in Subversion <1.5, now (after introducing mergeinfo) merge become even easier and more comfortable. Small overhead of monitoring "interesting" trees and sync-merges (often!!!) is fair price for developer, which get in return compact, clean, debuggable code.

Title: hginit - #ifdefs ridiculous


答:
What he is describing is actually a FeatureToggle, and there can be good reasons for using that instead of feature branches. The issue is with using #ifdef. Without very good management they can easily become a big mess littered all around the code-base.

Consider the following:

When do you remove an #ifdef? - Are you certain there is no builds left which still excludes that feature? Also not for that one (well paying) client for who you make some special builds?

Who's responsible for removing the #ifdef? - The developer who made the feature? Are you sure he will remember 4 weeks down the line, to check that the switch is not excluded in any build and can safely be removed? Will he be confident that it is safe to remove the #ifdef? What about that other extremely urgent task, doesn't that take priority over removing a measly #ifdef?

My experience says that such #ifdefs will be laying around forever, littering.

Title: hginit - #ifdefs ridiculous

Body:
I was reading Joel Spolsky's mercurial introduction when it struck me:

"And now what they do is this: each new feature is in a big #ifdef block. So they can work in one single trunk, while customers never see the new code until it’s debugged, and frankly, that’s ridiculous."

Why is this so ridiculous anyway, isn't this, if nothing else, simply simpler to handle? It's nothing fancy but does the trick - at least if you are already "married" with subversion.

What is the downside? I kind of don't get the argument.


问:
Should I return from a function early or use an if statement?
I've often written this sort of function in both formats, and I was wondering if one format is preferred over another, and why.

public void SomeFunction(bool someCondition)
{
    if (someCondition)
    {
        // Do Something
    }
}
```

<p>or</p>

<pre class="lang-java prettyprint-override"><code>public void SomeFunction(bool someCondition)
{
    if (!someCondition)
        return;

    // Do Something
}
</code>```

I usually code with the first one since that is the way my brain works while coding, although I think I prefer the 2nd one since it takes care of any error handling right away and I find it easier to read

答:
As others say, it depends. For little functions that return values, I may code early returns.
But for sizeable functions, I like to always have a place in the code where I know I can put something that will get executed before it returns.</p>


问:
What is an “implementation plan”?
I was recently given the task of creating an implementation plan document. When I asked for an example of one that I could look at, I was told to look at the Project Plan that had already been created an use that as a base. I'm still a bit confused on what I should be creating.

Can anyone point me to a good example out there or to something that explains what this is and more importantly the details about what it should contain.

答: You develop log frame of your project, which shows relationship between Inputs, activities and intended results(outputs,outcome and impact ie goal of your project), from the log frame you develop annual work plan, the plan should draw activities from your log frame each year.</p>

Title: What is an “implementation plan”?


答:
Not sure why you would do a rebase -i. I would just do a rebase, and fix the problems as they come in you feature commits.

I find fixing one and one commit is easier than fixing every error afterwords. You can then also make sure, between each commit, that your tests still runs (given that you have tests that is).

Lastly, I find 2) to be problematic if you plan to continue rebasing in the future, if your feature is not yet done. Rebasing in a merge is really not something I would do if I could avoid it. If the feature is done and you don't care to much about history however, you could just merge.

Conclusion:
I would personally rebase, without the -i, and fix each commit. The reason is that I find a tidy log quite useful, and I often feel that it is the easiest way to do it.

EDIT: By your example, I would say it depends. If there are a huge amount of commits, you have called functionA a lot of times, and it basically is a huge pain to rebase every single commit, I would probably fall back to just do a search-replace in a single commit. If I knew there were only a few places, and the rebasing would be easy, I would rebase.

Since you ask, I guess the former is the situation you are in, and I would have though about how much pain will it be to clean up the log.

Title: Git: rebasing on top of a refactor that affects the target rebase branch

Body:
Let's say I have a feature (topic) branch that I keep rebased on top of my development branch. During the course of the project (before merging in my feature branch), I decide that I need to make a large refactor to my project (for example, after updating a 3rd part module).

So I do this large refactoring on my development branch. Now I want to rebase my feature branch so I can take advantages of my refactoring.

The problem

There are still things in my feature branch that need refactored to match the changes I made in my development branch.

Should I:

Go back through my feature branch's history trying to edit commits (with rebase -i) to make the branch look as though all of the work had been done after the refactoring.

The advantage to this is that it keeps the history clean.

The disadvantage is that this can take a whole lot of time if the changes made in the development branch cause a lot of changes to need to be made in the feature branch.

Fix the things that need to be refactored in my feature branch and make a commit for this.

The advantage here is that it will be much easier to identify and fix things that need to be fixed

The disadvantage is that now the tree will have two commits in it for the refactor. One for the refactor done for the entire development branch, and a smaller commit done for the feature branch, once merged in it will look a little funny.

Which strategy should I go with?

An Example

Lets say on the development branch I rename functionA to functionB.

Now In my feature branch I've never modified the file containing functionA (now functionB in development). So when I run rebase development while on my feature branch it rebases cleanly.

The problem is if I've ever made a call to functionA in my feature branch, it's going to fail now since it was renamed functionB.

Now, should I just do a find and replace for functionA -> functionB and make one commit on the feature branch (option 2). Or should I go back through my history, finding where I introduced the call to functionA and rewrite the commit so it is introduced as calling functionB (option 1)?


问:
What is "the right way" to do search on a website?
I'm talking the kind of search that auto-suggests your query as you type, the way Google does, the way Wikipedia does, the way Stack Exchange suggests other questions as you type the title, etc. And Wikipedia used to have an awful search implementation, for those of us who remember. It had no auto-suggest, was shut down by the slightest typo or misspelling, and rarely gave pertinent results.

As an amateur web programmer, I'm trying to figure out how I would implement an effective and high-performing search-and-auto-suggest as Wikipedia now has, and as SE has, and as so many other websites have.

How can you obtain that kind of incredibly fast performance and flexibility? Does everyone just wing it, or are there principles, guidelines, helpful libraries, or other such resources to help you get it done right in the style of the "Internet of the Future"?

答:
For a start you will need a full text search engine like Apache Solr or Sphinx (there are more and some databases have full text features too, but I know those two and they are free and work great). If it has facet search (like Solr) this will help a lot (for certain types of queries). This will cover the largest part of indexing and performance issues.

From there on you need to analyze your data and the search needs of your customers and come up with a good setup of fields, field types, field weights, and the text search specific issues like stemming or multiple languages, handling of special characters, splitting compound words into single words (very important for german search, we can chain words arbitrarily here).

In addition you can do a lot of statistics like counting words or phrases your users search for and compare them against statistics of your index data (for example to find out what synonyms are relevant for you)


问:
I've been told that Exceptions should only be used in exceptional cases. How do I know if my case is exceptional?
My specific case here is that the user can pass in a string into the application, the application parses it and assigns it to structured objects.  Sometimes the user may type in something invalid.  For example, their input may describe a person but they may say their age is "apple".  Correct behavior in that case is roll back the transaction and to tell the user an error occurred and they'll have to try again.  There may be a requirement to report on every error we can find in the input, not just the first.

In this case, I argued we should throw an exception.  He disagreed, saying, "Exceptions should be exceptional:  It's expected that the user may input invalid data, so this isn't an exceptional case"  I didn't really know how to argue that point, because by definition of the word, he seems to be right.

But, it's my understanding that this is why Exceptions were invented in the first place.  It used to be you had to inspect the result to see if an error occurred.  If you failed to check, bad things could happen without you noticing.

Without exceptions every level of the stack needs to check the result of the methods they call and if a programmer forgets to check in one of these levels, the code could accidentally proceed and save invalid data (for example).  Seems more error prone that way.

Anyway, feel free to correct anything I've said here.  My main question is if someone says Exceptions should be exceptional, how do I know if my case is exceptional?

答:
I always think of things like accessing the database server or a web API when thinking of exceptions. You expect the server/web API to work, but in an exceptional case it might not (server is down). A web request might be quick usually, but in exceptional circumstances (high load) it might time out. This is something out of your control.

You users' input data is in your control, since you can check what they send in and do with it what you like. In your case, I'd validate the user input before even trying to save it. And I tend to agree that users providing invalid data should be expected, and your app should account for it by validating the input and providing the user-friendly error message.

That said, I do use exceptions in most of my domain model setters, where there should be absolutely no chance that invalid data goes in. However, this is a last line of defense, and I tend to build my input forms with rich validation rules, so that there's practically no chance of triggering that domain model exception. So when a setter is expecting one thing, and gets another, it is an exceptional situation, which should not have happened in ordinary circumstances.

EDIT (something else to consider):

When sending user provided data to the db, you know beforehand what you should and shouldn't enter into your tables. This means that data can be validated against some expected format. This is something you can control.
What you can't control is your server failing in the middle of your query. So you know the query is ok and data is filtered/validated, you try the query and it still fails, this is an exceptional situation.

Similarly with the web requests, you can't know if the request will time out, or fail to connect before you try sending it. So this also warrants a try/catch approach, since you can't ask the server if it will work a few milliseconds later when you send the request.


问:
agile / scrum and functional specs
I work in a small team of four devs, one domain expert and one manager. We are looking to move to using scrum to try and formalise our processes.

From what I understand of agile, it seems to be close(ish) to what we are doing anyway. We have a brief document with the overall features our product will have. As we come to code each feature, we sit down and thrash it out verbally, relying on our domain expert for what the customer will want. We then code it, and it gets tested in vague ways by the other devs / domain expert. Improvements get suggested and implemented.

At our last ISO 9001 audit we were (deservedly) reprimanded for lack of any traceability. The auditor wanted some way of seeing we had records of what the product would do, and then testing to prove that it did it.

We are looking to scrum to give us a process for this, along with other benefits, but my reading up so far has not answered my question of where detailed functional requirements are recorded / tested? My understanding of agile / scrum is far from complete, so please correct me if I have misunderstandings.

As an example, let's say we have a user story that says:
"As a customer, I need to be able to select a system state of A, B or C".
It has an acceptance test that says
"I should be able to select state A, B, or C, and the system will change to that state"

Come the sprint where this gets implemented, we sit around and decide that we will build a widget with A, B and C radio buttons, and a "Apply" button. Then we code it.

When this widget is tested, the following problems are found:
1. Selecting B sometimes doesn't uncheck the previous radio button.
2. Sometimes option C is unavailable on the system, and so should be greyed out.
3. When first opened, the initial selection does not match the current system state.

My question is how and where is this recorded? There is no detailed functional spec saying "There will be a widget with three radio buttons. When the widget is created, the current radio selection should match the system state" blah blah. Given the lack of this document how are we supposed to prove that the system does or does not do what it's supposed to to an auditor?

答:
Well I wonder how Agile/Scrum relates to stuff like ISO 9001. ISO 9001 has documentation and processes in mind, while the Agile Manifesto has working software in mind. Even though it does value documentation/documents, the focus is usually on just enough.

The reasoning behind this is that you can write it all down and a week after having implemented it, the customer might change his/her mind. Of course, you can keep the documents in sync, but after a while, you'll notice you're putting a lot of effort and time in your documents.

What is the added value of all this documentation? If the software doesn't work like the client wants, he should tell you. This can be put in a system like VersionOne, TFS, etc. to fall back on later, but I would advise against going to far in all this documentation.

The application as it is, is what should be important. Not what a certain document says.

This is because Agile embraces change and acknowledges the fact that software changes constantly and can't be set in stone.

I'd definitely recommend 'Scrum and XP from the trenches' by Henrik Kniberg. You can find it on InfoQ after logging in, but it's also available here.

In your example, I would think you demo the widget to your customer after a sprint. He would the see it doesn't do what he wants and point this out. This is the moment when the customer can accept or not accept the work you've done. He can also point out what the next priorities are. Possibly, he has other priorities first. Or he might say you have to fix that.

In the next demo, he might see the widget working as expected and say so.

Maybe you could write this stuff down in a sort of meeting notes. But in the end, I would still be critical and ask what the added value is of ISO 9001. Have you built better software in a faster and more efficient way because of it? Or do you now have a big database of documents and processes, blocking your ability to be agile?

I understand you will want the ISO 9001 certification anyway, so I would advise you to document your processes as little as possible, because in Agile development, you should be willing to constantly change your processes. Constanstly seeking the best way to go forward. Constantly being critical of oneself (this is what the retrospectives are for).

Title: agile / scrum and functional specs


答:
I practice fail-fast at the function level. It keeps code consistent and clean (to me and those I've worked with). Because of that I always return early.

For some oft-checked conditions, you can implement aspects for those checks if you use AOP.

Title: Should I return from a function early or use an if statement?

Body:
I've often written this sort of function in both formats, and I was wondering if one format is preferred over another, and why.

public void SomeFunction(bool someCondition)
{
    if (someCondition)
    {
        // Do Something
    }
}
```

<p>or</p>

<pre class="lang-java prettyprint-override"><code>public void SomeFunction(bool someCondition)
{
    if (!someCondition)
        return;

    // Do Something
}
</code>```

I usually code with the first one since that is the way my brain works while coding, although I think I prefer the 2nd one since it takes care of any error handling right away and I find it easier to read


问:
How to design website workflow?
I have been thinking about this for really long time without reaching an optimum answer.

First of all, I'm a medical doctor who loves programming but never really studied it, except for home learning and lots of years of playing around with code in my free time.

Currently I'm trying to build a small project to manage my clinic, to do that I started by created a list of options I want to be able to do.

Example:

active patient record.

authentication with different roles (eg. patient,nurse,dr)

appointment schedule (include calendar to schedual vacinations/surgeries etc with a reminder)

allow doctor to create his own plugins.

dashboard for doctor to view his statistics

Then I started with codeigniter/mysql/php/jquery and started coding.

My steps during development:-

1st database.

I started by creating all my tables that I will need.

Created all my models to handle these tables (1 master model that handle basic read/write/update/verify while also considering my table relations

After that I start to code my views and controllers. I first created view HTML, then create controller that will handle this view, and started coding functions to make the view interactions work.

Example when coding the appointment view(controller booking.php):

created this layout and made table td's clickable,
when user click : jquery get (booking/add_patient_form) and pop it up

when user save  : post to booking/save -it save appointment then reload index() function

etc.. and I continued same steps of creating view then its controller -that contain all the logic this view needed - to accomplish whole project.

At the end I had all my target functions working fine, but since there was no PLAN from beginning and as the whole project was punch of brain storming and debugging with no what so ever plan, after I went so far in this project i find my self stuck with maintainability and flexibility! and unable to link them together.

I have feeling that every page on website is completely isolated from other and I can't even recall how each page is loaded and what functions are inside without peeking!

Is there anyway I can recover this and get a design out?

答:
Your question - what's the process for developing a piece of software - is a hotly debated topic; just google "software methodology" to see how deep this can of worms goes...

There's no commonly accepted answer. In fact, if you ask 5 programmers, you'll get 7 answers, in my experience.

I'd recommend buying Steve McConnell's "Code Complete" to see the lower-level coding practices - things like how to lay out your code, how to comment it, how to test it. I'd recommend "Domain Driven Design" by Eric Evans for an overview of how to structure applications at an architectural level. I'd recommend "Agile Software Development: Principles, Patterns and Practices" by Robert Martin as an overview of how to "grow" software over time whilst maintaining quality.

Another developer is likely to reject all of these books, and point you at UML, the Rational Unified Process, and code generation. There's no right answer!

OwnerDisplayName: Momen M El Zalabany

Title: How to design website workflow?


问:
Strategies to avoid data entry duplication between PDF vs. website (e.g. restaurant menus)
I'm building a website for a restaurant. They have a downloadable PDF version of their menu (which is what the "real-world" menu is printed from), but we also want to have a text-based version of the menu on the website (because it's the 21st century and you shouldn't have to read a PDF when browsing a site like this).

I'm hoping to avoid -- or minimize as much as possible -- the potential problems with maintaining data in two places (one in the PDF and one on the website).

In an ideal world, we'd build a custom dashboard interface for managing menu data, with a fully-normalized schema, and from that data we'd automatically generate the PDF and the website versions of the menu (and come up with a very expensive and flexible visual design for the PDF menu that takes into account all future permutations of data that may be contained within it -- because the visual layout of the PDF menu is very important, since that's what the "real-world" menu is printed from).

But, since the budget is not unlimited, I'm trying to think of other ways to accomplish this goal. Are there any compromise solutions or "this gets you halfway there" kind of things I could do? Obviously I'm not expecting a perfect and cheap solution, but anything that minimizes the double-data entry to the extent that it's not so much of a chore would be really helpful.

答:
When you look at this from a content management point of view, the content is leading and it should be stored in some form. The design or layout of that content is a second thing, and then both the PDF and the website can be considered a different design or layout.

So separate your content and your design, and then make sure that your content is stored in a single location. Then both the PDF and the website will need to be generated from that single content location.

A simple way of achieving this is by choosing a CMS (Content Management System) for the website, preferably one that can generate both HTML and PDF, so you don't have to do anything extra there yourself.


答:
There are two concerns you should consider:

you discuss a single concern - let's call it Assigner since this concern is to assign inputs to structured objects - and you express the constraint that its inputs be valid

a well-implemented user-interface has an additional concern: validation of user input & constructive feedback on errors (let's call this part Validator)

From the point of view of the Assigner component, throwing an exception is totally reasonable, since you've expressed a constraint that has been violated.

From the point of view of the user experience, the user shouldn't be talking directly to this Assigner in the first place. They should be talking to it via the Validator.

Now, in the Validator, invalid user input is not an exceptional case, it's really the case you're more interested in. So here an exception wouldn't be appropriate, and this is also where you'd want to identify all errors rather than bailing out on the first.

You'll notice I didn't mention how these concerns are implemented. It seems  you're talking about the Assigner and your colleague is talking about a combined Validator+Assigner. Once you realise there are two separate (or separable) concerns, at least you can discuss it sensibly.

To address Renan's comment, I'm just assuming that once you've identified your two separate concerns, it's obvious what cases should be considered exceptional in each context.

In fact, if it isn't obvious whether something should be considered exceptional, I'd argue you probably haven't finished identifying the independent concerns in your solution.

I guess that makes the direct answer to

...  how do I know if my case is exceptional?

keep simplifying until it is obvious.
When you have a pile of simple concepts you understand well, you can reason clearly about composing them back into code, classes, libraries or whatever.

Title: I've been told that Exceptions should only be used in exceptional cases. How do I know if my case is exceptional?

Body:
My specific case here is that the user can pass in a string into the application, the application parses it and assigns it to structured objects.  Sometimes the user may type in something invalid.  For example, their input may describe a person but they may say their age is "apple".  Correct behavior in that case is roll back the transaction and to tell the user an error occurred and they'll have to try again.  There may be a requirement to report on every error we can find in the input, not just the first.

In this case, I argued we should throw an exception.  He disagreed, saying, "Exceptions should be exceptional:  It's expected that the user may input invalid data, so this isn't an exceptional case"  I didn't really know how to argue that point, because by definition of the word, he seems to be right.

But, it's my understanding that this is why Exceptions were invented in the first place.  It used to be you had to inspect the result to see if an error occurred.  If you failed to check, bad things could happen without you noticing.

Without exceptions every level of the stack needs to check the result of the methods they call and if a programmer forgets to check in one of these levels, the code could accidentally proceed and save invalid data (for example).  Seems more error prone that way.

Anyway, feel free to correct anything I've said here.  My main question is if someone says Exceptions should be exceptional, how do I know if my case is exceptional?


问:
What is a faster alternative to a CRC?
I'm doing some data transmission from a dsPIC to a PC and I'm doing an 8-bit CRC to every block of 512 bytes to make sure there are no errors. With my CRC code enabled I get about 33KB/s, without it I get 67KB/s.

What are some alternative error detection algorithms to check out that would be faster?

答:
The Effectiveness of Checksums
for Embedded Networks by Theresa  C. Maxino is a really good paper comparing the performance of various checksums and CRCs in an embedded context.

Some quotes from the conclusions (based on studies of undetected error probabilities):

When burst errors dominate

XOR, two’s complement addition, and CRC checksums
provide better error detection performance than one’s complement
addition, Fletcher, and Adler checksums.

In other applications

a “good” CRC polynomial, whenever possible, should be used for error detection purposes

If computation cost is very constrained

(as in your case), use (in order of effectiveness):

Fletcher's checksum

one's complement addition

two's complement addition

Other quotes:

The Fletcher checksum has lower computational cost than the Adler checksum
and, contrary to popular belief, is also more effective in most situations.

and

There is generally no reason to continue the common practice of using an XOR checksum in new designs, because it has the same software computational cost as an addition-based checksum but is only about half as effective at detecting errors.

Title: What is a faster alternative to a CRC?

ContentLicense: CC BY-SA 4.0


答:
Steps/Stages to design of Website Workflow

Concept

Discovery

Content development

Design

Development

Launch

Post-launch

Detailed Resources

Web Design Process by University of Texas

How to Create a Standardized Web Site Development Workflow

The complete no-nonsense step-by-step guide to designing web
sites

Web Design Workflow – Complete Overview

A design process revealed

Web Style Guide Online

Title: How to design website workflow?

Body:
I have been thinking about this for really long time without reaching an optimum answer.

First of all, I'm a medical doctor who loves programming but never really studied it, except for home learning and lots of years of playing around with code in my free time.

Currently I'm trying to build a small project to manage my clinic, to do that I started by created a list of options I want to be able to do.

Example:

active patient record.

authentication with different roles (eg. patient,nurse,dr)

appointment schedule (include calendar to schedual vacinations/surgeries etc with a reminder)

allow doctor to create his own plugins.

dashboard for doctor to view his statistics

Then I started with codeigniter/mysql/php/jquery and started coding.

My steps during development:-

1st database.

I started by creating all my tables that I will need.

Created all my models to handle these tables (1 master model that handle basic read/write/update/verify while also considering my table relations

After that I start to code my views and controllers. I first created view HTML, then create controller that will handle this view, and started coding functions to make the view interactions work.

Example when coding the appointment view(controller booking.php):

created this layout and made table td's clickable,
when user click : jquery get (booking/add_patient_form) and pop it up

when user save  : post to booking/save -it save appointment then reload index() function

etc.. and I continued same steps of creating view then its controller -that contain all the logic this view needed - to accomplish whole project.

At the end I had all my target functions working fine, but since there was no PLAN from beginning and as the whole project was punch of brain storming and debugging with no what so ever plan, after I went so far in this project i find my self stuck with maintainability and flexibility! and unable to link them together.

I have feeling that every page on website is completely isolated from other and I can't even recall how each page is loaded and what functions are inside without peeking!

Is there anyway I can recover this and get a design out?


答:
A classic reason for single-entry-single-exit is that otherwise the formal semantics become unspeakably ugly otherwise (same reason GOTO was considered harmful).

Put another way, it's easier to reason about when your software will exit the routine if you have only 1 return. Which is also an argument against exceptions.

Typically I minimize the early-return approach.


问:
mvc pattern on procedural php
First off, I do not have anything against OO programming (I'd be mad if i believed so). But I was thinking on some sort of procedural MVC pattern with PHP; let me explain better.

As we all know, variable scopes, unless they are taken from $_SESSION (, database, redis, etc.) are never global and only refer to a singular execution of a script. For example:

```<code>class Car {
  this->name = "foo";
  function setName($name) { ... }
  function getName() { return $this->name; }
}
</code>```

Where obviously in a more common situation, this data will be taken from the DB, otherwise any object car, per execution, would have the same name.

Now, is it not possible to apply MVC pattern on procedural code for simplicity purpose? Imagine a really simple social network like application; I could have a structure like this

```<code>*views
  -profileview.php
  -messageview.php
  -loginview.php
  -notloggedin.php
*models
  -user.php
  -message.php
- profile.php
- messages.php
- login.php
</code>```

where profile, messages and login.php work as controllers and route to the right view; and user and message.php work as the classes, that contain all the functions that are eventually needed by the controllers, such as getUserById($id), postMessage($id, $meesage), etc.

I have simplified it a lot but I think you can sort of understand my point.

What would you think of such implementation on the long run, and why?

答:
It's very subjective, but why would you choose to do it "this way" rather than adopt a real framework for the purpose? If it's just to learn something new, I can see the value in it, but there's been hundreds if not thousands of man-hours invested into developing the current crop of PHP MVC frameworks, and even the worst of them is likely to be better than doing it this way.

As a stepping stone towards using a real framework, this is a good start - because it encourages the separation of concerns - but as an end result? It's awful.

Title: mvc pattern on procedural php


答:
As an example, let's say we have a user story that says: "As a customer, I need to be able to select a system state of A, B or C". It has an acceptance test that says "I should be able to select state A, B, or C, and the system will change to that state"

There's your problem, in my opinion. And Scrum, a project-management technique, which falls in the realms of Agile (don't confuse the two terms), isn't going to help you. But there are other Agile techniques that will. For this scenario, behaviour-driven development will be the place to look.

To explain why I think that's your problem: Your first statement isn't really a user requirement (Feature, in BDD) and the second isn't a behaviour definition (Scenario, in BDD).

```<code>Feature: State A

As a customer
I need to be able to select system state A
So that the fires of Mordor will burn

Feature: State B

As a customer
I need to be able to select system state B
So that the orcs will be at the gates
</code>```

(I am assuming that neither one of these requires the other, so they are separate features.)

Notice the "So that ..." clauses. They are an important part of a feature. If you have trouble writing "So that ..." on each feature then either you don't need that feature or the scope of it is too large. I suspect the latter in this case, hence I've broken it down into the three states.

Your test definition is similar, it doesn't really specify anything. BDD has a Given-When-Then syntax that helps us focus on the scenario we're testing:

```<code>Given that I am on the state selection screen
When I select state B
Then the horn of Mordor should sound
And the orc-cages should be unlocked
</code>```

Note that each clause can have And, But or Or extensions, if needed -- but, in general, When (the user action) should be a single defining action.

Going back to the three bugs you listed:

```<code># Selecting B sometimes doesn't uncheck the previous radio button.

Given that I am on the state-selection screen
When I select option B
Then options A and C should be deselected
</code>```

This is a perfectly valid test. Entirely unnecessary if you use standard library radio-buttons, but if you have this bug then you clearly don't, so you should account for it.

```<code># Sometimes option C is unavailable on the system, and so should be greyed out.

Given that state C is unavailable
When I load the state-selection screen
Then option C should be greyed out
And option C should be unusable

Given that I am on the state-selection screen
When state C becomes unavailable
Then option C should be greyed out
And option C should be unusable
</code>```

Two behaviors that should definitely be tested separately, assuming they are both required.

```<code># When first opened, the initial selection does not match the current system state.

Given that the current system state is C
When I load the state-selection screen
Then option C should be pre-selected
</code>```

Starting to get the idea? Don't get me wrong though, this is HARD WORK. But being Agile is a lot more disciplined than people think it is. If you're going to get and hold an ISO 9001 accreditation, you're going to need to decide which disciplines are for you and stick to them. If this is too much effort, you probably need to go back to functional specs.

Title: agile / scrum and functional specs

Body:
I work in a small team of four devs, one domain expert and one manager. We are looking to move to using scrum to try and formalise our processes.

From what I understand of agile, it seems to be close(ish) to what we are doing anyway. We have a brief document with the overall features our product will have. As we come to code each feature, we sit down and thrash it out verbally, relying on our domain expert for what the customer will want. We then code it, and it gets tested in vague ways by the other devs / domain expert. Improvements get suggested and implemented.

At our last ISO 9001 audit we were (deservedly) reprimanded for lack of any traceability. The auditor wanted some way of seeing we had records of what the product would do, and then testing to prove that it did it.

We are looking to scrum to give us a process for this, along with other benefits, but my reading up so far has not answered my question of where detailed functional requirements are recorded / tested? My understanding of agile / scrum is far from complete, so please correct me if I have misunderstandings.

As an example, let's say we have a user story that says:
"As a customer, I need to be able to select a system state of A, B or C".
It has an acceptance test that says
"I should be able to select state A, B, or C, and the system will change to that state"

Come the sprint where this gets implemented, we sit around and decide that we will build a widget with A, B and C radio buttons, and a "Apply" button. Then we code it.

When this widget is tested, the following problems are found:
1. Selecting B sometimes doesn't uncheck the previous radio button.
2. Sometimes option C is unavailable on the system, and so should be greyed out.
3. When first opened, the initial selection does not match the current system state.

My question is how and where is this recorded? There is no detailed functional spec saying "There will be a widget with three radio buttons. When the widget is created, the current radio selection should match the system state" blah blah. Given the lack of this document how are we supposed to prove that the system does or does not do what it's supposed to to an auditor?

Body:
As an example, let's say we have a user story that says: "As a customer, I need to be able to select a system state of A, B or C". It has an acceptance test that says "I should be able to select state A, B, or C, and the system will change to that state"

There's your problem, in my opinion. And Scrum, a project-management technique, which falls in the realms of Agile (don't confuse the two terms), isn't going to help you. But there are other Agile techniques that will. For this scenario, behaviour-driven development will be the place to look.

To explain why I think that's your problem: Your first statement isn't really a user requirement (Feature, in BDD) and the second isn't a behaviour definition (Scenario, in BDD).

Feature: State A

As a customer
I need to be able to select system state A
So that the fires of Mordor will burn

Feature: State B

As a customer
I need to be able to select system state B
So that the orcs will be at the gates

(I am assuming that neither one of these requires the other, so they are separate features.)

Notice the "So that ..." clauses. They are an important part of a feature. If you have trouble writing "So that ..." on each feature then either you don't need that feature or the scope of it is too large. I suspect the latter in this case, hence I've broken it down into the three states.

Your test definition is similar, it doesn't really specify anything. BDD has a Given-When-Then syntax that helps us focus on the scenario we're testing:

Given that I am on the state selection screen
When I select state B
Then the horn of Mordor should sound
And the orc-cages should be unlocked

Note that each clause can have And, But or Or extensions, if needed -- but, in general, When (the user action) should be a single defining action.

Going back to the three bugs you listed:

# Selecting B sometimes doesn't uncheck the previous radio button.

Given that I am on the state-selection screen
When I select option B
Then options A and C should be deselected

This is a perfectly valid test. Entirely unnecessary if you use standard library radio-buttons, but if you have this bug then you clearly don't, so you should account for it.

# Sometimes option C is unavailable on the system, and so should be greyed out.

Given that state C is unavailable
When I load the state-selection screen
Then option C should be greyed out
And option C should be unusable

Given that I am on the state-selection screen
When state C becomes unavailable
Then option C should be greyed out
And option C should be unusable

Two behaviors that should definitely be tested separately, assuming they are both required.

# When first opened, the initial selection does not match the current system state.

Given that the current system state is C
When I load the state-selection screen
Then option C should be pre-selected

Starting to get the idea? Don't get me wrong though, this is HARD WORK. But being Agile is a lot more disciplined than people think it is. If you're going to get and hold an ISO 9001 accreditation, you're going to need to decide which disciplines are for you and stick to them. If this is too much effort, you probably need to go back to functional specs.


问:
Should I calculate hotness of a post on request or pre-calculate it?
Here is the Reddit's hot algorithm:

```<code>cpdef double _hot(long ups, long downs, double date):
    """The hot formula. Should match the equivalent function in postgres."""
    s = score(ups, downs)
    order = log10(max(abs(s), 1))
    if s > 0:
        sign = 1
    elif s < 0:
        sign = -1
    else:
        sign = 0
    seconds = date - 1134028003
    return round(order + sign * seconds / 45000, 7)
</code>```

My brain says hotness of a post should be calculated on every request because old posts should have a low hotness score.

I implemented this function in MySql but as you might guess, it's slow. Very slow even indexes are there.

And then I think to update the hotness field of the post on every upvote or downvote of the post. Let's assume we have a post just posted now and has 100 upvote and 1 downvote and it's hotness is 78 (example). But it doesn't get any votes for 3 days. After 3 days a new post appears and gets 100 upvotes and 1 downvote and has 78 score. If I'm updating hotness score on votes, the 3 days old post and the new post will be show together. But in theory, the 3 days old post shouldn't even show up in front page.

What is the most viable method to implement for this situation?

答:
In my humble opinion (not an expert) is that you can update the hotness in the db on any upvote or downvote but to distinguish the new posts from the old ones you can apply some kind of equation to the hotness that you keep in the DB. Something like:

hotnesss = hotness_from_up_and_down_votes_in_DB + (150 - (today-post_date)) + ((15-(today-last_vote_date)) * 10)

this means posts will get less hotness with time and posts with more then 150 days start geting negative hotness for that and also the post that had votes in the last 15 days get hotness for that and after 15 days without votes they start getting negative hotness

if you dont want negative hotness you can do it like this:

hotnesss = hotness_from_up_and_down_votes_in_DB + (150 / ((today-post_date) + 1)) + ((15/(today-last_vote_date)) * 10)

same thing but with time you start getting 0 hotness instead of negative

NOTE: the + 1 on "((today-post_date) + 1))" it's just to prevent that today's posts from dividing 150 by 0

NOTE: you can set the thresholds as you like (the 150 and 15 days). If you want a better equation you can look at logaritmic or exponencial equations.

Hope it helped.


问:
Different Project Type in a Single Website
I have developed a website in asp.net and I have some additional tasks, improvements to develop. In order to get experience in asp.net/mvc, I want to create an admin panel using asp.net mvc.

Is this a logical next step?

P.S. The project is small and 20% of the website is mine, so there are not any restrictions. There is no problem if I do not meet deadlines! :)

答:
The discussion between those two similiar technologies are very long, and no one is better than other, only is for two different things.

On the ASP.NET WebForms (classic ASP.NET) you have a lot of controls, an extense collection of controls which you can pick, drag and drop and configure, its really fast but you have a lot of impediments when you want to manage at lower level the html of the page, and the code are very disordered.

On ASP.NET MVC you a lot of control on your html and you can do almost anything, i mean anything with styles and html but mostly you need to do by hand. But one of the great advantages of MVC is de order of the code, you always have ordered solution, projects, and clases, its a really great pattern.

Finally do not care to have different projects with different technologies, its a common case, most than you think, and if you think that MVC is better for the new project go ahead, its a really good choice.

I'll hope this help you. I'm a teacher of web development on the course 10264


答:
When should an exception be thrown? When it comes to code, I think that following explanation is very helpful:

An exception is when a member fails to complete the task it is supposed to perform as indicated by its name. (Jeffry Richter, CLR via C#)

Why is it helpful? It suggests that it depends on the context when something should be handled as an exception or not. On the level of method calls, the context is given by (a) the name, (b) signature of the method and (b) the client code, which uses or is expected to use the method.

To answer your question you should have a look on the code, where user input is processed. It might look something like this:

```<code>public void Save(PersonData personData) { … }
</code>```

Does the method name suggest that some validation is done? No. In this case an invalid PersonData should throw an exception.

Suppose that the class has another method which looks like this:

```<code>public ValidationResult Validate(PersonData personData) { … }
</code>```

Does the method name suggest that some validation is done? Yes. In this case an invalid PersonData should not throw an exception.

To put the things together, both methods suggest that the client code should look like this:

```<code>ValidationResult validationResult = personRegister.Validate(personData);
if (validationResult.IsValid())
{
    personRegister.Save(personData)
}
else
{
    // Throw an exception? To answer this look at the context!
    // That is: (a) Method name, (b) signature and
    // (c) where this method is (expected) to be used.
}
</code>```

When it is not clear if a method should throw an exception, then maybe it is due a poorly chosen method name or signature. Maybe the design of the class is not clear. Sometimes you need to modify the code design to get a clear answer to the question if an exception should be thrown or not.

Body:
When should an exception be thrown? When it comes to code, I think that following explanation is very helpful:

An exception is when a member fails to complete the task it is supposed to perform as indicated by its name. (Jeffry Richter, CLR via C#)

Why is it helpful? It suggests that it depends on the context when something should be handled as an exception or not. On the level of method calls, the context is given by (a) the name, (b) signature of the method and (b) the client code, which uses or is expected to use the method.

To answer your question you should have a look on the code, where user input is processed. It might look something like this:

public void Save(PersonData personData) { … }

Does the method name suggest that some validation is done? No. In this case an invalid PersonData should throw an exception.

Suppose that the class has another method which looks like this:

public ValidationResult Validate(PersonData personData) { … }

Does the method name suggest that some validation is done? Yes. In this case an invalid PersonData should not throw an exception.

To put the things together, both methods suggest that the client code should look like this:

ValidationResult validationResult = personRegister.Validate(personData);
if (validationResult.IsValid())
{
    personRegister.Save(personData)
}
else
{
    // Throw an exception? To answer this look at the context!
    // That is: (a) Method name, (b) signature and
    // (c) where this method is (expected) to be used.
}

When it is not clear if a method should throw an exception, then maybe it is due a poorly chosen method name or signature. Maybe the design of the class is not clear. Sometimes you need to modify the code design to get a clear answer to the question if an exception should be thrown or not.


答:
From experience (on a large project in a 600,000+ line codebase, which was kept out of releases for 3 years using #ifdefs) my arguments against using them would be:

They reduce the readability of the code - particularly as some IDEs insist on placing them at the start of the line ignoring the indentation level.

They add complexity, both to the devs working on the segregated feature and to the devs trying to work around them.

That additional complexity slows down productivity - in our case I'm convinced it added several months to the project.

Removing them once the feature is released is not a zero cost task - in our case it was a week long task for someone to go through and remove all the #ifdefs and resolve the conflicts with the code that had been added in #elseifs.

All in all it was a glorious day when we migrated to Mercurial - we still have a huge, overly complex code base, but at least we can branch efficiently now.

Title: hginit - #ifdefs ridiculous


答:
When you have long-running processes, it is best to not make a request dependent on the completion of the process. If giving the user the most up-to-date hotness score is not of utmost importance, you could probably get away with giving the user a relatively close score.

Instead of launching this calculation on each request, you should have some sort of mechanism to trigger a background process that pulls the needed data, calculates the hotness and updates a set value for the post. Your database would like something like:

```<code>/* Other Post Data */
postViews - BIGINT // Number of actual post views
postViewsLastRun - BIGINT // Number of post views at last hotness job
lastViewed - DATETIME  // Timestamp of the last viewing of the post
lastCalculated - DATETIME // Timestamp of the last hotness job
hostness - INT // Hotness rating to display to the user
</code>```

Depending on what you feel is appropriate, you may wish to recalculate hotness after every n number of post views, or perhaps you want to calculate it every hour.

For the former, you would pull the postViews and postViewsLastRun column, increment it, and check it against your threshold of posts. If the difference between postViewsLastRun and postViews meets or exceeds your threshold, you would want to update the postViewsLastRun spin off a process with some sort of job scheduler to handle the processing and updating of the hotness score.

For the latter, you would have a scheduled process to run, say every hour. It would check if there was whether the post was viewed or not in the within it's threshold amount of time by checking the current time against the lastCalculated column. Assuming the criteria for another calculation are met, it would spin off a job to handle processing and continue checking the relevant data for other posts in the database.

Now whenever a user requests a post's data, you can give them a relatively accurate hotness rating, based on your criteria for accurate, and it will not cause any latency because of a long running calculation. In your case, you won't want any stale information to show up, because this would cause a bad user experience, so you would want to use the approach that runs at a regular interval of time.

Title: Should I calculate hotness of a post on request or pre-calculate it?

Body:
Here is the Reddit's hot algorithm:

```<code>cpdef double _hot(long ups, long downs, double date):
    """The hot formula. Should match the equivalent function in postgres."""
    s = score(ups, downs)
    order = log10(max(abs(s), 1))
    if s > 0:
        sign = 1
    elif s < 0:
        sign = -1
    else:
        sign = 0
    seconds = date - 1134028003
    return round(order + sign * seconds / 45000, 7)
</code>```

My brain says hotness of a post should be calculated on every request because old posts should have a low hotness score.

I implemented this function in MySql but as you might guess, it's slow. Very slow even indexes are there.

And then I think to update the hotness field of the post on every upvote or downvote of the post. Let's assume we have a post just posted now and has 100 upvote and 1 downvote and it's hotness is 78 (example). But it doesn't get any votes for 3 days. After 3 days a new post appears and gets 100 upvotes and 1 downvote and has 78 score. If I'm updating hotness score on votes, the 3 days old post and the new post will be show together. But in theory, the 3 days old post shouldn't even show up in front page.

What is the most viable method to implement for this situation?

Body:
When you have long-running processes, it is best to not make a request dependent on the completion of the process. If giving the user the most up-to-date hotness score is not of utmost importance, you could probably get away with giving the user a relatively close score.

Instead of launching this calculation on each request, you should have some sort of mechanism to trigger a background process that pulls the needed data, calculates the hotness and updates a set value for the post. Your database would like something like:

/* Other Post Data */
postViews - BIGINT // Number of actual post views
postViewsLastRun - BIGINT // Number of post views at last hotness job
lastViewed - DATETIME  // Timestamp of the last viewing of the post
lastCalculated - DATETIME // Timestamp of the last hotness job
hostness - INT // Hotness rating to display to the user

Depending on what you feel is appropriate, you may wish to recalculate hotness after every n number of post views, or perhaps you want to calculate it every hour.

For the former, you would pull the postViews and postViewsLastRun column, increment it, and check it against your threshold of posts. If the difference between postViewsLastRun and postViews meets or exceeds your threshold, you would want to update the postViewsLastRun spin off a process with some sort of job scheduler to handle the processing and updating of the hotness score.

For the latter, you would have a scheduled process to run, say every hour. It would check if there was whether the post was viewed or not in the within it's threshold amount of time by checking the current time against the lastCalculated column. Assuming the criteria for another calculation are met, it would spin off a job to handle processing and continue checking the relevant data for other posts in the database.

Now whenever a user requests a post's data, you can give them a relatively accurate hotness rating, based on your criteria for accurate, and it will not cause any latency because of a long running calculation. In your case, you won't want any stale information to show up, because this would cause a bad user experience, so you would want to use the approach that runs at a regular interval of time.


答:
Given the lack of this document how are we supposed to prove that the
  system does or does not do what it's supposed to to an auditor?

Why is that a given? There is no rule of scrum that the only thing created is software. Make your acceptance criteria include "done when we have a detailed ISO 9001 compliant functional specification". Or, make that a separate story altogether: "as a developer on an  ISO 9001 team, I need a functional spec so that our software is compliant". Create the spec, and then from that you can come up with the stories necessary to implement that spec.

In the comments to this question, @Pete expressed concern that if the spec were a story, how can the product be "potentially shippable" if all that is delivered after an iteration is a spec?

Look at it this way: your end product is composed of many pieces: A, B, C, D, etc. At the end of each iteration you should have one of those pieces finished and potentially shippable, right? When A is done it should be potentially shippable. When B is done it should be potentially shippable, and so on.

Where does it say that A must be a software product? A can be potentially shippable even if it is simply a functional spec, or a test case, or a DB schema, etc.

Don't look at your functional spec like it is somehow outside of your product. Instead, see it as an integral part of the product you are delivering, on equal footing with software, DB schemas, test cases, user guides, etc.

Title: agile / scrum and functional specs


答: Others have answered well, but still here is my short answer. Exception is situation where something in the environment has wrong, which you can not control and your code can not go forward at all. In this case you will also have to inform the user what went wrong, why you cannot go further, and what is the resolution. </p>


问:
Ensuring conceptual integrity in Python project with multiple programmers
One objection that I have often heard raised against Python that it is difficult to synchronize a team of many programmers on large Python project. Note: that synchronization is possible in such a project does not necessarily entail that it is practical, cheap or easy. There's still n*(n-1) communication channels between programmers, so communication cost grows more or less with square of number of programmers, on average.

One thing I liked in Java are interfaces. Sadly, both PEP 245 and even modified Guido's version on interfaces ( http://www.artima.com/forums/flat.jsp?forum=106&thread=87182 ) have not been implemented. I was thinking that duck-typing style limited interfaces (no types, just method names) might be very useful, emphatically not for sake of pychecker, faster code, or forcing (dumb) programmers to follow (smart) architect's design, but as means of easy synchronization between 2+ programmers.

So, apart from typical but not working very well suggestion of "more documentation" (nobody wants to write it really), what are your means of synchronization high-level design and conceptual integrity on such large, multi-person projects?

(in part I ask because large projects I have participated in never used Python)

I heard objections mentioned above in person: At least 3 times when talking to startups (2 Scala startups, so they have slant towards static typing) and at least once within corp when considering various programming languages for projects. On the web: can't remember this now, I have vague memory of reading it on some OO blogs and forums. Static typing guys (Java, Scala) seem to have had big on this point, even though typically static typing and interfaces are usually meant for other things (speed, IDE autocompletion).

Note I know TDD defense on this but the problem here is that it is defensive since typically it's one person that writes unit tests. Of course, one could envision 1+ programmers sitting down together and writing unit tests before coding as sort of indirect spec + test but have you seen it done? I haven't.  I also feel that unit tests, even written by groups, are not quite (limited) design or spec. They are low level after all. There's a reason (good maybe?) that Java has interfaces in addition to and not instead of JUnit.

答:
I think you're focusing too much on the language that you are using and not the real challenge that's facing you and your team.  Remember that there aren't any silver bullets.

Ultimately, your problem is governance.  As governance is really the only way to ensure conceptual integrity for any project.

The need for governance follows either a linear or exponential path correlated to the size of the team.  When you add in geographic and cultural divides, you're simply piling on to the need for governance.

There are some simple ways to get started.

If no one wants to write a whole bunch of documentation, then make sure code is commented liberally and correctly.  Avoid littering with your comments, but make sure others understand the contracts that each section of code is fulfilling.

If you don't want others accessing particular parts of code and you can't encapsulate it, then you should be putting comments around those areas to indicate what can and can't be used.  Even if the language doesn't directly support it, you can still mock up interfaces and closed objects within the code.  FWIW, I've written OO style code in C.  It can be done.

One of the ways you enforce that encapsulation is code review.  The tribal elders from each team needs to review all new code before it's allowed into the build.  If you have an architect, then they need to be in constant communication with the tribal elders to make sure they understand the vision and that everyone is in agreement with how the project will be built.

Management has to back the architect and the elders at the first skirmish.  Someone is going to break the rules and insist it goes in because you're behind the deadline.  Don't do it.  Politely slap the violator's wrist; force them to fix the code; then allow the commit.  Management has to back missing the deadline to guarantee the integrity of the project.  Yes, you missed a deadline but you have to focus on the long term goal.

As mentioned in the comments; everyone should be writing unit tests for their code.  Assigning that task to a single person is setting the project up for failure.  Use those tests to enforce the encapsulation and rules needed to stabilize your project.  If new code doesn't have a unit test then don't allow the requirement to be marked complete.

Ensuring the integrity of a project is everyone's responsibility with each tier taking on differing aspects based upon their own job function.


答:
How "designy" is the menu? That is to say, how elaborate is the placement of the text? My immediate thought on this problem is that if there's the least little bit of creative license in the menu (ie, certain items being different from other related items), then just maintain it in two locations.

As programmers, we tend to default to thinking about uniform data being rendered through templates/repeaters. If there's 7 entrees, then of course we can just define a template for an entree and push them through to it! WRONG. Today, the chef wants the salmon to get indented and bolded on the menu with a little fish by it, but the hamburger needs to pop over to the left to make room for the big capital letter on the next line ... and so forth and so on.

Furthermore, you have very real problems when it comes to physically printing a menu that don't exist from a data perspective. Like the number of pages. If you just have repeating sections that fill the page from a datastore, there's no good way to guarantee against page breaks. If the restaurant adds 6 entrees, they'll probably play around with the formatting of the entree section to keep the menu roughly the same overall proportion.

Before programming, I used to be in the printing world, and I saw quite a lot of menus being fiddled with and tweaked by graphic designers constantly. There's actually a whole field of psychology on menu item placement and pricing!! Here's an interesting article on the subject: http://rrgconsulting.com/psychology_of_restaurant_menu_design.htm The short version is that the design of the menu effects consumer choice greatly. Meaning that as different entrees become attractive to management as their profitability changes, the restaurant will want the design to change to accommodate this.

So you have two options: build a system by which items are stored in a data source, with options for virtually every possible design configuration, and print the PDF from that. Or just tell the chef that when he/she changes the menu PDF (from Word, or whatever), that they must change the textfile/CMS that powers the website at the same time. The former is going to be very expensive and will take a long time to perfect, and the latter is fast, cheap and takes the responsibility off you.

So can you implement a perfectly designed Menu Generator that allows for great flexibility in the PDF output, while keeping the website up to date at the same time? Sure! But is there any hope of it being cheap or fast? Not a chance in hell.

Title: Strategies to avoid data entry duplication between PDF vs. website (e.g. restaurant menus)

Body:
I'm building a website for a restaurant. They have a downloadable PDF version of their menu (which is what the "real-world" menu is printed from), but we also want to have a text-based version of the menu on the website (because it's the 21st century and you shouldn't have to read a PDF when browsing a site like this).

I'm hoping to avoid -- or minimize as much as possible -- the potential problems with maintaining data in two places (one in the PDF and one on the website).

In an ideal world, we'd build a custom dashboard interface for managing menu data, with a fully-normalized schema, and from that data we'd automatically generate the PDF and the website versions of the menu (and come up with a very expensive and flexible visual design for the PDF menu that takes into account all future permutations of data that may be contained within it -- because the visual layout of the PDF menu is very important, since that's what the "real-world" menu is printed from).

But, since the budget is not unlimited, I'm trying to think of other ways to accomplish this goal. Are there any compromise solutions or "this gets you halfway there" kind of things I could do? Obviously I'm not expecting a perfect and cheap solution, but anything that minimizes the double-data entry to the extent that it's not so much of a chore would be really helpful.


答:
Exceptions should be exceptional: It's expected that the user may
  input invalid data, so this isn't an exceptional case

On that argument:

It's expected that a file may not exist, so that isn't an exceptional
case.

It's expected that the connection to the server may be lost, so that isn't an exceptional case

It's expected that the configuration file may be garbled so that isn't an exceptional case

It's expected that your request may sometimes fall out, so that isn't an exceptional case

Any exception that you catch, you must expect because, well, you decided to catch it. And so by this logic, you should never throw an any exceptions you actually plan to catch.

Hence I think "exceptions should be exceptional" is a terrible rule of thumb.

What you should do depends on the language. Different languages have different conventions about when exceptions should be thrown. Python, for example, throws exceptions for everything and when in Python, I follow suit. C++, on the other hand, throws relatively few exceptions, and there I follow suit. You can treat C++ or Java like Python and throw exceptions for everything, but your working at odds with how the language expects itself to be used.

I prefer Python's approach, but I think it a bad idea to shoehorn other languages into it.


问:
Where to check that a function actually did what I told it to?
Consider this function intended to kill all running instances of a subprocess:

```<code>killAllFoobars()
{
    pids = getRunningFoobars();

    foreach ( pids as p ) {
        killOneFoobar(p);
    }

    return TRUE;
}
</code>```

Where should I check that in fact all Foobars were killed? Should killOneFoobar() check that its Foobar is now killed? Should killAllFoobars() check that there are no more running Foobars before returning TRUE (seems a bit disingenuous to return TRUE without checking). Should the function calling killAllFoobars() check?

Consider that the check is an expensive operation, so should not be done 'just whenever' but rather only when necessary.

答: You will never be sure that all the Foobars are killed (what if a new foobar is created after the check, but before returning from the function?). Just make sure that the killing functions work as intended. If you want to do more, you may loop forever, killing new processes as they are created.</p>


答:
There's a lot of philosophical pontification here, but generally speaking, exceptional conditions are simply those conditions which you cannot or don't want to handle (other than cleanup, error reporting, and the like) without user intervention.  In other words, they are unrecoverable conditions.

If you hand a program a file path, with the intention of processing that file in some way, and the file specified by that path doesn't exist, that's an exceptional condition.  You cannot do anything about that in your code, other than report it to the user and allow them to specify a different file path.


问:
Temporary variables vs line length requirements
I've been reading Martin Fowler's Refactoring. It is generally excellent but one of Fowler's recommendations seems to be causing a little trouble.

Fowler recommends that you replace temporary variables with a query, so instead of this:

```<code>double getPrice() {
    final int basePrice = _quantity * _itemPrice;
    final double discountFactor;
    if (basePrice > 1000) discountFactor = 0.95;
    else discountFactor = 0.98;
    return basePrice * discountFactor;
}
</code>```

you pull out into a helper method:

```<code>double basePrice() {
    return _quantity * _itemPrice;
}

double getPrice() {
    final double discountFactor;
    if (basePrice() > 1000) discountFactor = 0.95;
    else discountFactor = 0.98;
    return basePrice() * discountFactor;
}
</code>```

In general I agree except that one reason I use temporary variables is when a line is too long. For example:

```<code>$host = 'https://api.twilio.com';
$uri = "$host/2010-04-01/Accounts/$accountSid/Usage/Records/AllTime";
$response = Api::makeRequest($uri);
</code>```

If I tried inlining that, the line would go longer than 80 characters.

Alternately I end up with chains of code, which are themselves not that much easier to read:

```<code>$params = MustacheOptions::build(self::flattenParams($bagcheck->getParams()));
</code>```

What are some strategies for reconciling the two?

答:
Helper methods have a place, but you have to be careful about ensuring consistency of data, and unnecessary increase in scope of variables.

For example, your own example cites:

```<code>double getPrice() {
    final double discountFactor;
    if (basePrice() > 1000) discountFactor = 0.95;      <--- first call
    else discountFactor = 0.98;
    return basePrice() * discountFactor;                <--- second call
}
</code>```

Clearly both _quantity and _itemPrice are global variables (or at least class level) and therefore there is a potential for them to be modified outside of getPrice()

Therefore there is a potential for the first call to basePrice() to return a different value from the second call!

Therefore, I would suggest that helper functions can be useful to isolate complex mathematics, but as a replacement for local variables, you need to be careful.

You also have to avoid reductio ad absurdum - should the calculation of discountFactor be hived off to a method? So your example becomes:

```<code>double getPrice()
{
    final double basePrice      = calculateBasePrice();
    final double discountFactor = calculateDiscount( basePrice );

    return basePrice * discountFactor;
}
</code>```

Partitioning beyond a certain level actually makes the code less readable.

Body:
Helper methods have a place, but you have to be careful about ensuring consistency of data, and unnecessary increase in scope of variables.

For example, your own example cites:

double getPrice() {
    final double discountFactor;
    if (basePrice() > 1000) discountFactor = 0.95;      <--- first call
    else discountFactor = 0.98;
    return basePrice() * discountFactor;                <--- second call
}

Clearly both _quantity and _itemPrice are global variables (or at least class level) and therefore there is a potential for them to be modified outside of getPrice()

Therefore there is a potential for the first call to basePrice() to return a different value from the second call!

Therefore, I would suggest that helper functions can be useful to isolate complex mathematics, but as a replacement for local variables, you need to be careful.

You also have to avoid reductio ad absurdum - should the calculation of discountFactor be hived off to a method? So your example becomes:

double getPrice()
{
    final double basePrice      = calculateBasePrice();
    final double discountFactor = calculateDiscount( basePrice );

    return basePrice * discountFactor;
}

Partitioning beyond a certain level actually makes the code less readable.


问:
Applying Denotational Semantics to design of Programs
I've read a bit on denotational semantics (DS) and I'm very intrigued about the process of designing computer programs where types and functions have strong and clear mappings to mathematics.

Are there any resources that discuss designing programs based on DS in detail?  I've seen a few superficial treatments of the subject.

I'm conversant in Haskell, Scala, Common Lisp, and a bit of Scheme so any resources that use those languages would be greatly appreciated.

答: We have applied denotational semantics to language design itself, arguing that the design of languages, in particular, domain-specific languages, should start with the definition of the semantics. If you are interested in the details, you might want to take a look at Semantics-Driven DSL Design and Semantics First! Rethinking the Language Design Process. </p>

OwnerDisplayName: Tim Stewart


问:
Non-lvalues as function parameters in C++
I'm reading Accelerated C++ and in Chapter 4 they bring up the concept of lvalues. There's an example of something that shouldn't work, but after trying it myself I found that it does indeed work.

Specifically they state that, given these functions:

```<code>// return an empty vector
vector<double> emptyvec()
{
  vector<double> v;
  return v;
}

// read things from an input stream into a vector<double>
// (I'm leaving out the function body here because it's irrelevant)
istream &read_things(istream& in, vector<double>& hw);
</code>```

This should not be allowed:

```<code>read_stuff( cin, emptyvec() );
</code>```

Because emptyvec() is an expression and returns a temporary object (a non-lvalue as they called it in the book). However, this not only compiles but actually runs (Windows 7/VisualStudio 2010).

So, what's going on? Was this just a bad example on the authors' part, or is there something else happening that I don't understand.

Thanks.

答:
The concern the book mentions would come into play if the function was declared as:

```<code>vector<double> &emptyvec()
</code>```

or

```<code>vector<double> *emptyvec()
</code>```

as it would then be returning a temporary value by reference, and by the time you used the reference, the value it referred to would be gone.  Your compiler should issue a warning or an error for this case, and you might (but might not) see a variety of possible failures at run time (sadly, the type of error you would see could vary widely).

On the other hand, if the function is indeed declared as

```<code>vector<double> emptyvec()
</code>```

the vector is being returned by value (i.e. a copy of the actual vector is being made into wherever you store the return value), and the program should work correctly.

Body:
The concern the book mentions would come into play if the function was declared as:

vector<double> &emptyvec()

or

vector<double> *emptyvec()

as it would then be returning a temporary value by reference, and by the time you used the reference, the value it referred to would be gone.  Your compiler should issue a warning or an error for this case, and you might (but might not) see a variety of possible failures at run time (sadly, the type of error you would see could vary widely).

On the other hand, if the function is indeed declared as

vector<double> emptyvec()

the vector is being returned by value (i.e. a copy of the actual vector is being made into wherever you store the return value), and the program should work correctly.


问:
Is there something like a polymorphic Singleton?
I have a resource loader object that loads objects from the disk or from a ZIP archive, depending on the platform.

It has state (e.g. the path to the directory or the ZIP archive, and possibly some caching in the future), so it needs to be a single instance.

So normally, a Singleton would do. But my problem is that this resource loader has multiple implementations, of which one is chosen at initialisation. So turning the resource loader into a Singleton won't do.

All I can think of is to have a Singleton that holds a reference to the single resource loader. But isn't there a nicer pattern for this?

答:
Sounds like you have a use case for an Inversion of Control (IoC) Container -- they use what's called Dependency Injection (DI) to create/initialize instances of objects and wire things together for operation.

(This article about IoC Containers and DI might not be the best intro to IoC Containers (I can't seem to find a good one at the moment), but it's a good read.)

From what I've read they're similar to Factories and are good for instantiating things at run-time.

An SO post that might be of interest: Dependency Injection vs Factory Pattern

I'm not sure how this would work with getting only a single instance -- I've not used one before, only read about them.


答: It's a compiler extension on the part of Visual Studio. The code should indeed not compile, and it won't on the other major compilers like GCC and Clang, as a temporary cannot bind to a mutable reference.</p>

Title: Non-lvalues as function parameters in C++

Body:
I'm reading Accelerated C++ and in Chapter 4 they bring up the concept of lvalues. There's an example of something that shouldn't work, but after trying it myself I found that it does indeed work.

Specifically they state that, given these functions:

```<code>// return an empty vector
vector<double> emptyvec()
{
  vector<double> v;
  return v;
}

// read things from an input stream into a vector<double>
// (I'm leaving out the function body here because it's irrelevant)
istream &read_things(istream& in, vector<double>& hw);
</code>```

This should not be allowed:

```<code>read_stuff( cin, emptyvec() );
</code>```

Because emptyvec() is an expression and returns a temporary object (a non-lvalue as they called it in the book). However, this not only compiles but actually runs (Windows 7/VisualStudio 2010).

So, what's going on? Was this just a bad example on the authors' part, or is there something else happening that I don't understand.

Thanks.


答:
Exceptions were invented to help make error handling easier with less code clutter.  You should use them in cases when they make error handling easier with less code clutter.  This "exceptions only for exceptional circumstances" business stems from a time when exception handling was deemed an unacceptable performance hit.  That's no longer the case in the vast majority of code, but people still spout the rule without remembering the reason behind it.

Especially in Java, which is maybe the most exception-loving language ever conceived, you shouldn't feel bad about using exceptions when it simplifies your code.  In fact, Java's own Integer class doesn't have a means to check if a string is a valid integer without potentially throwing a NumberFormatException.

Also, although you can't rely just on UI validation, keep in mind if your UI is designed properly, such as using a spinner for entering short numerical values, then a non-numerical value making it into the back end truly would be an exceptional condition.


问:
Designing a list class with filtering and sorting
The app I'm developing needs to display lists of items. Simple enough, but there are a number of things which can change based on user input:

Items can be added to/removed from the list.

The items in the list can be updated. Multiple items can be updated simultaneously!

The filters can be updated. Multiple filters can be updated simultaneously!

The sort order of the items can change.

Possibly relevant info:

It's a multiplatform Java app.

One of the platforms we distribute on is MIDP, so that limits which language features/libraries/etc we can use.

The implementation is currently split into a model class (in the common code) and device-specific view/controller classes.

I've tried a couple of approaches to designing a suitable list implementation, but both have drawbacks:

Approach 1:

The platform-specific controller implementations are responsible for calling a refresh() method whenever anything happens which could change the list.

This approach keeps the list class (model) implementation fairly straightforward, but leaves much of the responsibility up to the platform-specific controller implementations. The more logic there is in these classes, the greater the chance of bugs creeping in. It also encourages the controllers to directly notifying the view of updates, which feels like poor design.

Approach 2:

The model is entirely responsible for raising events to notify the platform-specific views of changes. The list items, filter, and sorters notify the model when they change, which then notifies the views of changes.

This keeps the platform-specific classes much simpler, and feels like a stronger design (less coupling between the classes, etc). However, the list class implementation becomes much more complicated.

My main problem with this approach is dealing with a proliferation of events when multiple items/filters are updated in a single operation.

My questions:

Is there other approaches I could/should be trying?

Is there a recognised way to manage/avoid the explosion of events in approach #2?

答:
As the lists are the model (and the items are only parts of them), I would suggest the following process:

When changed, items raise events to the list in which they are placed.

When changed (directly or via a change in the items), lists raise events to the depending views.

Lists filtering and sorting only concern the views. So the sorters and filters are not longer active elements but just passive elements manipulated by the views.

I don't know. The fact to restrict the filtering and sorting activities to the views themself will reduce the number of events sent. The single other way I can imagine for reducing the number of events sent is to be as specific as possible so that only the concerned receivers receive an event. An alternative could be to gather the events in a "super-event" received by "something" acting consequently, but I fear it is not conceptually a better solution.


问:
How do you deal with an information hoarder?
We must have all come across them - developers that have been around for ages and have a fantastic domain knowledge and yet they fail to share that knowledge with their team.

The team desperately needs to share the knowledge, but they can't seem to pry it out of the hoarder.

In what ways have teams successfully solved this problem?

答:
Would it be in the best interests of both parties if the information
hoarder was encouraged to find a company with a smaller size
or even to start his or her own company? Perhaps the person would thrive in
that smaller type of environment. (Am curious if anyone
has ever tried this approach in the real world, as well.)</p>


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答:
A common HR thing that drives me nuts when I'm job hunting: the implicit assumption that all coding skills are language-specific, that there is no software engineering expertise that transcends command sets.  That ten years experience in Java and another five in Perl mean you'd be completely useless on a project that uses, say, C#.

"Yes, there's a learning curve.  But I've made harder transitions than this.  I'll make you a deal, pay me 80% for the first month and at the end of that time if I'm not ... oh, wait, we're not actually having this conversation, because your HR monkey simply deleted my application."