问:
To use or not to use a backing app for website?
By suggestion in comments, I'll try to rephrase my question to better reflect my problem:

I have to present users (few at first, as many as possible later) with a website. There they will be able to browse various data. The data will be served from a local "cache" db. Users should be always presented with data as fresh as possible.

The source for most of the data will be external services with possible limits, long response times etc. The process of processing data from those sources to the schema of local db is also not straightforward (conversion, calculations, decoupling, recreating relations etc.)

Is putting all that data mining and processing code ok (and doing all that work in the time between users click a link and receive data), or is my second idea - another, constantly running data-miner application - better? Or is there another option?

Old text:

I'm currently developing a website that will present both its own data (user profiles, their submited content) as well as data obtained from various external sources (e.g. via webservice calls).

Varied sources will have varied limits of allowed calls, will respond with varied speed etc.

No, the data user is presented with should be, by default, as fresh as possible with an option to request refresh (unless refreshed very recently).

I started development in ASP.NET (for better or for worse), with some templates and some customization, and quite a lot of coding I ended up with a workable proof of concept. But then I started to think about large-scale operations.

Displaying cached data is quick and easy, I didn't mess that up. Refreshing though is a problem.

a) Requesting data for one user is fast, but it will eat through allowed api calls quickly.
b) Requesting data for multiple users (for apis that allow that) saves potentialy great amount of api calls, but takes linearly longer (not 1:1, but still, it takes time to request, receive and parse tens of times more data than single request).

There also comes the problem of exceeding the limits. Usually that would force the app to either cancel refresh, or wait few seconds for new allowance. But I don't really see the user happily waiting for several seconds for the page to load.

I am currently concidering gutting the data-gathering part of the website and moving it into a single managing application, sharing a db with the website. The website would provide info which users need their data to be refreshed, the app would load-balance the external services to use them efficiently (not limited to "when a user opens a website"), and keep the data as fresh as possible - also possibly keeping part of the allowance for forced refreshes.

Now, the main problem I see with this is cost of hosting not just website, but also a background running .NET application. But let's assume that the cost is not that relevant. What I actually fear is that I overcomplicate the solution. I might just put more of the website in Ajax and just wait for the request to complete in the background (when calls become available).

So, does anyone has any simillar experience? I'm especially interested in the scenario where it is all scaled up, that is we can assume that there will always be deficit of available calls.

PS I also worry about keeping website (which can be triggered independently by many users) from trying to refresh the same records twice etc. - I guess I should put some additional safeguards, lock or at least mark the records undergoing refresh etc. - a lot of code just to solve the problem that wouldn't exist with a single-backend....

答:
If you're making calls to a 3rd party service and that service's response is not dependant on the user's request then yes - consider making a data miner gateway between you and the service.

The key points to decide are whether the 'cost' of calling the service is prohibitive, if you are calling it repeatedly to fetch the same data then there's no reason why you need to call it on every request (eg a stock price say, where users get data every 15 minutes, you can simply call it once every 15 minutes to refresh the price). If however, you do need to update it based on the user, then its going to weigh heavily in favour of calling every request and the data miner will not work well.

I have done similar things - usually for data that is received independently of the user requests - eg GPS signals for a vehicle, the data comes in when it likes and it got stored in a dB that the user would read from when the user needed to know where the vehicle was.

Waiting for multiple users to request the same data is a poor choice though - make the call for the first user and cache the results, if another user requests that data within a time limit, respond from the cache instead. Where the cache is not filled with the right data, let the cache make the request to the 3rd party to fill itself while blocking the user request, then the newly-filled cache will be the only interface for all user requests - that kind of architecture makes life easier.


问:
How to enrich a simple two endpoint SOAP application to become enterprise level?
Imagine you have some exchange of data between two endpoints (webservices or let's call URL).
Data can travel in any way (Xml, Json, GET, POST) it doesn't matter.

I've got the source code of the first endpoint (I drawed it on the left).
The second one is from a third party and will call back my infrastructure on a third endpoint (which is also part of my infrastructure).

I would like to implement some session / state to relate the first call to their callback.
And I would also like to add distributed logging, support for problem solving in a production environment, configuration, performance monitoring, a dashboard, and so on.

What kind of consideration should I do in facing the design of this kind of architecture?

Let me clarify with an example (which answers to @SparKotॐ comment)

I should log the first call and understand if the third party is calling me back or not.

I can do this only if my "3rd party" caller Class (the white box higher on the lef) and the Class called from the "3rd party" (the white box lower on the lef) shares some logging infrastructure. How would you implement this?

Possibilities are:

Share a database

Share a message queue

Share a WCF service

Share some AppFabric cache

What else?

Pipeline?

Which consideration would you make about this tracking service? Should both my class being hosted on the same server? What kind of question would drive you to design the architecture which transform two simple WebClient.Open request into something which is more traceable and fault tolerant?

答:
This answer is just to document the first effort I did for solving problems. It's not complete so it would not be the accepted answer.

However there is still no other complete answer here. Since that I hope you will appreciate my effort.

Actually the code is structured as in the first design. But I think it's not very readable.

Problems before the architectural changes

The namespaces name are saying nothing of the responsability of each class

Is it really useful to split between DAO and BLO layer a so small architecture? There is almost no logic.

The logic / responsability of the BLO is not identifiable by the names of class / methods / namespace

What is UserType? The namespace is not grouping it with any other class..

Config class is a good name for me since it identifies a functionality. But It's the only class with a precise purpose specified by its name.

Get3rdPartyUrl and logging in (to that url) could all be put together in a same class, while InitializeConfigValue and ParseErrorMessage could be put into some other Help class.

Contacting a 3rdParty WS is reusable. Everything should inherit from just one interface also defining logging.

Class design before refactoring

Class design after refactoring

ContentLicense: CC BY-SA 3.0


问:
Am I bound by the license of a library that is used in my project but is not distributed with it?
I want to publish a small open source project on GitHub. I'd like to release it with either MIT or Apache license.

The project has unit tests that use JUnit library.  JUnit is released with the Eclipse Public License v1.0. JUnit is not distributed in the project - it is downloaded and used at build time by Maven, the build tool.

Am I bound by the license of a library that is used in the project but is not distributed with it? If I am, can I use a library released with the Eclipse Public License in MIT or Apache licensed projects?

My own thoughts (the most pessimistic scenario)

As the unit tests use JUnit, the project is a derivative work of JUnit, even though JUnit is not distributed with it. Distributing the project automatically means distributing JUnit.

The Eclipse Public License (the JUnit's license) says:

A Contributor may choose to distribute the Program in object code form
  under its own license agreement, provided that … its license
  agreement:

There is a list of four requirements here that sound trivial but which, perhaps, are not fully addressed in the MIT and Apache licenses (disclaiming all warranties, excluding any liability, a statement about additional provisions, a statement about availability of the source code).

So, the Eclipse Public License may not be compatible with the MIT and Apache licenses, and I may not be able to use JUnit.

答:
As a general rule, if you don't distribute someone else's code you are not obliged by any of its licence terms when you distribute your own. The liability comes at the point where the code is actually merged.

Assume that A writes and distributes code for B to use, and that A's program uses code written by C but A does not distribute any of it. Then the liability for compliance with C's licence falls with B, the user, at the point where A's code is merged with C's. B would need to be warned of this liability.

Sorry if that's complicated, but it's not easy to explain clearly. The point is that copyright law is mostly about copying (distribution) and not so much about using (consuming).

As I tell people repeatedly, if you make no money out of it and harm no-one then just do your best and don't worry too much. If you make money out of your product or services and/or if you may cause damage to someone, you must take competent legal advice. That won't protect you, but it will warn you of the risks and perhaps how to mitigate them.

Re your other question, it seems to me that Apache and MIT would be compatible with a work released under EPL but not necessarily vice versa. Neither of them fits with GPL but may fit with LGPL in some circumstances. Mixed licences are indeed a royal pain.


问:
How to distribute, one virtual token to each person in this world, and make sure nobody gets more than one?
How to distribute, one virtual token to each person in this world, and make sure nobody gets more than one?

In other words, how to prevent a user from creating more than one user account in a site?

What's this problem called? Is there any specific name to this problem? What are the solutions? Thanks.

答:
Unique user identification is the problem, and basically you're limited in what you can do about it.  Many systems have begun to depend on tools like OpenID (which in turn depends on "identity providers").  However, this is an inadequate solution in some cases, because little prevents a user from establishing multiple OpenID identities.

Normally, the way we get around this problem with web sites is to reframe the problem altogether.  So, for example, let's say we're trying to prevent people from creating multiple accounts because each account gets some virtual asset.  We don't want them cheating by aggregating these initial assets into one account.

What are some ways to deal with this?  Well, one is to make the user actually pay a nominal fee to open an account.  If it costs me $1.99 to create an account, then that takes away a lot of the incentive to cheat.  Obviously it doesn't completely prevent cheating, but if you're making money when people cheat, does it matter?  Another way is to force new users to complete some task that takes time in order to get their "initial assets".  In that way, you're not preventing users from using the site for free, but you ARE forcing them to spend time getting a new account functional, which in turn makes it a pain to "cheat".  Another approach is to make these "initial assets" special in some way so that they can't be exchanged -- maybe they're branded with the user account's credentials when they're created, and that makes them unusable by another user in the system.

So, unless you're doing something extremely unusual where actual identity truly is a business requirement, your best bet is probably to rethink your requirement.  If you truly need identity and nonrepudiation, then you pretty much have to go low-tech -- physical interaction with the users where they provide government issued identity cards.


问:
If one is to learn a new programming language each year, what should the list be?
In chapter one of "The Pragmatic Programmer" the first learning goal is:

Learn at least one new language every year. Different languages solve the same problems in different ways. By learning several different approaches, you can help broaden your thinking and avoid getter struck in a rut. [...]

To achieve this over a career, the list of languages is likely to get quite long (particularly if you do not want to "progress" into management). Clearly the education of a programmer (or whatever form) is going to get you started with a core of commercially useful languages (the usual list from job posting: C, C++, Ruby, Python, JavaScript, C#, Java, VB, ...). Additionally a formal or informal learning programme is likely to have covered functional approaches (via something like Haskell, LISP or an ML derived language)

But once a reasonable subset of that list is learned- what's next, and why?

答: Make it interesting and spend each year writing an interpreter or compiler for your own programming language that fills up a niche you've never used a programming language for. Each year, write your next compiler/interpreter using the language you wrote the previous year.</p>

ContentLicense: CC BY-SA 2.5


问:
How many programming languages is a programmer expected to be an expert at?
Do most programmers specialize on a single stack, leaving other things be, or are they expert at multiple languages at the same time? If it's more than one, how many is standard?

By expert, I mean more than simply knowing the syntax of a language - an expert knows enough of standard libraries, tools, environments and syntax to be able to write non-trivial programs without having to constantly look things up or read books/tutorials.

答:
One

The one in front of you.

Body:
One

The one in front of you.


问:
How does Observer create loosely-coupled design?
I completely understand the Observer design pattern, what it is for and how to implement it. I also understand what the term 'loosely-coupled' means.

But I'm not sure how Observer makes designs more loosely-coupled.

For example, let's say I want objects B and C to get updates from object A about it's state. The Observer pattern is a great way to do that. But one could also implement this with a more 'brute-force' way, not using the pattern.

Please explain to me how the Observer pattern allows for more loosely-coupled designs. I'm not sure I completely understand. Thanks

(Again, I understand what 'loosely-coupled' means, but not exactly how Observer allows for designs to be more loosely-coupled).

答:
The simplest way to implement the observer pattern is to define two interfaces, say ISource and ISink in a type library.

Any objects that can send signals implement ISource and any objects that can receive signals implement ISink.  These implementations depend on the type library, but do not need to contain any references to each other.

In your application you can then connect up your objects ISource and ISink interfaces without either class needing to have knowledge of the other objects implementation.


问:
Question/Answer for multiple Users - How should I design it?
I'm wondering about a good way to deal with a Question/Answer - Model for multiple Users.
My goal is to have an efficient and readable model where all the results of my users are stored. Every user has the same questions/answers!

At the moment I have three classes, Question,Answer and User.

A user has a Set of Questions.
A question has a Set of Answers and an extra field selected_value which is the answer the user clicked.

Every user has a copy of the same set of questions. Therefore I can easily see what a user has clicked.

This is an unnecessary overload because I need to store the questions/answers more than once.

But the good thing about this approach is the availability of my questions/answers in my user-model as I need to see what every user clicked. It's also easy to extract this information (e.g. via xml) doing just a loop around every user and his questions.

But what kind of approach would you recommend to use? Should I create a model "result" inside of my User-Model where I simply store a list of pairs like "QuestionId, AnswerId"? Is there any more accepted way to do so?

答:
A User may take many Sets of Questions, at different times or even more than once - I think you need a new class here to store:

(a) The association of a User with a Set of Questions (Quiz?), possibly at a particular time, and

(b) The answers selected by that User for that particular Set of Questions.

I would consider a new class, created based on the data within a Set of Answers and containing a new field called, say, Chosen_Answer.  In this way, the Sets of Answers class itself stays clean, self-contained and, most importantly, exists independently of any particular User, so you don't need duplicated copies any more.  When a User takes a Set of Questions, you create a new instance of this new class in which to hold their responses.


答:
If you read the book GoF Book, there you will find the answer to your question in applicability section of the Observer pattern (page 294).

Applicability Use the Observer pattern in any of the following situations:

When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and
  reuse them independently.

When a change to one object requires changing others, and you don't know how many objects need to be changed.

When an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don't
  what these objects tightly coupled.

There are a few keywords here: 'encapsulating', 'vary and reuse independently', 'a change in one object affecting others', and 'making assumption about objects'.

This can guide you in your investigation to understand the patter much better. Also, it may be a good idea to get a copy of the GoF book and give it a read.

Title: How does Observer create loosely-coupled design?

Body:
I completely understand the Observer design pattern, what it is for and how to implement it. I also understand what the term 'loosely-coupled' means.

But I'm not sure how Observer makes designs more loosely-coupled.

For example, let's say I want objects B and C to get updates from object A about it's state. The Observer pattern is a great way to do that. But one could also implement this with a more 'brute-force' way, not using the pattern.

Please explain to me how the Observer pattern allows for more loosely-coupled designs. I'm not sure I completely understand. Thanks

(Again, I understand what 'loosely-coupled' means, but not exactly how Observer allows for designs to be more loosely-coupled).


答:
Since it looks like the questions and the set of possible answers are the same for all users, I would say that it is fine if you share the same data with all the users. You can use composition for this.

The only piece of data that varies according to your descriptions is the user's selected answer for every question. As such, a user may have another collection data structure to store the selected answer per questions, somewhat like

```<code>class User{
  private final List<Question>;
  private final Map<Question, Answer> answers;

  public User(List<Question> questions){
      //shared by all users
      this.questions = questions;
      //an instance per user
      this.answers = new HashMap<>();
  }
}
</code>```

When it comes to storage, the map of answers will probably be just a table (or document, file,  store,etc.) containing the IDs of the questions and the ID of selected answer for a given user.

```<code>+-----------------+
| selected_answer |
+-----------------+
| user_id  <pk>   |
| quest_id <pk>   |
| ans_id   <pk>   |
+-----------------+
</code>```

Doing so, avoids repetition in both memory and storage.

Title: Question/Answer for multiple Users - How should I design it?

Body:
I'm wondering about a good way to deal with a Question/Answer - Model for multiple Users.
My goal is to have an efficient and readable model where all the results of my users are stored. Every user has the same questions/answers!

At the moment I have three classes, Question,Answer and User.

A user has a Set of Questions.
A question has a Set of Answers and an extra field selected_value which is the answer the user clicked.

Every user has a copy of the same set of questions. Therefore I can easily see what a user has clicked.

This is an unnecessary overload because I need to store the questions/answers more than once.

But the good thing about this approach is the availability of my questions/answers in my user-model as I need to see what every user clicked. It's also easy to extract this information (e.g. via xml) doing just a loop around every user and his questions.

But what kind of approach would you recommend to use? Should I create a model "result" inside of my User-Model where I simply store a list of pairs like "QuestionId, AnswerId"? Is there any more accepted way to do so?

Body:
Since it looks like the questions and the set of possible answers are the same for all users, I would say that it is fine if you share the same data with all the users. You can use composition for this.

The only piece of data that varies according to your descriptions is the user's selected answer for every question. As such, a user may have another collection data structure to store the selected answer per questions, somewhat like

class User{
  private final List<Question>;
  private final Map<Question, Answer> answers;

  public User(List<Question> questions){
      //shared by all users
      this.questions = questions;
      //an instance per user
      this.answers = new HashMap<>();
  }
}

When it comes to storage, the map of answers will probably be just a table (or document, file,  store,etc.) containing the IDs of the questions and the ID of selected answer for a given user.

+-----------------+
| selected_answer |
+-----------------+
| user_id  <pk>   |
| quest_id <pk>   |
| ans_id   <pk>   |
+-----------------+

Doing so, avoids repetition in both memory and storage.


问:
Move from Curl to Aria2?
We have a crawling engine that uses curl and caters to about 400,000 ppl  / month. Although curl supports concurrent downloads, it does not support bandwidth limiting ( only in php 5.4.0 ) which is why my boss wants me to move to aria2. He also says Aria2 is faster ( which seems to be true to me as well )

Aria2 would require a large amounts of changes to the system. Right now we have crawling system which does not crawl in a conconrrent manner.

Would moving to aria2 be a good decision?

答:
Bandwidth limiting is supported by PHP Ext cURL.
The settings you are looking for is:
curl_setopt($ch, CURLOPT_MAX_RECV_SPEED_LARGE, 10240);

aria2c is faster than cURL on mirrored downloads, because it allows fetching parts from multiple sources in parallel and combines them. this is not supported by cURL, afaik. rebuilding this feature on PHP side is possible, but the handling is slower than with aria2c.

Title: Move from Curl to Aria2?


问:
What should a repository really do?
I've heard a lot of the repository pattern, but I quite didn't understand what a repository should really do. When I say "what a repository should really do" I'm mainly concerned about which methods it should provide. For instance, should a repository really provide CRUD methods, or should it provide some different kind of method?

I mean, should the repositories contain business logic, or should they simply contain the logic to communicate with the data store and manage the entities to be saved or loaded?

Also I've heard that repositories are units of persistence for aggregates. But how is that? I fail to understand how this works in practice. I thought that we should have just one interface IRepository which contains the CRUD methods, and then for any entity the implementation would simply contain the logic to save and retrieve such type from the data store.

答:
Well, you can see a good example in the Spring Data Framework which is based on the concept of repositories.

There you will see repositories only deal with the data store, and rarely contain any business logic (this is reserved for the service layer). So, for instance, you take a look a their design you will see they have a CRUDRepository interface which exposes methods to create, destroy and recover entities (among other things). There is also a PagingAndSortingRepository that adds extra functionality for precisely that, sorting and paging results, etc, etc.

So, this framework is perhaps a good place to study a good repository design.

As far as I know, many of the concepts implemented by the Spring Data Framework, come from a great book called Domain-Driven Design: Tackling Complexity in the Heart of Software, the book has an entire section dedicated to Repository design.

You may consider getting a copy of it.

A small excerpt from the book explains:

The REPOSITORY pattern is a simple conceptual framework to
  encapsulate those solutions and bring back our model focus.

A REPOSITORY represents all objects of a certain type as a conceptual
  set (usually emulated). It acts like a collection, except with more
  elaborate querying capability. Objects of the appropriate type are
  added and removed, and the machinery behind the REPOSITORY inserts
  them or deletes them from the database. This definition gathers a
  cohesive set of responsibilities for providing access to the roots of
  AGGREGATES from early life cycle through the end.

Clients request objects from the REPOSITORY using query methods that
  select objects based on criteria specified by the client, typically
  the value of certain attributes. The REPOSITORY retrieves the
  requested object, encapsulating the machinery of database queries and
  metadata mapping. REPOSITORIES can implement a variety of queries that
  select objects based on whatever criteria the client requires. They
  can also return summary information, such as a count of how many
  instances meet some criteria. They can even return summary
  calculations, such as the total across all matching objects of some
  numerical attribute.

A REPOSITORY lifts a huge burden from the client, which can now talk
  to a simple, intention-revealing interface, and ask for what it needs
  in terms of the model. To support all this requires a lot of complex
  technical infrastructure, but the interface is simple and conceptually
  connected to the domain model.

Therefore:

For each type of object that needs global access, create an object
  that can provide the illusion of an in-memory collection of all
  objects of that type. Set up access through a well-known global
  interface.

Provide methods to add and remove objects, which will encapsulate the
  actual insertion or removal of data in the data store. Provide methods
  that select objects based on some criteria and return fully
  instantiated objects or collections of objects whose attribute values
  meet the criteria, thereby encapsulating the actual storage and query
  technology. Provide REPOSITORIES only for AGGREGATE roots that
  actually need direct access. Keep the client focused on the model,
  delegating all object storage and access to the REPOSITORIES.

Title: What should a repository really do?


答:
It should provide neither a straight CRUD interface nor do business logic.  It mediates between business logic and the database.  The interface should be in business logic terms but not perform business logic itself, more like a business logic primitive. As an example say you were going to build an email system, you have users and messages.  Your Repository would provide basic CRUD operations for users and messages but it would also provide filtered views of messages like GetUsersNewMessages(user) or GetSearchedMessages(user,searchTerms).

The idea is that the Repository hides how storage is implemented and provides a clean interface that allows fast flexible access to the data.  Keeping the operations in high level terms of what should happen rather than how means you have more flexibility to implement them in whatever way is best for the underlying backing store.

Title: What should a repository really do?

Body:
I've heard a lot of the repository pattern, but I quite didn't understand what a repository should really do. When I say "what a repository should really do" I'm mainly concerned about which methods it should provide. For instance, should a repository really provide CRUD methods, or should it provide some different kind of method?

I mean, should the repositories contain business logic, or should they simply contain the logic to communicate with the data store and manage the entities to be saved or loaded?

Also I've heard that repositories are units of persistence for aggregates. But how is that? I fail to understand how this works in practice. I thought that we should have just one interface IRepository which contains the CRUD methods, and then for any entity the implementation would simply contain the logic to save and retrieve such type from the data store.


问:
What really is the "business logic"?
I'm working with web development since 2009, when I started with PHP. When I moved to ASP.NET, I've heard a lot about DDD and OOAD where a lot of focus is given to this "business logic" and "business rules". The point is that all the apps I've developed until now were all about CRUD operations and I've never seen these things in practice.

I simply can't imagine what those things can really be in practice. So, what really is this business logic and how does this fit into an app? I know these are implemented as methods in domain models, but what could those methods possibly be, and where in the application they could possibly be used?

答: Business logic or rules are anything that don't pertain to the mechanics of the user interface (the "programming stuff"). They are the things you would still have to apply if you were doing this transaction or whatever 100 years ago (manually). For example, when to apply sales tax to a purchase.

ContentLicense: CC BY-SA 4.0

Title: What really is the "business logic"?


问:
How to get money from reluctant client?
I completed this website 4 months ago. (I would like to keep the website anonymous - if this post comes up on google search by customers, it will have a negative impact on their business). We did several iterations, the client was very demanding (and nosy), I complied with every single thing that was wanted, including the font-size of the footer which destroyed the aesthetic looks by quite a bit; (and they messed with the colours too, making it look dangerously childish and unprofessional).

Anyway, the client was very friendly during the whole process. After getting all the requirements I accepted to build the website for £950 and I charged him £150 in advance so he wouldn't want to bail out after I started the work. The requirements kept changing quite a lot, I made adjustments as and completed the website just 5 days late, w.r.t. the agreed date, in-spite all the changes in requirements.

That was four months ago. They have never returned my calls nor replied to my emails since then. How do I get the money back from them? I really need some advice on this, this is the second time someone has not paid me.

Points to be noted:

We did not sign any contract - the client was a friend of a friend.

I still hold the passwords for ftp, cpanel and everything. I don't want to bring the site down; somehow it doesn't seem ethical to me.

I posted this on Stack Overflow and it was closed, I was redirected here.

EDIT

Thank you everyone, for your enormous support. I thought I should include some more details: The client is hosting the site; as in, I made them register and use their own debit card to buy the domain name, webspace and everything, I just have the passwords for his cpanel, and ftp (well, I have access to cpanel that pretty much gives me access to many things).

Now, if I give them a warning, he might change the password to cpanel, but I am fairly sure they doesn't know about ftp's.

UPDATE

I followed Anna Lear's advice and sent the final invoice, on Saturday, with a warning that I will take the site down if he doesn't respond to my email before this Tuesday. They havn't replied to my emails yet, but I will let you know how this goes. Thanks much for your support. I plan to put up a holding page as Darknight suggested after Tuesday.

Points

I don't have a server space of my own, however I have few web spaces of my clients but I don't want to use them for this kind of purpose.

RESULTS

After my follow up of final invoice and warning, the client refused to anything. workman's advice seemed to be the most sensible to me. I mirrored the site to my own webspace, logged into his CPanel and forwarded the website to my site. Once that was done, I put up a holding page on my site so anyone going to the website would see a holdup page (nothing fishy, just an Under Construction page). Of course, this was all very weak in the sense that if my client knew about CPanel he could just remove the redirection. But, I had this second chance to get back to him and I was relying on him not knowing anything.

Two hours later, I got a call from the said client, (and  acting as if they did not get any of my voice mails or emails) and asked me to get the site back up. I, of-course, said I had to be paid and two days after that I received a bank transfer. The site's back up and running now.

Just wanted to say thank you all very much, I was very desperate when I had started this question. You are the best, not only you told me to learn the lesson (which I did) you also gave me a very very good solution that seemed to be very ethical (almost) to me.

A BIG thank you to workman!

If I could choose more than once answer, I would have chosen Anna Lear  too, but since I followed workman's advice I had to pick that up. People who made a point about not taking the site down without consulting a lawyer, thanks a lot.

答: I would suggest that you leave it alone - totally. No support whatsoever. Software has this strange tendency to require something called maintenance and support. The day will come, sooner or later. When he comes back - and he will - then you have some more leverage.</p>

Title: How to get money from reluctant client?


问:
Unit Testing a method that contains two output type parameters
I was following a book Art of Unit Testing, This book says that You must not have any logic in Your asserts as this reduces readability of test, or I may be testing too many things at a time. Suppose there is a method with signature as below:

```<code>public int DoSomething(int variable1, out string variable2, out float variable3)
{
...
}
</code>```

How should I test this method, as I have to assert on return value, variable2, variable3 ???

Sample Test method that tests all of these three concerns:

```<code>    public void DosSomethingTest(){
        //add code for arrange
        int expectedvalue=12;
        string expectedVariable1="I am expected";
        string expectedVariable3=15.9;
        string actualVariable1, actualVariable3;
        var sut=new Foo();
        int actualValue=sut.DoSomething(15, out actualVariable1, out actualVariable3);

        //this is where I am testing 3 concerns in one test. Is there a better way?
        if(actualValue==expectedvalue){
            if(expectedVariable1==actualVariable1){
                if(expectedVariable3!=actualVariable3){
                    Assert.Fail("Unexpected variable2 returned");//pseudo code
                }
            }
            else{
                Assert.Fail("Unexpected variable1 returned");//pseudo code
            }
        }
        else{
            Assert.Fail("Unexpected Value returned");//pseudo code
        }
    }
</code>```

Approach 2

Seperate Test methods that tests concerns separately:

```<code>    public void DosSomething_Passing15_Returns12Test(){
        //add code for arrange
        int expectedvalue=12;
        string expectedVariable1="I am expected";
        string expectedVariable3=15.9;
        string actualVariable1, actualVariable3;
        var sut=new Foo();
        int actualValue=sut.DoSomething(15, out actualVariable1, out actualVariable3);

        Assert.IsTrue(actualValue, expectedvalue);
    }

    public void DosSomething_Passing15_ReturnsExpectedVariable1Test(){
        //add code for arrange
        int expectedvalue=12;
        string expectedVariable1="I am expected";
        string expectedVariable3=15.9;
        string actualVariable1, actualVariable3;
        var sut=new Foo();
        int actualValue=sut.DoSomething(15, out actualVariable1, out actualVariable3);

        Assert.IsTrue(actualVariable1, expectedVariable1);
    }

    public void DosSomething_Passing15_ReturnsExpectedVariable2Test(){
        //add code for arrange
        int expectedvalue=12;
        string expectedVariable1="I am expected";
        string expectedVariable3=15.9;
        string actualVariable1, actualVariable3;
        var sut=new Foo();
        int actualValue=sut.DoSomething(15, out actualVariable1, out actualVariable3);

        Assert.IsTrue(actualVariable3, expectedVariable3);
    }
</code>```

Isn't approach 2 adhering to "Tests should not test more than one concern"?

Conclusion

If redesigning of SUT is possible:

There should ideally be no out parameter instead an aggregate class
should be evaluated in Asserts.

If there are unrelated out parameters then SUT method should be
refactored into multiple methods, then those new methods should have their own Test methods and they will then test only one concern.

If redesigning of SUT is not possible then as per the answer there will be three Asserts

答:
The idea behind "a method should test one thing" is so you can immediately see what is causing the problem when the test fails.

If you have an assert on three different things then you will have to see what one is going wrong exactly.

Another benefit of splitting them up is so you have an overview over what works and what doesn't when an assert fails. If you put all three in the same method and the first assert fails, you won't know if the latter two work. This will increase the difficulty for solving the problem: you won't know when you accidentally break another output parameter.

At this point you have to make a decision for yourself: do you consider these three output variables closely related or are they worth splitting up?

If they are closely related you can keep them together but if they aren't then I would advise you to put them in separate methods. You should extract their common logic to another method so you don't have to write the setup twice.


问:
ASP.net/IIS runtime environment
I'm not too experienced in the regard of configuring IIS/ASP.net. A client has asked me to extend the functionality of a custom web application I didn't develop. Unfortunately, they don't have the original Visual Studio project/source code. I'm trying to pull the application off of their production IIS server and configure it for development on my machine. I've already setup a new website instance in IIS on my machine and copied the code to it's directory. When I access it (http://localhost), I'm currently receiving a null reference in the application. Obviously, this is a pretty generic error the can be caused by a bug, but I feel it's related to IIS's configuration. I've made sure both sites are using the same .NET version and they are also both running in integrated pipeline mode. Any ideas on what else I should look into?

Production server: Server 2008 R2 (64bit), IIS 7.5 Development machine: Win7 (64bit), IIS 7.5

答: I agree this was a broad question - if it's worth anything in the future, check the connection strings too. I forgot ASP.net would be connecting to most of these datasources on startup. This/bad error handling was the issue in my case.</p>

Title: ASP.net/IIS runtime environment


问:
OOCSS / BEM / SMACSS architecture
I've been working through this article to organize my front-end code. It references articles on BEM / SMACSS, which in turn reference other articles.

I'm really trying to understand what the best practices are ... I have a few days to lay down this "standard", and then have to burn through a high-priority / high-visibility / limited timeline project. As such, I'd like to ensure I'm starting with a foundation that will scale as my app does.

Given a component named segment ... I'm creating pages that will have ~10 segments per page. Each segment will share the same base class. However, certain segments will have modifiers on them (different background colors). Further, elements within each block (in the BEM approach) will have modifiers as well. To demonstrate, here is a simple implementation (with only a single element arrow, while my full site will have 4-5 elements in each segment):

```<code>.segment__arrow {
    position: absolute;
    bottom: -24px;
    left: 50%;
    margin-left: -11px;
    background-position: center no-repeat;
    height: 21px;
    width: 21px;
    z-index: 2;
}
.segment__arrow--orange {
    @extend .segment__arrow;
    background-image: url('/images/arrow_orange.png');
}
.segment__arrow--white {
    @extend .segment__arrow;
    background-image: url('/images/arrow_white.png');
}
</code>```

So this is the single-class approach:

```<code><div class="segment__arrow--white"> ... </div>
</code>```

Alternatively, I could go with the multi-class approach:

```<code>.segment__arrow {
    position: absolute;
    bottom: -24px;
    left: 50%;
    margin-left: -11px;
    background-position: center no-repeat;
    height: 21px;
    width: 21px;
    z-index: 2;
}
.segment__arrow--orange {
    background-image: url('/images/arrow_orange.png');
}
.segment__arrow--white {
    background-image: url('/images/arrow_white.png');
}
</code>```

Where my markup would be:

```<code><div class="segment__arrow segment__arrow--white"> ... </div>
</code>```

Third, I could do:

```<code>.segment__arrow {
    position: absolute;
    bottom: -24px;
    left: 50%;
    margin-left: -11px;
    background-position: center no-repeat;
    height: 21px;
    width: 21px;
    z-index: 2;
}
.segment__arrow.orange {
    background-image: url('/images/arrow_orange.png');
}
.segment__arrow.white {
    background-image: url('/images/arrow_white.png');
}
</code>```

And then my class def would be

```<code><div class="segment__arrow orange"> ... </div>
</code>```

Perhaps even namespacing orange with something like sa_orange to avoid loose selectors.

The end result I'm looking for is less code / easier to maintain (which probably rules out the single class approach (option 1), as described in this great article on scalable architecture. The multi-class approach (option 2) results in a lot of verbosity (especially in my HTML), but is extremely explicit. The third uses a multi-class approach, but doesn't use namespaced modifiers (like .segment__arrow), so is slightly less verbose (but also less explicit & higher potential for collisions).

Does anybody with real world experience with this stuff have any feedback on the best way to approach this?

答:
For a long time I have been using and recommending the explicit multi-class approach (the second example) as it is the most universal, maintainable, and coherent. Here I will try to support this claim.

Single-class

This approach has a big problem when there are two or more categories of modifiers. For example a .button with modifiers small, large, huge for size and primary, success, info, and warning for "colour." On top of the usual 7 (= 3 + 4) classes one has to create all 12 combinations too:

```<code>.button--small--primary
.button--small--success
.button--small--info
…
</code>```

So far a bit inconvenient but not a disaster.

Another annoyance - a bigger one - is that the correct order "size first, colour second" must be used and therefore remembered (and well documented).

The worst is when JavaScript is involved. Want to change the "colour" of this button but keep the current size? Parse the class attribute! Want to just remove the success modifier? Parse the class attribute!

Count that e.g. Bootstrap has 7 "colours", 4 sizes, and active/disabled states; for which 119 (= 13 + [7*4 + 7*2 + 4*2] + 7*4*2) classes have to be declared in order to maintain single-class approach! That is the big problem.

Explicit multi-class would require just 13 classes (one for each modifier). The order would be arbitrary. Lastly, adding, removing, and changing one while preserving others would in jQuery look like:

```<code>$('#login-button').removeClass('button--primary').addClass('button--success');
</code>```

Shortcut multi-class

Firstly, as you mentioned, there is a potential for collisions - a bad thing by itself.

Secondly, what it also means, is that the .segment__arrow.orange has a higher specificity and cannot be overwritten with a single class selector. This is often in issue when an element is e.g. not only a large button but also e.g. a login button. Its code would look like:

```<code><a href="#" class="button large primary login__button">Log in</a>
</code>```

One might want to have a bigger left and right padding on the login button but preserve the height of large. This would result in more and more specific selectors which would bring us to the specificity hell - a place OOCSS should save us from.

It is evident this would not happen in the explicit multi-class approach.

Explicit multi-class

The only problem (as far as I am aware of) of this is that there are a few sometimes quite long classes in the markup. I do admit this.

Let me note that this is only a matter of taste of the developer as it has a negligible (to no at all) effect to the performance. The standard compression will take care of this.

That being said, using a good IDE will help to write these (yes, I know, it still will look a bit ridiculous).

On one hand, I would say, seeing such long classes forces one to think more about the structure; e.g. whether it would not be better to introduce a new (reusable) component instead of nesting it into something else.

Title: OOCSS / BEM / SMACSS architecture

Body:
For a long time I have been using and recommending the explicit multi-class approach (the second example) as it is the most universal, maintainable, and coherent. Here I will try to support this claim.

Single-class

This approach has a big problem when there are two or more categories of modifiers. For example a .button with modifiers small, large, huge for size and primary, success, info, and warning for "colour." On top of the usual 7 (= 3 + 4) classes one has to create all 12 combinations too:

.button--small--primary
.button--small--success
.button--small--info
…

So far a bit inconvenient but not a disaster.

Another annoyance - a bigger one - is that the correct order "size first, colour second" must be used and therefore remembered (and well documented).

The worst is when JavaScript is involved. Want to change the "colour" of this button but keep the current size? Parse the class attribute! Want to just remove the success modifier? Parse the class attribute!

Count that e.g. Bootstrap has 7 "colours", 4 sizes, and active/disabled states; for which 119 (= 13 + [7*4 + 7*2 + 4*2] + 7*4*2) classes have to be declared in order to maintain single-class approach! That is the big problem.

Explicit multi-class would require just 13 classes (one for each modifier). The order would be arbitrary. Lastly, adding, removing, and changing one while preserving others would in jQuery look like:

$('#login-button').removeClass('button--primary').addClass('button--success');

Shortcut multi-class

Firstly, as you mentioned, there is a potential for collisions - a bad thing by itself.

Secondly, what it also means, is that the .segment__arrow.orange has a higher specificity and cannot be overwritten with a single class selector. This is often in issue when an element is e.g. not only a large button but also e.g. a login button. Its code would look like:

<a href="#" class="button large primary login__button">Log in</a>

One might want to have a bigger left and right padding on the login button but preserve the height of large. This would result in more and more specific selectors which would bring us to the specificity hell - a place OOCSS should save us from.

It is evident this would not happen in the explicit multi-class approach.

Explicit multi-class

The only problem (as far as I am aware of) of this is that there are a few sometimes quite long classes in the markup. I do admit this.

Let me note that this is only a matter of taste of the developer as it has a negligible (to no at all) effect to the performance. The standard compression will take care of this.

That being said, using a good IDE will help to write these (yes, I know, it still will look a bit ridiculous).

On one hand, I would say, seeing such long classes forces one to think more about the structure; e.g. whether it would not be better to introduce a new (reusable) component instead of nesting it into something else.


答:
You don't have a lot you can do. In the US most districts have "small-claims" courts where you can represent yourself so you could try legal action but be prepared to invest a lot of time into and still lose. Verbal contracts are enforceable but not always practical, which leads to your most likely solution: Write it off.

Next time, use an escrow service that includes arbitration provisions. A written contract by itself won't be of much help if the amount of money is too little to justify taking it to court but you should still use one.

ETA: I already commented on this but I would absolutely NOT take the site down without speaking to a lawyer. While you do have an implicit contract it is not clear that you own the site or can repossess the code except by going through the courts.

Title: How to get money from reluctant client?

Body:
I completed this website 4 months ago. (I would like to keep the website anonymous - if this post comes up on google search by customers, it will have a negative impact on their business). We did several iterations, the client was very demanding (and nosy), I complied with every single thing that was wanted, including the font-size of the footer which destroyed the aesthetic looks by quite a bit; (and they messed with the colours too, making it look dangerously childish and unprofessional).

Anyway, the client was very friendly during the whole process. After getting all the requirements I accepted to build the website for £950 and I charged him £150 in advance so he wouldn't want to bail out after I started the work. The requirements kept changing quite a lot, I made adjustments as and completed the website just 5 days late, w.r.t. the agreed date, in-spite all the changes in requirements.

That was four months ago. They have never returned my calls nor replied to my emails since then. How do I get the money back from them? I really need some advice on this, this is the second time someone has not paid me.

Points to be noted:

We did not sign any contract - the client was a friend of a friend.

I still hold the passwords for ftp, cpanel and everything. I don't want to bring the site down; somehow it doesn't seem ethical to me.

I posted this on Stack Overflow and it was closed, I was redirected here.

EDIT

Thank you everyone, for your enormous support. I thought I should include some more details: The client is hosting the site; as in, I made them register and use their own debit card to buy the domain name, webspace and everything, I just have the passwords for his cpanel, and ftp (well, I have access to cpanel that pretty much gives me access to many things).

Now, if I give them a warning, he might change the password to cpanel, but I am fairly sure they doesn't know about ftp's.

UPDATE

I followed Anna Lear's advice and sent the final invoice, on Saturday, with a warning that I will take the site down if he doesn't respond to my email before this Tuesday. They havn't replied to my emails yet, but I will let you know how this goes. Thanks much for your support. I plan to put up a holding page as Darknight suggested after Tuesday.

Points

I don't have a server space of my own, however I have few web spaces of my clients but I don't want to use them for this kind of purpose.

RESULTS

After my follow up of final invoice and warning, the client refused to anything. workman's advice seemed to be the most sensible to me. I mirrored the site to my own webspace, logged into his CPanel and forwarded the website to my site. Once that was done, I put up a holding page on my site so anyone going to the website would see a holdup page (nothing fishy, just an Under Construction page). Of course, this was all very weak in the sense that if my client knew about CPanel he could just remove the redirection. But, I had this second chance to get back to him and I was relying on him not knowing anything.

Two hours later, I got a call from the said client, (and  acting as if they did not get any of my voice mails or emails) and asked me to get the site back up. I, of-course, said I had to be paid and two days after that I received a bank transfer. The site's back up and running now.

Just wanted to say thank you all very much, I was very desperate when I had started this question. You are the best, not only you told me to learn the lesson (which I did) you also gave me a very very good solution that seemed to be very ethical (almost) to me.

A BIG thank you to workman!

If I could choose more than once answer, I would have chosen Anna Lear  too, but since I followed workman's advice I had to pick that up. People who made a point about not taking the site down without consulting a lawyer, thanks a lot.


问:
log4net - roll my own singleton, use LogImpl, etC?
Reposting here... hopefully the better place to seek opinions on the matter.  :)

Writing my own log4net wrapper class using C#. I want to create a lib such that I can reference it from any project/assembly in a given solution with a minimum of effort. ie: include the reference, maybe throw in a using statement and then make calls like MyLogger.Debug(blahblah); with perhaps a property (MyLogger) being set from a "main" method somewhere.

From reading the docs, I'm not sure if I should be writing my own or using LogImpl? The latter seems to include all of what I'd want to put in my own wrapper, so, why reinvent the wheel? But, there is also a note in the help that says thast an instance member of type logimpl is not thread safe whereas a static member is...

OTOH, if I make my own, I'd be looking at a singleton class I can create once and use throughout my solution (by passing the singleton ref to objects which require it) but I gotta rewrite all those Debug, Error, etc sections.

So... not sure what approach to take. What would you folks suggest as a beginning?

答:
Generally singletons are considered bad:

...if you still feel the need to use Singleton objects, consider using the Factory Method pattern instead. It gives you all of the flexibility of the Singleton, with nowhere near as many problems.

...and you're supposed to inject the logger implementation into any class that uses it (or inject a logger factory if you only want the logger object to exist for as long as your class is using it), so:

```<code>interface IMyLogger
{
    void Log(string whatever);
}

class MyClass
{
    private readonly IMyLogger logger;

    public(IMyLogger logger)
    {
        if(logger == null) throw new ArgumentNullException("logger");
        this.logger = logger;
    }

    void someOtherMethod()
    {
        this.logger.Log("Something");
    }
}
</code>```

This allows you to inject various different logger implementations.  If you decide to go the shortcut route and use a Singleton, and then use the built-in one from log4net then you're pretty much coupling every class that uses it directly to your implementation, which is generally a bad idea.

Body:
Generally singletons are considered bad:

...if you still feel the need to use Singleton objects, consider using the Factory Method pattern instead. It gives you all of the flexibility of the Singleton, with nowhere near as many problems.

...and you're supposed to inject the logger implementation into any class that uses it (or inject a logger factory if you only want the logger object to exist for as long as your class is using it), so:

interface IMyLogger
{
    void Log(string whatever);
}

class MyClass
{
    private readonly IMyLogger logger;

    public(IMyLogger logger)
    {
        if(logger == null) throw new ArgumentNullException("logger");
        this.logger = logger;
    }

    void someOtherMethod()
    {
        this.logger.Log("Something");
    }
}

This allows you to inject various different logger implementations.  If you decide to go the shortcut route and use a Singleton, and then use the built-in one from log4net then you're pretty much coupling every class that uses it directly to your implementation, which is generally a bad idea.


问:
In an if statement, what are an "if clause" and a "then clause"?
I am a bit confused about the nomenclature for the parts of an if statement. Consider the following example:

```<code>1:  if condition then
2:      statement_1;
3:  else
4:      statement_2;
5:  end if;
</code>```

What is the "if clause" in this statement? Here are a few possibilities:

Is it lines #1 and #2?

Is it line #1?

Is it line #2?

Is is the condition in line #1?

And in the same example, what would be the "then clause"?

Is it line #2?

Is it the then keyword, plus line #2?

Is it just a synonym for "if clause"?

My main reference is Code Complete 2nd Ed., but the author seems to use exclusively the term "if clause", with the meaning being lines #1 and #2 in this example.

答:
The reason you hear about conditional "clauses" is because English has clauses.   When you hear about conditional clauses in programming, what the person is speaking about is "that which embodies the condition."

So the if clause is

```<code>if condition then
    statement_1;
</code>```

because that's the part that pertains to the if.

The else clause is

```<code>else
    statement_2;
</code>```

because that's the part that pertains to the else.

Body:
The reason you hear about conditional "clauses" is because English has clauses.   When you hear about conditional clauses in programming, what the person is speaking about is "that which embodies the condition."

So the if clause is

if condition then
    statement_1;

because that's the part that pertains to the if.

The else clause is

else
    statement_2;

because that's the part that pertains to the else.


问:
Should multi-threading be used for tasks which does not involve IO operation?
I was reading a book on OS and got confused between different terminologies.
I hope i will get my doubt cleared here.
These questions might be very basic for some experts, but i find this platform best suitable for such clarifications.

Processes are run by CPU and this whole operation is managed by OS.
For Single core CPU, at any instant only one process will be running.
CPU saves the state of a process to Process Control Block and starts running another process which was waiting and this switching is so fast that it feels like all processes are running simultaneously.

Need of different threads in a process was felt to get more fine-grained control over process , that means if process is waiting because of some I/O bound operation then even if this process is selected by CPU, it will not do anything.

So, if multiple threads are running under one process, then if one thread takes care of I/O activity , other threads can do some real computation, provided this process is selected by CPU.

Here are my questions:
Is Multi-threading effective only if task involved I/O activity?
Why is Multi-threading preferred over Multi-processing ? (is it because threads will share same memory space? )

Why Multi-core processors are better for multi-threading? (I think they will be better even if you don't use multi-threading, why so excitement in name of multi-threading?). And anyway threads in different processes will not share same memory, so two threads running in different processes on different cores are like running different processes. It is just that they will be parallel, and the real parallel, not the pseudo parallel.

答:
When it comes to understanding parallel processing (I'm going to use this term as a generic term), it's best to start out with the basics.  Take it slow and simple at first.

It's my understanding that threads and processes are much the same, but threads are a light-weight work system whereas processes are heavy-weight.  These are the terms used to indicate how much system work must be generated in order to support these work arrangements.  This is an important matter because parallel processing causes the computer some extra work.  If a task spawns a great many threads, this is more efficient than if it has to spawn an equal number of processes to do the same work.

Try to understand I/O in the broadest possible sense.  It's not only about user input, or I/O to mass storage devices (disk).  From the CPU's perspective a read from main memory is I/O.  A cache read is I/O too, even the fastest Level 1 cache.  Parallel processing allows productive work to continue even if one thread (or process) is waiting on I/O, because other non-blocked threads can continue to execute.

And never get stuck thinking that you know or control the order of execution of threads you spawn!  While you can force synchronization of parallel tasks, only do so if the problem logic requires it.  Synchronization slows down the pace of program execution and is bad unless strictly necessary.

Most modern CPU's are complex beasts internally and will break down even Assembly language statements into micro-instructions.

All talk of multiple CPU's versus core utilizing CPU's is just hardware implementation stuff.  Even a single CPU, non-core based, can often make very effective use of parallel software.  It just requires OS and application support.

The crude hierarchy of processor power (in increasing order of instruction-executing power) is:

Single CPU, no multi-core

Multiple CPU, no multi-core

Single CPU, multi-core

Multiple CPU, multi-core

Why?  Multi-core CPU's can route tasks around to internal cores much faster than it takes to send a task to a different CPU.  Also, multi-core CPU's routinely share cache levels, more so than single-core CPU's.  That permits faster data sharing too.

The crude metrics I've seen say that sending a task from one core to another, within a single CPU is approximately 10X faster than having to send that task off-chip, to another CPU.

Note too that shared-nothing architectures, like supercomputers routinely use, abstract this up even higher.  Then you have multiple whole computers all working together as a coordinated unit.  The instruction processing power goes up but so does the inter-process communications (IPC) overhead.  This is directly analogous to the increase in power with attendant IPC overhead found between multiple single-core CPU's and one multi-core CPU.  All found within a single computer with a single operating system.

Here are some general guidelines for programming parallel processing:

implement as many parallel tasks as you can, as the logic will permit;

stay away from trying to coordinate the number of subtasks you spawn to correlate with your current CPU design;

stay away from second-guessing the CPU's instruction processing abilities;

stay away from process synchronization wherever possible;

In fact it's a good design pattern to not design to your current hardware, as much as possible.  Software can have a very long life while hardware has a relatively short and fixed lifespan.  Therefore bet on (by spending time on) the software more so than the hardware.  The hardware will change, you can count on it.


问:
Can MVC implementations differ in design-details and still be considered MVC implementations?
Is the Model-View-Controller pattern very strictly defined, to it's design details? Or is it a term, like many others, with lots of different interpretations and versions (that all fit the definition)?

I have come across many 'versions' and interpretations of the MVC term. For example: Some versions state that using the Observer pattern, the View registers as an observer to the Model. Through this the View gets updates from the Model when it changes, and can update itself. Other versions claim that the View must never interact with the Model in any way.

The first version is from the Head First Design Patterns book. The second version I read here on Programmers. Two contradicting interpretation of the specific design-details of the MVC. And there are more examples.

My question is: Is the definition for the MVC pattern one of these terms that are interpreted in a variety of ways, which are all acceptable?

I am not talking about the higher-view definition of the pattern. This has a pretty clear definition.

I am talking about more specific details of design. Examples: Should Observer be used to update the View about changes of the Model? Should orders to the View to update be passed to it only through the Controller, or may be told to it by the Model directly? Things like these.

Do MVC versions vary in these details, but all still fit the MVC definition? Or is it simply that there are lots of 'wrong' MVC implementations?

答:
I'm not sure what to tell you based on what you're asking.

Is the definition for the MVC pattern one of these terms that are interpreted in a variety of ways, which are all acceptable?

Well, yes.  I mean, every concept has a history, right?  So back in the late 80s, Smalltalk developers coined the term "MVC", and it had many of the features you expect -- a model holding data state, a view responsible for presentation and UI handling, and a controller that coordinates the two.

However, when it gets into details of implementation, you're going to find a lot of variety.  Now, you'll hear die-hard GoF guys say that only the GoF definition is properly called "MVC", but I personally don't agree, because I've seen things that look like MVC with many variations (who owns what, who's allowed to talk to whom, etc.)

In fact, I would actually go further and say that "MVC" is a lot like the triangle is to building architecture.  It's a shape (or in this case a set of three relationships) that provide an important characteristic -- separation of concerns.

I've seen apps built such that each of the MVC components THEMSELVES have MVC-like classes inside.  (For example, you'll have a meta-view, meta-controller, and meta-model, and maybe the meta-view has a model for how it accesses its setup data, a view for actually rendering the controls, and a controller that is the external interface to the meta components).

So I view MVC as more of a building block than a limited thing with only one valid implementation.


答:
I think your question is not answerable at all, and you will ended up getting all again different opinion-based answers. You can't basically compare a definition that you're not actually sharing it with us -- I might have a different understanding of MVC, with all the known/unknown implementations.

People usually do Experiment with what they have. That could simply lead to thousands of either creative or ill-designed applications, however it's necessary for improvement.

Also people have different Understanding of same things. That's why we appreciate Team Work. A design pattern also is a work-on-progress like every other thing in this world. You can't directly jump from MVC to better-MVC in a day. What you see is the natural way of Learning and Creating.

Also most of the time you have to mix design-patterns to get what you want. It might be possible to implement only MVC for smaller applications, but there are many cases that you need to mix your MVC -- or whatever else, with other design-patterns. That might force you to change some aspects of your MVC. That might confuse people, or they might even hate you, but that's the way we learn and live: Trial and Error.

Title: Can MVC implementations differ in design-details and still be considered MVC implementations?

Body:
Is the Model-View-Controller pattern very strictly defined, to it's design details? Or is it a term, like many others, with lots of different interpretations and versions (that all fit the definition)?

I have come across many 'versions' and interpretations of the MVC term. For example: Some versions state that using the Observer pattern, the View registers as an observer to the Model. Through this the View gets updates from the Model when it changes, and can update itself. Other versions claim that the View must never interact with the Model in any way.

The first version is from the Head First Design Patterns book. The second version I read here on Programmers. Two contradicting interpretation of the specific design-details of the MVC. And there are more examples.

My question is: Is the definition for the MVC pattern one of these terms that are interpreted in a variety of ways, which are all acceptable?

I am not talking about the higher-view definition of the pattern. This has a pretty clear definition.

I am talking about more specific details of design. Examples: Should Observer be used to update the View about changes of the Model? Should orders to the View to update be passed to it only through the Controller, or may be told to it by the Model directly? Things like these.

Do MVC versions vary in these details, but all still fit the MVC definition? Or is it simply that there are lots of 'wrong' MVC implementations?


答:
Perhaps a simple example is in order.

Most MVC implementations have a feature called "convention over configuration."   What that means is that some configuration values can be "assumed."  For instance, consider this controller method in ASP.NET MVC:

```<code>public View Index()
{
    return View();
}
</code>```

This bit of code (absent several additional details for simplicity) returns the "Index" view, because the controller assumes that you are returning the view with the same name as that of the controller method.

But what if I specified the view explicitly?

```<code>public View Index()
{
    return View("Index");
}
</code>```

It still returns the "Index" view, but this time I have stated my intention explicitly. I am no longer using "convention over configuration," however.

Does this make it any less "MVC"?  Of course not.

Naturally, there are varying degrees of compliance, and there may come a time when you have departed from the "spirit and intent" of MVC to a degree in which it is no longer plausible to still call it MVC.

Winforms could never be called MVC, although there are ways to write it (and libraries to support it) which can emulate Model-View-Presenter.

Body:
Perhaps a simple example is in order.

Most MVC implementations have a feature called "convention over configuration."   What that means is that some configuration values can be "assumed."  For instance, consider this controller method in ASP.NET MVC:

public View Index()
{
    return View();
}

This bit of code (absent several additional details for simplicity) returns the "Index" view, because the controller assumes that you are returning the view with the same name as that of the controller method.

But what if I specified the view explicitly?

public View Index()
{
    return View("Index");
}

It still returns the "Index" view, but this time I have stated my intention explicitly. I am no longer using "convention over configuration," however.

Does this make it any less "MVC"?  Of course not.

Naturally, there are varying degrees of compliance, and there may come a time when you have departed from the "spirit and intent" of MVC to a degree in which it is no longer plausible to still call it MVC.

Winforms could never be called MVC, although there are ways to write it (and libraries to support it) which can emulate Model-View-Presenter.


问:
Best way to search through directory structure
I'm working on a python program which organizes a music library. The program will basically help me detect misspelled file or directory names, wrong FLAC tags or unknown/superfluous files. It will also make sure that the FLAC files are named correctly according to their FLAC tags etc.

The structure I though of looks as follows (/ being the root of the music library):

```<code>/
    [category]
        [artist]
            [year] - [release]
                [track number] - [title].flac
                [...]
                [artist] - [release].jpg
                [artist] - [release].cue
                [artist] - [release].log
        Various Artists
            [artist_0 [, artist_1 [, ...]]] - [year] - [release]
                [track number] - [title].flac
                [...]
                [artist_0 [, artist_1 [, ...]]] - [release].jpg
                [artist_0 [, artist_1 [, ...]]] - [release].cue
                [artist_0 [, artist_1 [, ...]]] - [release].log
        [...]
    [...]
</code>```

I started writing some code but pretty soon I noticed that this is actually not a too easy problem to solve. I wrote 4 functions, category, artist, release and file, which are called accordingly while iterating through all the directories. Basically like that (pseudo code):

```<code>func category:
    do some checks
    for each file in this directory:
        artist(file)

func artist:
    do some checks
    for each file in this directory:
        release(file)

func release:
    do some checks
    for each file in this directory:
        file(file)

func file:
    do some checks (FLAC tags etc)

for each file in the root directory:
    category(file)
</code>```

Now I'm wondering, are there any known algorithms or techniques which could be used to solve this problem in an elegant way?

答:
There is absolutely nothing wrong with your approach.

Note that if the "do some checks" part was the same in every function, then indeed you could simplify and have a single function that calls itself recursively on sub-folders. Perhaps this is what you had in mind... But this is not the case here as each function is clearly different.

Since you are using Python, you might want to check the os module, esp. os.walk(), which may help traverse the directory structure.


答:
Other answers are correct. One additional thought…

Business Logic Is Portable

If you were to re-implement a software project in a different programming language, say moving from Turbo Pascal to Java, business logic & business rules is what the old and new projects would have in common.

The programming language would be different. The source code would be entirely different. The tools (IDEs, compilers, and such) might be entirely different. The user interface might be entirely re-organized or have a different look-and-feel. The documentation would probably be different. But the purpose of the two projects, the end results of work performed / goals accomplished, would be the same.

Whether you are using text files or a relational database, whether using a green-screen or a GUI, whether you are using magnetic tape or SSDs, what remains constant is the business rule about an invoice having at least one line item.

Title: What really is the "business logic"?

Body:
I'm working with web development since 2009, when I started with PHP. When I moved to ASP.NET, I've heard a lot about DDD and OOAD where a lot of focus is given to this "business logic" and "business rules". The point is that all the apps I've developed until now were all about CRUD operations and I've never seen these things in practice.

I simply can't imagine what those things can really be in practice. So, what really is this business logic and how does this fit into an app? I know these are implemented as methods in domain models, but what could those methods possibly be, and where in the application they could possibly be used?


问:
Is there a Pattern or a Refactoring Method to pull data-loading out of existing Class
I am refactoring legacy codebase.  Part of it is a loadProduct() function inside a larger "everything" class.  loadProduct() loads data from a database.  I want to move this loading-data part out of the larger class, because I do not think it belongs there.  I am not sure exactly where I want to move it yet, but I think that just moving it out into a separate class will do great to start.

How do I do this?

i.e. Imagine this:

```<code>class Big
{
    function x() {}
    function y() {}
    function z() {}
    function w() {}

    ...

    function loadProduct()
    {
        $sql = "select * from X where Y = $this->p1 and w = $this->p2";
        $result = db_call($sql);
        ...
        $this->a = $result->field_a;
    }
}
</code>```

What I think of so far is:

I can create a Product class that instantiates and returns the product data.  Call it i.e. $data = new Product($p1, $p2, $p3).

create a ProductProvider class, which has function loadFromDB().  Call it:

$pp = new ProductProvider();
$data = $pp->loadFromDB($p1, $p2, $p3);
...
include 'db.php';
class ProductProvider()
{
    function loadFromDB($p1, $p2, $p3)
    {
         $product = null;
         //code to load Product
         return $product;
    }
}
```

I think way 2 is a bit more flexible and allows me to add more functions later on, such as loading different sets of data from different sets of parameters.  This flexibility may come in useful in case legacy codebase gives me surprises later on.  (i.e. say as I refactor I may realize I need to move or group this data-loading piece into or with some other piece of code and code encapsulation Provider will give me should be easy to move elsewhere).

Will my 2nd example pattern be a proper* fit for my refactoring example?

By proper fit I mean industry-accepted best practice, recommended for cases similar to mine.

答:
As asked in the title, you are probably looking for the Data Access Object pattern, that is also discussed in this StackOverflow question.

The point is using software layers to separate the program logic from database structure, because this way you could change your database schema, the names of the tables, and modify a small and isolated part of your code. Also having all DAO classes in the same package would help if the Database Management System changes. An example of possible change is moving from relational to NoSQL.

As pointed in the comments and explained by Mak Seeman, Provider is not a pattern. All code that is called at least once, provides some service. The name of a class should reflect what is provided, and not the fact that it provides something.


问:
Should a stored proc try to do more, in the attempt to avoid php mysql back and forth overhead
I have a REST architecture, running PHP on the server side which store
and query a Mysql database.

I am re-evaluating one architecture design decision:

DECISION to re-evaluate:

In an attempt to avoid back and forth communications overhead
between PHP and Mysql:

For some browser requests (for example: 'GET /sessions/4'), one request requires a big response with related objects links.

For these situations, I have designed some big mysql stored
procedures to query multiple tables.  Therefore, for one browser request, PHP launch this one Mysql stored
procedure which execute.  On PHP result reception, my PHP code goes through each Packet of query results to create objects and     link them logically.

At the end of this process, PHP query my internal logical view objects to construct the formatted response returned to the browser request.

The alternative would be to request multiple stored procedure and launch each of them within PHP instead of within this one stored procedure.

PROBLEMS:
It becomes quite hard to manage changes over time. These stored procedure becomes hard to maintain cause each table change, have an impact on one of them.

QUESTION:
I have started this design, because many code generated framework are being criticized for their lack of efficiency on communication between the PHP and Mysql layer.  Doing those stored procedure by hand, I expected to have the best performance in production, however, the maintenance start to be annoying.  Is real life high efficiency architecture attempts to limit the number of PHP-(Mysql stored procedure) back and forth communication or am I attempting to surround a false problem ???

Thanks

答:
You could send the entire contents of a stored procedure to be executed by the database and return the exact same dataset(s) or do the same code execution without losing any performance, but my guess is that's not your problem since you're still maintaining the code in the MySQL language. There are probably a lot of calculations in your stored procedure and other logic that you would like to execute with your language of choice.

Try and do some testing to see where the bottle-neck would be. No one knows for sure because some things are better done in the database (set stuff) and other type of procedural and repeated things are better done in other programming languages.

You could try and consider where your future hardware needs would be to help with performance. Generally, it's easier to throw multiple web and application servers at an application than it is to build a database cluster of servers. This is why in many instances, the database server just has a lot hardware thrown at it to create one big server.

It really is driven by your app needs, but probably more where yours or your team's skill sets are at.


问:
Place measurement data in database (access)
In a software I use records of measurement data. Each record contains basic information like a name, some parameters and the actual measurement data in the form of three arrays of double values that may vary in length from record to record. I currently use a binary format to save these records.

However I am not entirely happy with this approach, since it makes it hard to maintain (there may be changes or additional information in new versions and so on).

So I was thinking of moving the data into a database like access. This would have advantages for everyone. I can add information as I want, the user can use the database for other purposes if they please, etc.

However I am a complete novice in regards to databases and I wonder how I would structure a database to represent this content, especially the variable arrays.

I thought about encoding the double values into a string (like ; separated base64 strings) but this seems like a dirty hack that's not very user friendly.

So my questions are:

Is a database like Access suitable for my type of application.

There are no "array"-fields in an Access database, right?

How is storing a variable amount of data in a database entry usually handled?

Can I link one Access-Table to an entry in another table? So I would create a Data-table with entries for each datapoint and link this to a specific record in my main table?

I hope I could make myself clear somehow, but it's hard to wrap my head around the concepts. If you need more information, please ask. Thank you.

答:
An array in access (or any other relational database) is simply another table.</p>

```<code>Table 1

    ArrayID      AutoNumber

Table 2

    ArrayItemID  AutoNumber
    ArrayID      Number (Foreign Key, in one-to-many relationship with ArrayID in Table1)
    Value        Number
</code>```

Body:
An array in access (or any other relational database) is simply another table.

Table 1

    ArrayID      AutoNumber

Table 2

    ArrayItemID  AutoNumber
    ArrayID      Number (Foreign Key, in one-to-many relationship with ArrayID in Table1)
    Value        Number


问:
How to distribute, one virtual token to each person in this world, and make sure nobody gets more than one?
How to distribute, one virtual token to each person in this world, and make sure nobody gets more than one?

In other words, how to prevent a user from creating more than one user account in a site?

What's this problem called? Is there any specific name to this problem? What are the solutions? Thanks.

答:
As other answers have made clear, the problem as stated does not have a perfect solution, only approximations and disincentives. If you need to establish before creating an account that the user has not already opened one, then there is nothing more to add.

Non immediate approach

However, if it is acceptable to create an account without checking identity, and then gradually over time close accounts that have been identified as duplicates, then you may be able to bring the number of duplicate accounts to an acceptably low level with far less hassle for yourself or your users.

If your users will interact with, for example, a website using their account on a regular basis, then their input can be used to keep a "fingerprint" of their input style. This could be in the form of speed and frequency of mouse movements and keystrokes, use of particular words, phrases, use at particular times of day and week, or anything else that your particular situation makes available. The more different measures you can include the less susceptible your resulting fingerprints will be to oversights or false positives.

Ethical precautions

Ethically I would expect this information to be treated in the same way as actual fingerprints. The user must be informed that the information is being gathered, have the right to request a copy of it or to have it deleted, and have assurance that it will not be shared without their explicit permission. Otherwise it could be used to leak the identity of a person to any unrelated website that has bought their fingerprint.

While this "identity" may not include their name and address, just knowing that a user has an account with a given website may be of value to advertisers or organisations wishing to screen their users, so I would still consider sharing this fingerprint to be unethical without explicit consent.

Relevant prior work

Work has already been done on such fingerprinting. For example, this paper. The link only gives access to the abstract. I could not find a free version of the full article, but the numbers given in the abstract give an idea of how quickly you may be able to create an accurate fingerprint. There is free information at this Wikipedia page. While you will need to store data for every account on your servers, the bulk of the work of gathering, compressing and comparing fingerprints can be done on the users' computers.

This information can be used to highlight potential duplicate accounts, which can then be either closed if you are sufficiently certain, or raised with the user to request identification if giving them the benefit of any doubt. If you are prepared to accept some duplicates existing for the time taken to identify them, then this approach allows the majority of users to never have to provide identification.

Weak points

This approach will not prevent all duplicates. It will be effective with most users, but software could be used to mask typing patterns and even times of day (submitting information while the user sleeps for example). There is also nothing to stop a user from opening a new account and getting a friend to do their typing (providing that friend does not have an account of their own which would then show up as a duplicate).

There are opportunities for false positives which would need to be addressed in order to avoid excluding groups of people. For example, there are a wide variety of reasons that a user might not be able to use the keyboard or mouse and would therefore have someone to type for them. If that person also has an account, it will show up as a duplicate.

All of the problems with identifying people still apply, but this approach allows the identification to only be required for a much smaller set of users.

Unlikely to suit decentralisation

If you wish to provide a token in a one off event, with no possibility of deletion of duplicates that are identified later, then this won't be of any use to you. If (as hinted in one of the question comments) you are looking to set up a decentralised system with one account per person, this approach is not strictly incompatible with decentralisation, but it would need to have a very low rate of false positives when deleting suspected duplicates, especially if the token is linked to monetary value. Another major problem would be protecting the fingerprinting data from being extracted from the decentralised software for use elsewhere.


答: Either you consult with a lawyer, who will tell you what you can and should do, or you just write it off. IMO there is no middle ground.</p>

Title: How to get money from reluctant client?


问:
What would you add in this Software Development Project Checklist?
I'm a big fan of checklists. There is Travel Checklist, Moving Checklist and even a Scrum Checklist.

Context: you have been hired by a large corporation and given the mission to setup the whole software development environment, processes, team, etc. You have "carte blanche". You will be responsible for the creation of the working increments of the software. Project size: 2000 man/days.

What items would you add to the following (intentionally small and incomplete) checklist:

Install a Continuous Integration Server

Write a DoD

Write a one page coding guidelines

Create a product backlog

Install a Bug Tracking System

Schedule Regular Face Time

答:
Let's start with hire a good team of the right professionals for your project. In a typical business app you would need to hire a database developer and a dba, a QA person, a system admin, a business analysts,application developers, a UI specialist and team leads at a minimum. DBA, System Admin, business analysts and QA should be in a separate reporting chain from the development team. The development database specialist should report to the same technical lead as the application developers and UI specialist.

Set up the office space. Private offices are great if you can get them (I wish you lots of luck with this), but at a minumum you needs desks, phones, computers, whiteboards and a couple of dedicated conference rooms. Make sure there is a place for lunch breaks, a refrigerator, soft drinks, snacks, and coffee available. Free soft drinks and coffee even better.

Set up dev/qa/staging and prod servers for both the application and the databases. Databases should not ever be on the same server as the applications. Depending on the size and scope of the project, you may need multiple servers or SANs, etc for each environment.

As soon as servers are set up, schedule backups of the file sytem, the database and the database transaction logs. Do this the very first day things are set-up. Hire a firm like Iron Mountain to take backups off-site weekly.

Set up a source control system and create a document describing how it will be used. Do not forget to insist that ALL database structural changes and data inserts for lookup type tables be in scripts in source control. This will make deployment easier.

Buy commercial software or download open source software for the toolset you decided to use with licenses for all the pertinent users.

Buy developer machines that are screaming fast and have two monitors. Buy at least one test user machine that is moaning slow and typical of what the users will have on their desktops.

Train your new developers in how you want things done. If you have a large enough team to have some junior developers, then schedule extra training for them and include the time in your project planning. Monitor juniors very closely for at least three months. Monitor all new employees closely for the first month. Get rid of deadwood and rogue developers as soon as possible.

Determine what needs to be done in what order (the critical path). Do not assign tasks at the end of the critical path until the tasks they depend on are complete.

Create test plans and requirements.

Set up regularly scheduled progress meetings with the clients. They deserve to know what you are doing and what the roadblocks are. Do not fail to tell them when things will be late. If you are three weeks away from a deadline and you already know you will miss it, that deficit will not magically disappear before you have to tell the client. Make sure that the client knows that added requirements means added costs and time and that every added requirement will either have to have other tasks dropped or the deadline will change by the amount of hours in the new tasks. Making this clear from the start will save lots of pain and overtime hours and cost overruns absorbed by your group and not the client.

Set up an environment to performance test, not just the speed of one user, but one where you can test the expected number of simultaneous users. Do not wait to do this testing until the day before you go live.

In project planning, assume QA will find bugs and that they will take time to fix. Do not schedule QA for only one day at the end.

Create test data that is roughly the size you think the database will be. Make all developers test their code against the database of this size. Do not allow developers to only develop against a small database on their personal machines. This is a frequent cause of code that works fine until it hits production.

Plan rewards into the budget. It demotivates people when they work their butts off for months and only managers get bonuses. Also say thank you frequently and in writing.

You may need a project management system or at least set up spreadsheets to track what you need to track. When doing the project planning, assume no more than six hours a day person in your plan. This helps account for the time that will be spent not on the project, such as vacation, sick time, holidays, HR meetings, performance reviews, etc. If you know the project is in a period of high unavailability (say a project that runs form Nov1 - Jan 1 in the US), you may need to make extra allowances for more leave and holiday time. It is not fair to expect that developers will give up their leave and holidays and no one can predict when things such as sick time, jury duty , bereavement time etc will happen. Assume they will happen to your team on this project.


问:
MVC design, singleton in model with initialization
I've recently learned of MVC (model view controller) and am trying to refactor an existing program.  I am in a situation where I'd like to have exactly one object of a particular class so it seemed evident that I should use a singleton.  This singleton will be used to keep a hashmap of certain things.  However this hashmap will have to be initialized when the singleton is created by reading nodes from a xml file and storing them as class objects.

Now my dilemma is:

If I initialize the xml attributes (reading and converting to class objects), I'm effectively doing things in the model class that the controller should be doing, which is definitely not good.

If I put the initialization method in a controller class, I would have to refer to a controller class from a model class, which does not conform to the MVC design.

If I put the whole singleton in controller, then I'd have to look for the hashmap in the controller package, which defeats the purpose of having model classes.

I can't pass a premade hashmap to the singleton as a parameter neither, because the constructor is private..  Well, I technically could, by giving it to the getInstance() method as a parameter, but it feels like a dirty way of fixing, since I now either pass null every time, or make another getInstance() method that doesn't accept a  parameter.

Right now, my code is looking like this:

```<code>public class CategoryCatalog{

    private static CategoryCatalog categoryCatalog;
    private HashMap<CarOptionCategory, Set<ICarOption>> categoryOptionsMap;

    private CategoryCatalog(){
        categoryOptionsMap = new HashMap<CarOptionCategory, Set<ICarOption>>();
        initialize();
    }

    public static CategoryCatalog getInstance(){
        if(categoryCatalog == null){
            categoryCatalog = new CategoryCatalog();
        }
        return categoryCatalog;
    }

    private void initialize(){
        // TODO: xml
    }
}
</code>```

Am I overlooking something or should I use a different approach?

答:
You have to use the right tool for the right problem. MVC is used to separate the representation logic from routing request logic (controller) and business logic (the model).

For creating objects you should use Creational Patterns. Now, in my opinion,

If I initialize the xml attributes (reading and converting to class
  objects), I'm effectively doing things in the model class that the
  controller should be doing, which is definitely not good.

It's good if the classes are used by the model.

If I put the initialization method in a controller class, I would have
  to refer to a controller class from a model class, which does not
  conform to the MVC design.

Yep, don't do this because a low lever layer should not depend of a higher layer.

If I put the whole singleton in controller, then I'd have to look for
  the hashmap in the controller package, which defeats the purpose of
  having model classes.

This singleton is not a controller so don't do that too.

I can't pass a premade hashmap to the singleton as a parameter
  neither, because the constructor is private.. Well, I technically
  could, by giving it to the getInstance() method as a parameter, but it
  feels like a dirty way of fixing, since I now either pass null every
  time, or make another getInstance() method that doesn't accept a
  parameter.

Yep, you will break encapsulation here because the hash map is an invariant of your class and if you accept a hash map it means that the invariant can be overwritten, maybe accidentally.

In my opinion this singleton is some kind of factory that provides classes, if the classes are used by the model, then put this singleton in your model package. also take a look at Spring, it will do this for you in a nice way.

OwnerDisplayName: Babyburger