答:
The "premature optimisation is the root of all evil" thingy is nice and cute, but it is often misinterpreted and should not be used as an excuse to write poor code: if you can easily write code that obviously performs better, you should (for example by choosing the right data structure or avoiding to loop twice when one loop can do the job).

In the simple example you showed, you could create a class that handles the specific job. Something like:

```<code>class FindAGoodName {

    FindAGoodName(char[] array, char... retain letters) {
        //your loop here
    }

    int getCount() {}

    String getWord() {}

}
</code>```

The code will be as readable (possibly more readable) and you only loop once. Everybody happy.

Body:
The "premature optimisation is the root of all evil" thingy is nice and cute, but it is often misinterpreted and should not be used as an excuse to write poor code: if you can easily write code that obviously performs better, you should (for example by choosing the right data structure or avoiding to loop twice when one loop can do the job).

In the simple example you showed, you could create a class that handles the specific job. Something like:

class FindAGoodName {

    FindAGoodName(char[] array, char... retain letters) {
        //your loop here
    }

    int getCount() {}

    String getWord() {}

}

The code will be as readable (possibly more readable) and you only loop once. Everybody happy.


问:
Architecture guidelines for a "single page web-app"
I'm going to start a side project to build a "single page" web application. The application needs to be real-time, sending updates to the clients as changes happen.

Are there any good resources for best-practice approaches wrt the architecture for these kinds of applications. The best resource I've found so far is the trello architecture article here: http://blog.fogcreek.com/the-trello-tech-stack/

To me, this architecture, although very sexy, is probably over-engineered for my specific needs - although I do have similar requirements. I'm wondering if I need to bother with a sub/pub at the server side, could I not just push updates from the server when something happens (e.g. when the client sends an update to the server, write the update to the db, and then send an update to the clients).

Tech-wise, I'm probably looking to build this out in Node.JS or maybe Ruby, although the architecture guidelines should to some extent apply to any underlying server technologies.

答:
If you want something close to the mean stack (node.js, mongo...) for building a single page application that needs to be reactive, I'd pick meteor. Especially if you are building a prototype and starting from scratch.

Rails with an angular frontend would be an ok choice imho, but you will have an harder time "sending updates to the clients as changes happen", as you would need to install specific gems, string together some long-polling or sockjs library...

ContentLicense: CC BY-SA 3.0


问:
What exactly is a business rule?
I'm trying to better organize my application architecture, so I've been doing some reading, but I keep running into references to "Business Logic" and "Business Rules". I've never really understood what these actually are. I generally just focus on Use Cases and "User Stories". Could someone explain what Business Logic and Business Rules are, and how they are related to Use Cases?

All the definitions I've found seem to pertain to actual businesses, not software development.

Because software is not always representative of a business, does that mean that software does not always have business logic? Or...

答:
People use the terms "business rule" and "business logic" to refer to the portion of your application that is specific to your application and represents the core behavior of how things are supposed to work as opposed to generic functionality that could be useful in software written for a different client/business/customer base or code that exists to support the infrastructure of the application.

Often business logic is subject to change when the needs of the customer change, so we like to put it in a special place/tier so that we can modify it as needed.

Although the term seems to imply otherwise, non-business software also has business logic. For example, a rule that states that "when a user does xyz, the application should validate something" can be classified as a business rule.

Utility code, such as parsing/processing/data access and such would not be considered business logic.

It's kind of a nebulous term and could mean different things to different people in different contexts. It's not worth getting hung up on. The general idea is to separate your application into logical portions, each of which is responsible for something specific. How exactly this is done is something you learn from experience and working on well-designed large applications. But there aren't any hard and fast rules. Ask three good developers and you'll get six opinions.

Title: What exactly is a business rule?


问:
Improve processing of data (and structure) from flat file to CMS Database
I have a flat file (CSV) that brings me the data I want, but it needs to be cleaned and processed before it can be used, so I built an intermediate Database (MySQL) in order to get the structure from flat file as I want and like I want (cleaned and formated)... so then I use that data and insert into a CMS.

This process is iterative so more and more flat files come and a script (PHP and stored procedures) will do the cleaning and saving.

What happens now is that both structures (my intermediate DB and the CMS's DB) are similar and I'm worried about the solution I'm using is not so good, and maybe there's better option (because it's like having the same tables in each DB).... For example:

In intermediate DB:

```<code>element: id_web, name, col1, col2, var
category: name, col3, var (probably modified so variable)
</code>```

In CMS's DB:

```<code>cms_element: id_el, col, col, var
cms_element_lang: id_el, id_web (added/modified structure), name, col1
cms_category: id_cat, cols
cms_category_lang: id_cat, name, col3, var
cms_category_element: id_cat, id_el (use col2 from table: element to assign relationship)
</code>```

As explained before, this process is iteratived so I use the id_web for elements to recognize the register and change only the variable field (var), and for categories I use just the name, I know it's not a good idea but is it to modified the CMS structure and add my own id?

I've been doing the process like this and now I want to make it better but I'm not sure how to do it.

In the case of the relation between both (element and category) is it ok to not save it in the intermediate DB, just on CMS's DB?

EDITED: I'm trying to use the intermediate DB as a repository with no dependencies on a specific CMS (or version of CMS).

And as @Xavier clarified me, I want this repository to be useful as a way to easy "replay".

答:
Do you need a separate step? It's often faster to read each line, clean it and insert it into your CMS.

If you have a lot of cleaning and processing, you might want to look at kettle from pentaho, it handle Extraction, Transformation, and Loading (ETL) and could help you (beware, takes a while to master)


问:
Should I bother to develop for JavaScript disabled?
Should I bother to develop for JavaScript disabled?

I feel that my time is better spent developing for the majority.

答:
Things to consider:

AFAIK, search engine spiders don't like Javascript.  You should have basic content and navigation without Javascript just for SEO.

Some websites may have rules for access by the disabled, either for legal reasons or for company policy.  That is usually best accomplished with simple HTML as opposed to Javascript.

While most people surf with Javascript on nowadays, that isn't a guarantee for the future.  The web is becoming increasingly hostile, and tools like NoScript may become more popular.  Alternately, it's possible that more people will use devices with less capable browsers, although with some Android phones being fairly inexpensive this seems less likely.  Graceful degradation may be a way of future-proofing the site.

ContentLicense: CC BY-SA 2.5


答: You could call the business logic where you decide what you will do with the data that you got from the user.  There you can manipulate it and return or save on database. What you do with that data depends on the client  needs. </p>

Title: What exactly is a business rule?

Body:
I'm trying to better organize my application architecture, so I've been doing some reading, but I keep running into references to "Business Logic" and "Business Rules". I've never really understood what these actually are. I generally just focus on Use Cases and "User Stories". Could someone explain what Business Logic and Business Rules are, and how they are related to Use Cases?

All the definitions I've found seem to pertain to actual businesses, not software development.

Because software is not always representative of a business, does that mean that software does not always have business logic? Or...


答:
Here's an excerpt from Wikipedia:

It is a rule that defines or constrains some aspect of business and
  always resolves to either true or false. Business rules are intended
  to assert business structure or to control or influence the behavior
  of the business Business rules describe the operations, definitions
  and constraints that apply to an organization. Business rules can
  apply to people, processes, corporate behavior and computing systems
  in an organization, and are put in place to help the organization
  achieve its goals.

With respect to what @aarong said, business rules or business logic doesn't really mean you require some form of business entity to make this up.

This can mean any constraint or definition of a process that your application is supposed to do. These rules are meant to assert the behavior of your application and what it does.

For example, let's put this logic in an ATM machine.

Business Rules could be:

The user should have an ATM card

The user should know the pin to the ATM card

The amount the user is trying to withdraw shouldn't exceed the account balance

In case of any errors, revert any changes made to the system and reverse transactions if possible

Or in a more common place like Facebook:

You need a Facebook account to login

You must be logged in to add friends

The user must be able to select who can see their posts and pictures

The user should be notified about friend requests

The user can accept or decline friend requests

Stuff like that.

Title: What exactly is a business rule?

ContentLicense: CC BY-SA 4.0


问:
Should I store images in my database or file system in this application?
I'm using ASP.NET MVC 4 and SQL Server 2012. I have no problem going for either of these solutions but I want to know which one would fit better in the particular application I'm creating now.

I'm making a sort of a library system application. The only images the application will store are:

Users' profile pictures (1 per user)

Libraries' profile pictures (1 per library)

Book authors' pictures (1 per author)

Book cover images (1 per book)

None of the images stored will need to be of high quality. So obviously the images are not a big part of the application and considering this, I am currently storing the images in my database. Though I noticed something that I think makes for a major con.

The images are retrieved using a Url.ActionLink which leads to a Controller action method that accepts (for example) a bookId parameter before reaching to the database, retrieving that book's image and sending it back. So if a user were to search for books and he ends up getting a list of books along with their images before him, there will be a new call to the action method that retrieves images and a new query to the database for each image listed.

Is there a better way of handling this? Should I reconsider keeping my images in the database or is it not a big issue?

EDIT: Wouldn't consider this question a duplicate because it pertains to a specific type of an application that handles very little image data as as opposed to any type of an application (like in the linked question). Of course when you're not sure how much image data you're gonna be storing it's always best to store images on the file system. This is not such a case. The nature of the answers here versus the answers there shows this.

答:
I advise against storing the images in the database.

It's not what database are intended for - it isn't relational data that relates to other data.  It easily takes up a huge amount of space and is difficult to manipulate when within a database blob column.

I use databases to store the name, timestamps, meta data and file location. I then store and access the image at that file location/name

I went through this a few years ago in the real world and along with many others, came to the conclusion that storing the images in the database was a bad approach.  For versioning and history just have the code with the references in source control and manage them as with any other.  So change the name for each image, use date stamps and don't re-use exactly the same filename for another image.

Many folks that start off during this have to main the switch after a while as their database grows too big due to all the images.  This has a ripple effect on storage needs, servers, cpu and possibly network traffic.  It also makes it harder to use cloud based filesystem storage that can take into account geographic location, traffic and the like.  These techniques become critical as your company grows and having the images in a database can severely limit your options.

In conclusion, good for small projects with small amount of image data.  Not suitable for larger shops or larger amounts of data.


问:
How to fit testing in Scrum sprints and how to write user stories in Scrum
I am the development team lead of a new project at my company. This is the first project where the company will use Scrum. We have a waterfall/iterative SDLC. The BAs write requirements docs, hands over to dev and test, dev start developing and will release to testing in iterations. Testers take long time to test a release by which devs continue development but also bug fixes for the current release.
I have a few questions

In a sprint with say 5 stories when do you release for testing ? Is it as soon as a story is completed by dev or after all stories are completed but before end of sprint giving test the required time to test.

If the BA writes user stories what should be the detail. Traditionally it takes long time to write a spec with all UI layout, behaviour, text etc to be finalised. I guess my question is how to write stories that are implementable and testable.

Our test team is non-technical. How important it is to have automated UI testing for Scrum. The UI is based on WPF.

I have solid development experience using agile methods (TDD, code reviews, refactoring etc.) but new to scrum.

edit: By iterations I mean that if there are 100 requirements we may release to testing when we have finished 30, 35, 35 requirements rather than wait till all 100 requirements have been completed.

答:
Working in shorter and shorter iterations makes all these handoffs more and more expensive. You can reduce these costs by following a stupid, simple rule: cut batch sizes in half, change how you work to make that comfortable, repeat until happy.

Take your 5-story sprint example. If your teams are accustomed to write the code for all 5 stories, then testing all 5 stories, then the batch size is 5 stories. Cut that in half. In the next sprint, work on the 3 most urgent stories first, getting them ready for testing as early as you can. As the testers are testing those 3 stories, the rest can get the remaining 2 stories ready for testing. This will cause some growing pains. Change how you work in order to make this more comfortable.

For example, more people will work on each story together, so try more pairing and see if that helps you work more steadily. Or, perhaps, the testers will find problems in story 2 that distracts some programmers while they're trying to work on story 5, so encourage the programmers and testers next sprint to discuss earlier how to test one of the story in the "first batch" so that the programmers are less likely to make a mistake that a tester can easy catch with a test.

It might take a few sprints to work out the big problems associated with testers testing a small batch of stories while the programmers work on the next batch of stories. Once it becomes comfortable, cut the batch size in half again. And again. Within a year or so, the team will be comfortably testing stories as the programmers believe they've finished with them and probably making fewer mistakes along the way. Each story will be done sooner.

Of course, at this point, now you can do the same thing with the batches that the team receives from the product owners, or that the team ships to the operations organisation. And so on. At this point, you can tackle the "how much detail should the BAs write for stories?" problem.

By the way: in order for the testers to be able to lower their turnaround time, they will have to adopt some automation, by some combination of learning how to automate and programmers helping them automate. As you try to reduce batch size, you'll find out when you need to fix those problems. Don't add automation just because a book says you need it.

I hope that helps you.


问:
How to write tasks in Jira when using Scrum?
I am going to start a new project using Scrum and Jira and I have some questions regarding how to write proper tasks in Jira.

From what I understand user stories are small non-technical descriptions written by the stakeholders (ideally) that can have the form: As a user I want to order monkies so I can earn money.

However these tasks must be elaborated with requirements, technical requirements etc. My question is: How do you write such tasks in Jira properly, and do I have the right understanding of user stories.

Should I create user stories as super tasks and then create subtasks with the actual tasks/requirements?

Should I estimate super tasks/user stories, or only the sub tasks?

答:
You have a very superficial understanding of user stories. That's fine, but you should know. If you really want to understand this topic, then I highly recommend you look at the work of Liz Keogh, Dan North, Chris Matts, and Jeff Patton. Have fun.

Don't overthink tracking this stuff in Jira. It's just a fancy to-do list. Here's a story. What's left to do? Put those tasks in Jira, each associated with the story. As people think of extra things to do, make these tasks in Jira, each associated with the story. That's it.


问:
Does auto make C++ code harder to understand?
I saw a conference by Herb Sutter where he encourages every C++ programmer to use auto.

I had to read C# code some time ago where var was extensively used and the code was very hard to understand—every time var was used I had to check the return type of the right side. Sometimes more than once, because I forgot the type of the variable after a while!

I know the compiler knows the type and I don’t have to write it, but it is widely accepted that we should write code for programmers, not for compilers.

I also know that is more easy to write:

```<code>auto x = GetX();
</code>```

Than:

```<code>someWeirdTemplate<someOtherVeryLongNameType, ...>::someOtherLongType x = GetX();
</code>```

But this is written only once and the GetX() return type is checked many times to understand what type x has.

This made me wonder—does auto make C++ code harder to understand?

答:
Yes.
It decreases verbosity but the common misunderstanding is that verbosity decreases readability.
This is only true if you consider readability to be aesthetic rather than your actual ability to intepret code - which is not increased by using auto.
In the most commonly cited example, vector iterators, it may appear on the surface that using auto increases the readability of your code.
On the other hand, you don't always know what the auto keyword will give you. You have to follow the same logical path as the compiler does to make that internal reconstruction, and a lot of the time, particular with iterators, you're going to make the wrong assumptions.

At the end of the day 'auto' sacrifices readability of code and clarity, for syntactic and aesthetic 'cleanliness' (which is only necessary because iterators have needlessly convoluted syntax) and the ability to maybe type 10 fewer characters on any given line.
It's not worth the risk, or the effort involved long-term.

OwnerDisplayName: Felics


答:
Business rules are rules that exist in the problem domain that define or restrict processes in that domain.

These are rules that may be applied by software.

The use cases are documented observations of the business rules in practice.

Example, if the problem domain is prescribing, then:

a business rule could be "Can't do refills on Control-II Medications".

a use case or story could be "Patient requests refill on Medication... System denies refill because refills aren't allowed on Control-II Medication..."

Business rules aren't necessarily associated with computer applications.

When you see the term in a book, you can generally think of it as "Requirements" although requirements encompass more than just business rules.

Title: What exactly is a business rule?


答:
There are valid concerns on either side of the debate, so always consider your requirements and constraints. How much data, how many images, how large, how secure, time to recovery?

Inline / BLOB storage

Upside

Version control / transactional consistency. This is the key semantic difference. This is handled well by the DB, so allows for point-in-time recovery. Filesystems don't provide this so you aren't going to have the ability to rollback. (I'm not referring to the filesystem standalone, I am referring to the problem of transactional control from your code). Images and documents can get corrupted by user error, or out of synch, becoming a 2-phase commit problem. Some systems solve this by adding an external revision control system, but it requires integration.

Simplifies implementation

All app data self-contained - Simplifies backup and recovery or migration of the system as long as the blob data footprint isn't unwieldy; just do a dump, backup, export (whatever the term for your flavor of DB) and move it to the new database. No external files to synchronize.

Security / access control is cleaner; access to an image BLOB is intrinsic to access to the data row. If a document is outside the DB and we let the HTTP server fetch it up (outside of MVC app), it may be better for concurrency and scalability, but takes more care to ensure Authorization is applied to the external files as they are the DB data. I've audited designs where large files were stored out of line, under static, multiplexed URLs, and my first test scenario is to attempt direct access to the static URL without authentication. If you do house secure documents outside the DB, don't serve them statically, and make sure your security policy covers access control of images between tenants. Your HTTP server authentication has to integrate with the overall system's authentication. This is a big concern in multi-tenant databases. Less of a concern in single purpose, single-tenant systems, with simple authentication.

Reduced Database Server Surface Area - In many systems, the DB is separate from the apps server, and there is a firewall in between. Everything can be served through a single DB port (1433 / MSSQL) or (1521 / Oracle) as an example. With files, if you move your DB to a separate tier, you have to use NFS or NAS or either replicate the files among app server if you scale out.

Downside

Backup times - For really REALLY large databases (not applicable to you), the backup and recovery gets frustrating and starts to become problematic and costly; while you may have a small core dataset otherwise, you may have many GB or TB of image data. Treating it all as one consistent database is both good from integrity point of view, but bad for backup and recovery unless you use DBMSes with enterprise grade backup and recovery (example is Oracle RMAN and rolling backups, EMC BCVs or Netapp Snapshots). At one customer, our DB got so large, we just stopped backing it up and committed to geographically redundant replicas. Another well known case was Starbucks (the DBAs put the paper online, it is interesting read if you are into that).

Time to Recovery (aka Recovery Time Objective or Recovery SLA) - This is often defined by your client. As a DBA you have to back into that if the customer has already declared so. If adding 90% to the size of the database to store non-secure images impacts the recovery SLA of the critical data, then don't do it.

Less flexibility. Not simple to access the documents with OS level utilities, shell commands, etc.

Personally, in this context, I think the scales are stacked in favor of inline DB storage. If your DB isn't large, keep it all in the DB.

Title: Should I store images in my database or file system in this application?

Body:
I'm using ASP.NET MVC 4 and SQL Server 2012. I have no problem going for either of these solutions but I want to know which one would fit better in the particular application I'm creating now.

I'm making a sort of a library system application. The only images the application will store are:

Users' profile pictures (1 per user)

Libraries' profile pictures (1 per library)

Book authors' pictures (1 per author)

Book cover images (1 per book)

None of the images stored will need to be of high quality. So obviously the images are not a big part of the application and considering this, I am currently storing the images in my database. Though I noticed something that I think makes for a major con.

The images are retrieved using a Url.ActionLink which leads to a Controller action method that accepts (for example) a bookId parameter before reaching to the database, retrieving that book's image and sending it back. So if a user were to search for books and he ends up getting a list of books along with their images before him, there will be a new call to the action method that retrieves images and a new query to the database for each image listed.

Is there a better way of handling this? Should I reconsider keeping my images in the database or is it not a big issue?

EDIT: Wouldn't consider this question a duplicate because it pertains to a specific type of an application that handles very little image data as as opposed to any type of an application (like in the linked question). Of course when you're not sure how much image data you're gonna be storing it's always best to store images on the file system. This is not such a case. The nature of the answers here versus the answers there shows this.


问:
Data Access Layer with Asynchronous services like MQ
I am tasked with creating a development, design and architecture guide for a large multi-year project.  I have to dictate best design practices for a number of architectural perspectives.  See the below diagram to demonstrate how I see this looking.

So based on other architectural mandate, MQ based asynchronous services are preferred because of guaranteed message delivery and because not every business critical component guarantees to be High Availability.  My experience in developing against MQ interfaces was rather low scale and not in a transactional COA design.  Typically I would develop multiple threads that would routinely check for new messages to process, both messages to push into a queue for requests, temporarily persisting the state, then another thread that will consume responses from another queue.

When considering a COA style architecture that has a clearly defined Data Access layer and Business Logic layer, how is asynchronous data sources represented or implemented here typically?  It generally makes sense for a Data Access layer to provide an interface to Business Logic where the data source is a REST or SOAP based web service.  These services are synchronous, they receive a request and immediately process it, then return a response while the client waits a predetermined amount of time to recieve it.

Asynchronous requests may not be processed right away, they also might not return a satisfactory response.  MQ only guarantees the target component will eventually receive the request message, it does not guarantee it will return a response.

I feel like the best way to handle this is to have two seperate interfaces required by the Data Access layer, request interface and response interface.  A scheduled batch job that is then using the Business Logic component might be able to deal with this effectively using multiple threads, however there may be another component that requires a real time synchronous interface of our Business Logic component where we are required to interface through MQ that is NOT real time.

I am confused in how to reconcile the two.  Is this the right design pattern here?   How can I effectively provide an interface to a component that requires real time when my component requires an asynchronous interface?

NOTES:

Some relevant articles I have been reading:

https://www.ibm.com/developerworks/community/blogs/WebSphere_Process_Server/entry/sync_over_async_switch?lang=en

http://en.wikipedia.org/wiki/Request%E2%80%93response

Link

It seems this situation is defined already as an Architectural Anti-Pattern called Sync over Async.  It is clear to me that reading this people are saying it is an extraordinarily bad idea.  Then others note that sometimes we do have no choice and we have to do this which I am finding myself in.  I am not in a position to ask for a synchronous interface to lookup and search services for this one system, and I have no say with the others components requirement for a synchronous lookup and search service.

答: Maybe you can design your interface between business and data layer to be async? One component of the data layer would access the underlying 'asyncness' of MQ, the other component would be and async-over-sync accessing your Database through JDBC</p>


问:
Design Pattern for Data Validation
What would be the best design pattern for this problem:

I have an Object A. Object A can either be registered or deleted from the database depending on the user request.

Data validation is performed before registration or deletion of the object. There are a set of rules to be checked before the object can be registered and another set of rules for deletion. Some of these rules are common for both operations.

So far, I think the Chain of Responsibility design pattern fits the most but I'm having trouble implementing it.

答:
Normally I'll use a separate validator class to validate each use case. E.g. before adding product to database, I'll use AddProductValidator to validate business rule, before deleting product, I'll use DeleteProductValidator to validate, etc. Common business rule can be extracted to specification class (Specification pattern) and shared by validator classes

To structure validator class, I follow the approach here: http://lostechies.com/jimmybogard/2007/10/24/entity-validation-with-visitors-and-extension-methods/

If you use .NET, I think you might want to consider Fluent Validation (https://github.com/JeremySkinner/FluentValidation). I think it's quite cool and quite close to the article I mentioned above

Title: Design Pattern for Data Validation


问:
What are your decision critera in C++ to make something a data member or virtual method?
(Figured this was too subjective for SO, so posting here...)

I have some behavior that I can implement in various ways.  At least two methods are shows in the code snippet below.  Presume that the m_well data member is correctly set somehow at object construction time.

```<code>struct Behavior
{
    virtual bool behavesWell() { return true; }

private:
    bool m_well;
public:
    bool behavesMemberWell() { return m_well; }
};

struct OtherBehavior : public Behavior
{
    virtual bool behavesWell() { return false; }
};
</code>```

Obviously the one relies upon virtual dispatch, and the other merely the return of a data member.

A third, non-shown method would likely have the non-virtual public member function not return a fixed data member, but instead call a virtual - lets leave that aside for the purpose of this please.

What would lead you to one or other other of these two methods of implementing functionality, such that a user of this class can interrogate an object's behavior?

答:
We've got some classes that work that way - there is a type-of function that returns something different in different subclasses.  The problem I have is that there's no good way to tell within the debugger, given a BaseClass *.

Use a member variable.  The next guy to work on the code may thank you.


问:
Usage of the argv[0]
Lately I've discovered that the latex and pdftex (with some other one) binaries in Ubuntu are the same:

```<code>lrwxrwxrwx  1 root root          6 лип 29 18:03 latex -> pdftex*
lrwxrwxrwx  1 root root          6 лип 29 18:03 pdflatex -> pdftex*
lrwxrwxrwx  1 root root          6 лип 17 20:22 pdfcslatex -> pdftex*
</code>```

Executing all without any options yields different results; so, my assumption they use argv[0].

What is the advantage of using argv[0] instead of compiling several binaries? And what other usages of argv[0] is possible?

答: It's basically about saved overall effort. Shipping several subtly different binaries is a waste of disk space, build effort (need more compiles for every release), administration effort (need to maintain more build targets and more projects), etc. And the things that differ between those binaries are relatively simply conditionals that would probably end up auto-generated from the same source file via compiler directives anyway; so it's easier to go dynamic all the way and make the distinctions in-language via proper if constructs rather than wonky preprocessor commands.

Title: Usage of the argv[0]


问:
What's the worst question you were ever asked at interview?
It doesn't have to be programming or software development related, but just asked during an interview for an IT related job.

I know some "left field" questions are meant to see how the candidate copes with unexpected and novel situations, but here I'm looking for a question that appeared to be completely unrelated to the job they were interviewing you for, or something that made you think "what useful information could they possibly get from my answer to that question?".

答:
How do you feel about customers?

I answered with: "I haven't met any."

Then at the end (this question ended the interview by itself) my favorite:

From one to ten, how would you rate yourself as a person?

To which I replied: Eleven.

Big Silence

He then thanked me, and I left. Ten minutes out the door I was offered my current job.

Now you know why I wanted to impress the guy. =)


答:
It results in smaller overall executable size when there is a lot of shared functionality.  This is taken to the extreme by busybox, which has hundreds of size-optimized commands all linked in to the same binary and distinguished via argv[0].

There are only two other useful ways of using it that I'm aware of:

It is handy to use it in help messages showing command line usage so that the help references the same command that the user used even if the binary is symlinked or renamed under a different name to its original

Some programs write into it to provide a way of showing status feedback that will show up in ps.

Title: Usage of the argv[0]

Body:
Lately I've discovered that the latex and pdftex (with some other one) binaries in Ubuntu are the same:

```<code>lrwxrwxrwx  1 root root          6 лип 29 18:03 latex -> pdftex*
lrwxrwxrwx  1 root root          6 лип 29 18:03 pdflatex -> pdftex*
lrwxrwxrwx  1 root root          6 лип 17 20:22 pdfcslatex -> pdftex*
</code>```

Executing all without any options yields different results; so, my assumption they use argv[0].

What is the advantage of using argv[0] instead of compiling several binaries? And what other usages of argv[0] is possible?


答:
If a lot of code is reused across the commands, like parsing a file and translating into another format then this prevents mostly duplicate executables. You can do this with a uber command and arguments as well.

This does have the downside that it's dependent on the way the executable is called, a naive person may copy over the executable and rename it which would then stop it from working like expected.

Title: Usage of the argv[0]


问:
SaaS model, 1DB per client

The context

we're building a web-based system and one of the design decisions (database related) was whether to have 1 main DB manage all client data VS having 1 DB per client.
After reading a lot on the matter (especially in these forums), it appears that 1 DB per client is overall a better approach, especially on the mid to long-run and especially in our use-case.

The basic architecture

Our system is mostly a front-end system that pulls data from a RESTful webservice (where the client data is located), to access that webservice we use unique keys, each key belonging to a specific pair of CLIENT:DATABASE.

Where things get tricky

When a new client creates an account, the idea is to have the webservice auto-create a new DB, DB user and API key for that account. I've looked for a standard method of implementing this, but failed to find anything conclusive. Obviously, SaaS providers automate this stuff, but where I fail to understand is how they do this safely.

The only current solution I have is to create a sort of MASTER MySQL user, which has absolute total full über power over MySQL, which we would use to create these DB, DB user pairs. But this feels like such a dangerous set up that it CANT be the only solution. Any compromise to this user would be fatal. This is where I need your help...

Another side-question, is how to limit DB size with MySQL/innoDB. The only things that I have found is that MySQL can only limit TABLE SIZE. And, in more sophisticated contexts, that DBs are stored in separate directories which have a specific disk-quota (this seems to be used by some web hosting providers... but I can't confirm).
Does anyone know of any other way to control DB size?

答:
This is the classic single-tenant vs multi-tenant dilemma. To service multiple clients, should you:

Have a single database that includes the data for all your clients (i.e. make them all tenants of your single database), or

Have multiple databases, with each client partitioned off and the single tenant interacting with just its own database.

Most of the SaaS (and other XYZ-as-a-service) shops I know, and almost all of the Internet-scale properties (Google, Facebook, Twitter, etc.), strongly prefer the multi-tenant model. Multi-tenant is generally more efficient, for performance perhaps, but even more so for minimizing administrative overhead. There's just one database to set up and worry about, with data for different clients separated by client_id values. But there is no magical solution. If you "put all your eggs in one basket," then you have to work extra hard to protect that basket. And all-in-one databases can rapidly grow large if you're successful and have many clients, requiring investment in distribution, replication, indexing, and other scalability and quality-of-service optimizations. Developers of SaaS and Internet-scale services invest enormous time and energy in their infrastructure.

Some as-a-service shops do use single-tenant configurations, with clients each having their own database instance (and often, separate virtual machines or virtual environments). One reason is the obvious "greater isolation" virtue, which is often perceived as having stronger security and privacy protections. This isn't just a technical attribute; it's also a question of customer preference and ease of sale.

Single- and multi-tenant are great labels, but there are a lot of middle-ground and hybrid approaches between the two poles. The single database manager running multiple "database instances" that you seem to be describing, for instance, is the architecture used by many WordPress hosts. It's kind of a
"multi-tenant lite" or "housemate" scenario. For getting going and smaller configs, it has lot of virtues.

Title: SaaS model, 1DB per client


问:
Heterogeneous Associations - Data Modeling When an Object that Must Relate to One of Many Classes
Suppose you have 3 classes: ClassA, ClassB and ClassC. Now suppose you have a class Message. You want a one-to-many relationship between each one of those three classes and the Message.

The goal is that a Message must 'belong' to either a ClassA, ClassB or a ClassC object. A ClassA/ClassB/ClassC object can have zero or many Messages. The Message class is the same for any of the three classes (i.e. there shouldn't be a different class of Message for each of the three Classes A, B and C).

Now thinking about data-modeling on a relational DB (also, I'm using ORM, in this case Entity Framework Code First), I'll map each one of those 3 classes and the Message class to a table.

But then, the issue is trying to apply the relationships I explained above. I see a few ways to do this:

Add three nullable Foreign Keys (ClassAID, ClassBID, ClassCID) to the Message table. e.g. If a message belongs to a ClassA object, then ClassAID will have that obect's ID as a value and ClassBID and ClassCID will be null. This will force me to write a constraint/trigger to make sure that the Message object only has a value in one of those FK's. It also makes it a bit ugly on the Business Logic and Presentation layers whenever I want to know to which object does a message belong to: the MessageObject would have a nullable reference to a ClassA, ClassB and a ClassC object and I would need to check it before presenting it in the UI (e.g. a link from the Message to its object).

Implement inheritance and generalize ClassA, ClassB and ClassC. The Message has a FK for the generalized class' ID. This adds complexity and doesn't really solve the problem of easily figuring out to which ClassA/B/C a Message is related to.

Add a ClassToMessage table (similar to a link-table) that connects the 3 tables to the Message one, again, via nullable FK's. Sort of a combination of the previous two, but still not exactly a good solution for the same reasons.

I'd like to know if there's an elegant way to achieve the desired scenario, preferably having the Entiy Framework approach in mind. Thanks in advance.

EDIT 1:

Imagine the Message objects as being comments (or files) in a tree-like structure of objects (ClassA objects can have ClassB's and ClassB's can have ClassC's...). You want objects from all of those classes to have zero or many comments. You want the same Comment table for all of the comments (doesn't matter if they're belong to a ClassA or ClassB... instance). You also want it to be easy to find out the comments for a given object or the object a comment belongs to.

EDIT 2:

Two other alternatives:

Implement table per hierarchy (TPH) by having a ClassAMessage, ClassBMessage... that still doesn't quite solve the problem...

The Message stores the ID of the object that owns it and the object Type (whether it was a ClassA, ClassB...). No actual relationship: service layer or business logic does the rest (ouch).

I have seen this issue being addressed in StackOverflow, but I can't seem to find a good solution:

Entity Framework Code First - Entity maps to one or the other

Multiples Object Relationship in Code First

Database design - articles, blog posts, photos, stories

EDIT 3:

I'm pursuing alternative #4 (Table per Hierarchy / Class Table Inheritance) and have evolved this into a more specific S.O. question: Entity Framework 6 Code First - Comments on a Tree Structure

答:
It sounds like you're having exactly the same kind of problem that led to me adopting an object database rather than relational in one of my current projects.

Using an object database, you could simply have Message holding a non-nullable reference to MessageClass object, with ClassA, ClassB and ClassC being subtypes of MessageClass.  While this is basically the same as one of your suggestions, the simple fact is that while this is difficult to implement using SQL (and impossible to get correct referential integrity constraints for, if the different classes require different types of data) it is trivial to do in an object database.

I'm using db4o and finding it quite handy for this kind of task.


问:
DDD: service/repo operations on IDs or instances?
This might be silly, but: let's say I want to delete a Book from the repo. Should I:

deleteBook(bookId) - send the ID since in the most of the time, the ID is passed from the UI

or

deleteBook(Book) - but then I need to fetch the book first? And this would be just a shortcut for above: deleteBook(book.getId()).

My guts tells me both should exist. Any wisdom on this?

答:
Repositories are fist-class citizens in the domain model, so they should operate in terms of ubiquitous language using entities and value objects. Therefore you should avoid naming repository methods after CRUD operations and using database table IDs (primary keys) to handle your entities. Instead you should focus on your business vocabulary and try to derive important concepts. Lots of times aggregate roots have a clear identity in the problem domain and it's a common practice in the DDD world to model such identity as a value object.

Going back to books. Not sure about your domain model but maybe you could use ISBN or similar as an ID for your books. Or you might want to use a combination of ISBN and some other identifier generated by your system. Anyways, I think this concept of a book identity deserves to be a part of your model as a value object.

Depending on your needs this is what your repository might look like

```<code>public interface BookRepository {
    public Book find(ISBN isbn);
    public Book find(BookID id);

    public void store(Book book);

    public void remove(ISBN isbn);
    public void remove(BookID id);
    public void remove(Book book);
}
</code>```

Body:
Repositories are fist-class citizens in the domain model, so they should operate in terms of ubiquitous language using entities and value objects. Therefore you should avoid naming repository methods after CRUD operations and using database table IDs (primary keys) to handle your entities. Instead you should focus on your business vocabulary and try to derive important concepts. Lots of times aggregate roots have a clear identity in the problem domain and it's a common practice in the DDD world to model such identity as a value object.

Going back to books. Not sure about your domain model but maybe you could use ISBN or similar as an ID for your books. Or you might want to use a combination of ISBN and some other identifier generated by your system. Anyways, I think this concept of a book identity deserves to be a part of your model as a value object.

Depending on your needs this is what your repository might look like

public interface BookRepository {
    public Book find(ISBN isbn);
    public Book find(BookID id);

    public void store(Book book);

    public void remove(ISBN isbn);
    public void remove(BookID id);
    public void remove(Book book);
}


问:
Representing category splits in a personal finance database
I'm working on developing a personal finance applications (e.g. Quicken/Mint.com/etc..). I plan to store the data in a SQLite database. I'm stuck trying to determine how I want to represent splits in the database. Each transaction will be assigned a category such as "Food and Dinning" or "Rent". However, a single transaction may be split across multiple categories. For example a transaction at a grocery store may be split between "Groceries" and "Household".

Here's one version of my Transactions table. Transactions that are split would have a Catagory of "Split".

```<code>---Transactions Table (Option 1)---
INTEGER Id
DATE Date
REAL Amount
TEXT Description
TEXT Comment
TEXT Tags
TEXT Category
</code>```

And here's my Splits table which identifies how much of each transaction is assigned to specific categories.

```<code>---Splits Table (Option 1)---
INTERGER Id
INTEGTER TransactionId
REAL SplitAmount
TEXT Category
</code>```

The problem I have with this setup is the two tables could potentially get out of sync with one another. If a split is added or removed then the code has to know to switch the transaction category to and from "Split". Also the total amount of the splits associated with a transaction need to match the actual transaction amount.

Alternatively I was thinking of just treating everything as a split or "TransactionCategory". So rather then assigning an amount to the transaction the amount is just assumed to be whatever the sum of the "TransactionsCategories" are for each transactions. Transactions that are not split would just end up having a single associated "TransactionCategory" row to identify the amount and category of the transaction. If for some reason a Transaction did not have an associated "TransactionCategory" entry it could just be assumed to be an uncategorized transaction of 0 amount.

```<code> ---Transactions Table (Option 2)---
INTEGER Id
DATE Date
TEXT Description
TEXT Comment
TEXT Tags

---TransactionCategories Table (Option 2)---
INTERGER Id
INTEGTER TransactionId
REAL Amount
TEXT Category
</code>```

I'm leaning towards this option as I do not have to keep the two tables in sync, but I'm worried about the overhead of having to join the two tables and take the sum of the TransactionCategories table anytime I need to show a list of transactions and their total amounts.

答:
The table design for a double entry bookkeeping system has been pretty well understood for the last 35 years.  You should be able to find hundreds of examples on the web.

You may be able to find a model in the Data Models website.

Double entry bookkeeping is probably overkill for personal finances, but you can probably start with a data model for double entry, and then build an application that makes it look like single entry bookkeeping for your user.

If you don't understand double entry bookkeeping, maybe you should learn it before venturing into building financial apps for other people.


问:
How can one presenter be used for multiple views in MVP
I am using MVP for creating an android application, which takes data from server and sets to activity.

I am forced to create one presenter for each view.

Each view is unique because each view has different textviews/labels.

The presenter will read values from model and call setter method for each control in view.

For second view, I will need  different presenter, as I need to call some other setter methods on the view interface.

This means view - presenter will have one to one relationship.

Is it ok for view - presenter to have one to one relation in MVP or my approach is not correct?

EDIT: I will be using one presenter for each  view because I have to. Because each presenter will implement the functionality unique for each view.

However that poses reusability problem. The presenters have a lot of common code. eg calling helper to load data from URL etc.  So I am planning to use either the abstract factory pattern or the strategy pattern.  The problem with abstract factory pattern is , if tomorrow my presenter need to extend another class, it cannot be done because i m coding in java. So is it advisable to use abstract factory pattern in java , for the presenter group?

答:
Yes, it is fine.

Applying MVP design pattern means having MVP triplets (model-presenter-view) per every (even a bit complex) item to display. The logic goes to the model, and the presenter is there just to glue things.


问:
How do I cope with a manager who’s always interfering in what I do, but doesn’t really understand it?
We've all had them, managers who have either come from sales or last looked at code 10 or more years ago but think they know how to write code.

What can I do to give the impression that I'm grateful for their intervention, but keep it as short as possible so I can get on with my work?

Or, should I be engaging more with the manager to educate them with modern coding techniques and practices? After all, a manager who understands these will be able to talk sensibly to clients and more senior management when discussing the project and its timescales.

答: Do the same thing to him.  Every time you see him, immediately start talking about his stuff regardless of whether or not you understand it or not ... "Hey, I think that marketing campaign should go like foo!" "Hey, I think our sales team should do bar!" "Hey, next time you talk to your manager, you should tell him quox!"  He'll start avoiding you like the plague.</p>


问:
Scrum: Is it okay for the development manager to be the Product Owner
My company is going through an agile rollout and is currently considering options for what that means.

The ScrumMaster role is somewhat straightforward, but Product Owner has many candidates: Product Managers, UX, Software Analysts. The favored candidate for the moment is for each development manager to be the team Product Owner.

However, using development managers as product owners seems like it will discourage self-organization.  What's the "right" way to select product managers in an Agile way?

答:
Generally speaking, the person who knows the most about the application requirements or has the responsibility for interfacing with the client is the one who should be the Product Owner.

If the development managers in your organization have the best knowledge of the product's requirements, then they ought to by the Product Owner.  Developers need to be able to go to the Product Owner in order to clarify requirements and make sure that what they're developing is actually meeting the requirements.

As far as self-organization is concerned, I don't believe it should have an effect unless the developers report the development managers.

If the developers do report to the individual development managers, then the developer's performance metrics should be adjusted so they are not penalized if they work on other manager's requirements.  Likewise, rules need to be put in place so a particular development manager doesn't leverage their employees to gain priority for their product development at the expense of other requirements.

You may consider enhancing the scope of the ScrumMaster in order to make sure that the development managers don't exert undue pressure on the developers in order to change previously agreed upon priorities for the user stories.


问:
Normalization 3NF and BCNF
If I have the following relation R = (A, B, C, D)

And the functional dependencies:

A -> B,   B -> A,  CDB -> A,   CDA -> B

The candidate keys are CDA and CDB.

The third normal form says that there can not be a functional dependency between non-prime attributes. A non-prime attribute is an attribute that doesn't occur in one of the candidate keys. Then that means that this relation already is 3NF since both A and B, that depend on each other, are part of one of the candidate keys, am I right?

If so, I have another question about BCNF. BCNF says that every determinant must be a candidate key. In this case, A and B are not candidate keys, so that violates BCNF, or am I missing something here?

Thanks.

答:
You have relation 1-1 between A and B. Then you can make it appart in another table.

You have then 2 relations R1 = (A, B) and R2 = (A, C, D) or R2 = (B, C, D).

You choose between A and B to make attribute of R2. This choice will depend on the attribute size and fetch complexity. For example indexing integers is better than strings.

Title: Normalization 3NF and BCNF


答:
I'm assuming your security layer is wrapped within the Generic Data Access component.  The first thought that came to my mind when I saw your design was "why are trusted systems accessing the data layer in the same manner that untrusted systems are?"

The design you're laying out looks like something an insurance, financial, or even retail environment would want to use.

Your trusted layer, which is the batch and real-time synchronous components, is generally used for the create, update, and delete operations that can affect the underlying data.

Your untrusted layer, which comprises the widgets, is generally restricted to report type operations.

As you call out, the complexity in the design is that you have requests coming in through synchronous and asynchronous methods.  One benefit of using Websphere MQ as an intermediary for your asynchronous calls is that the WMQ clients can listen for specific messages on a return queue through a correlation ID.  Other lighter-weight MQ servers generally don't provide that feature.

Another nice aspect of WMQ is that it has a really robust dead letter queue handling system.  Inevitably, you're going to get responses that are delivered late.  The DLQ system will help you track those and understand why they are happening.

I think you're right to be worried about how the widgets are interfacing with the Generic Data Access component.  The primary challenge is you're setting yourself up for custom interfaces for each widget.  It may be manageable now, but experience and hindsight says that there will be more and more and more of them.

To simplify things at the data access layer, I'd recommend having all widget requests be run through a WMQ based layer.  All incoming requests are put on a queue, and responses are placed on a reply queue with a correlation ID.

The advantage here is that your Generic Data Access component only has 2 means of access.  Trusted systems get direct access to the layer.  Everybody else goes through the WMQ based queues.  An advantage of this is it's trivial to keep adding WMQ clients that can push requests on behalf of future widgets.

But wait! you might say.  There are widgets that expect synchronous responses and running them through a queue will affect that.  That's true, but you're going to have to deal with that communication protocol mismatch at some point in your design somewhere.

I recommend putting that impedance mismatch within your MQ clients as it keeps the logic within the Generic Data Access component simplified.  Said another way, the data access layer isn't responsible for handling the impedance mismatch.  It's the responsibility of the client performing the access.

While this may appear to complicate the API for the synchronous clients, it actually exposes something that may have otherwise been hidden.  _Somewhere_ in your data access pathway, something could have gotten disconnected and the upstream clients need to be able to handle a timeout / no-response.  By using an MQ client and explicitly stating within the API "this will timeout in 1 minute" then the upstream client has to acknowledge that situation and handle it accordingly.

As an aside, using a WMQ client for protocol mismatches is a pretty good way to go.  All of the rectification code is encapsulated within a particular layer, and your ability to reuse that layer increases due to the abstraction it provides you.  And even if you can't completely re-use the WMQ code due to differing API calls, you can still re-use the communication protocol rectification code.

And as a final consideration, using a WMQ layer for all widget access makes it easier to scale up your data access layer's response time.  As the volume of requests increases, you can always add more queue handler threads within the data access layer.

To summarize...

Make all of the widgets go through a Websphere MQ queue based access layer in order to request data from your central store.  Doing so abstracts out the external interface to your data access layer, and the decoupling that provides will make it easier for you to adjust to future changes.

Title: Data Access Layer with Asynchronous services like MQ

Body:
I am tasked with creating a development, design and architecture guide for a large multi-year project.  I have to dictate best design practices for a number of architectural perspectives.  See the below diagram to demonstrate how I see this looking.

So based on other architectural mandate, MQ based asynchronous services are preferred because of guaranteed message delivery and because not every business critical component guarantees to be High Availability.  My experience in developing against MQ interfaces was rather low scale and not in a transactional COA design.  Typically I would develop multiple threads that would routinely check for new messages to process, both messages to push into a queue for requests, temporarily persisting the state, then another thread that will consume responses from another queue.

When considering a COA style architecture that has a clearly defined Data Access layer and Business Logic layer, how is asynchronous data sources represented or implemented here typically?  It generally makes sense for a Data Access layer to provide an interface to Business Logic where the data source is a REST or SOAP based web service.  These services are synchronous, they receive a request and immediately process it, then return a response while the client waits a predetermined amount of time to recieve it.

Asynchronous requests may not be processed right away, they also might not return a satisfactory response.  MQ only guarantees the target component will eventually receive the request message, it does not guarantee it will return a response.

I feel like the best way to handle this is to have two seperate interfaces required by the Data Access layer, request interface and response interface.  A scheduled batch job that is then using the Business Logic component might be able to deal with this effectively using multiple threads, however there may be another component that requires a real time synchronous interface of our Business Logic component where we are required to interface through MQ that is NOT real time.

I am confused in how to reconcile the two.  Is this the right design pattern here?   How can I effectively provide an interface to a component that requires real time when my component requires an asynchronous interface?

NOTES:

Some relevant articles I have been reading:

https://www.ibm.com/developerworks/community/blogs/WebSphere_Process_Server/entry/sync_over_async_switch?lang=en

http://en.wikipedia.org/wiki/Request%E2%80%93response

Link

It seems this situation is defined already as an Architectural Anti-Pattern called Sync over Async.  It is clear to me that reading this people are saying it is an extraordinarily bad idea.  Then others note that sometimes we do have no choice and we have to do this which I am finding myself in.  I am not in a position to ask for a synchronous interface to lookup and search services for this one system, and I have no say with the others components requirement for a synchronous lookup and search service.


答:
I'd add two extra integer columns in the Transactions table and get rid of the Splits table completely. Keep the ID column as it is, but call one of the new fields TransactionID, and the other one SplitLine, which will be an integer. The data would look like this:

```<code>ID   TransactionID   SplitLineID   Amount  Category
1    1               1             12.00   Groceries
2    2               1             20.00   Household
3    3               1             5.00    Groceries
4    3               2             7.00    Books
</code>```

So here transaction 3 is for a total of $12, split $5 on groceries and $7 on books.

Title: Representing category splits in a personal finance database

Body:
I'm working on developing a personal finance applications (e.g. Quicken/Mint.com/etc..). I plan to store the data in a SQLite database. I'm stuck trying to determine how I want to represent splits in the database. Each transaction will be assigned a category such as "Food and Dinning" or "Rent". However, a single transaction may be split across multiple categories. For example a transaction at a grocery store may be split between "Groceries" and "Household".

Here's one version of my Transactions table. Transactions that are split would have a Catagory of "Split".

```<code>---Transactions Table (Option 1)---
INTEGER Id
DATE Date
REAL Amount
TEXT Description
TEXT Comment
TEXT Tags
TEXT Category
</code>```

And here's my Splits table which identifies how much of each transaction is assigned to specific categories.

```<code>---Splits Table (Option 1)---
INTERGER Id
INTEGTER TransactionId
REAL SplitAmount
TEXT Category
</code>```

The problem I have with this setup is the two tables could potentially get out of sync with one another. If a split is added or removed then the code has to know to switch the transaction category to and from "Split". Also the total amount of the splits associated with a transaction need to match the actual transaction amount.

Alternatively I was thinking of just treating everything as a split or "TransactionCategory". So rather then assigning an amount to the transaction the amount is just assumed to be whatever the sum of the "TransactionsCategories" are for each transactions. Transactions that are not split would just end up having a single associated "TransactionCategory" row to identify the amount and category of the transaction. If for some reason a Transaction did not have an associated "TransactionCategory" entry it could just be assumed to be an uncategorized transaction of 0 amount.

```<code> ---Transactions Table (Option 2)---
INTEGER Id
DATE Date
TEXT Description
TEXT Comment
TEXT Tags

---TransactionCategories Table (Option 2)---
INTERGER Id
INTEGTER TransactionId
REAL Amount
TEXT Category
</code>```

I'm leaning towards this option as I do not have to keep the two tables in sync, but I'm worried about the overhead of having to join the two tables and take the sum of the TransactionCategories table anytime I need to show a list of transactions and their total amounts.

Body:
I'd add two extra integer columns in the Transactions table and get rid of the Splits table completely. Keep the ID column as it is, but call one of the new fields TransactionID, and the other one SplitLine, which will be an integer. The data would look like this:

ID   TransactionID   SplitLineID   Amount  Category
1    1               1             12.00   Groceries
2    2               1             20.00   Household
3    3               1             5.00    Groceries
4    3               2             7.00    Books

So here transaction 3 is for a total of $12, split $5 on groceries and $7 on books.


问:
Class template specialization for implementing Automata
I'm implementing classes for simulating and generating different kind of automata. I'd prefer to use the same State and Transition classes for all the automata: NFA, DFA, PDA, etc.

For a PDA a transition from one state to another work require some sort of an extension, because the transition requires to pop something from and push something on the stack.

So I came up with the idea to let the transitions accept a extension class as template parameter:

```<code>public class Transition<T> {

    private State target;
    private T extension;

    public Transition(State target, T extension) {
        this.target = target;
        this.extension = extension;
    }

    public State getTarget() {
        return target;
    }

    public T getExtension() {
        return extension;
    }
}
</code>```

Note that there are EpsilonTransition and RegularTransition derived classes from this base class.

A PDA would require for instance this extension:

```<code>public class StackExtension {

    private Character toPop, toPush;

    public StackExtension(Character toPop, Character topush) {
        this.toPop = toPop;
        this.toPush = topush;
    }

    public Character getToPop() {
        return toPop;
    }

    public Character getToPush() {
        return toPush;
    }
}
</code>```

So that the PDA class can use Transition<StackExtension> instances.

Although this is a solution for my problem, it feels like bad design. Especially for the NFA and DFA, which do not require any extension.

Is there another design pattern for my particular problem?

答:
I'm not familiar with the particular automata classes you mention, but whenever you have a one-off class that you'd like to handle in similarly to the other classes, then the Facade pattern is pretty useful.

I'm over-simplifying, but the facade pattern is little more than a wrapper around the class in order to either or both of:

reduce the complexity of the available class methods

make the class conform to a particular interface

In your case, it sounds like you're wrapping the PDA class so that it will conform to a particular set of interfaces.  That's a perfect use for the facade.

OwnerDisplayName: Tim


问:
In domain driven design, how do I convert a database table with a primary key into a Value Object?
Lets suppose there's a database schema defined like this:

```<code>Person.mail_address_key ----- Address.address_key
Person.billing_address_key ----- Address.address_key
</code>```

A Person has a mailing address and a billing address.  As a denormalization technique, we create a separate Address table.  Most of the time the mail_address_key and the billing_address_key of a single Person will be the same value (ie: their mailing and billing address key will be the same).

In my database the Address has an identity (the address key).  But, in my domain model, I don't see a compelling reason for the Address to be an Entity, I'd like it to be a Value Object.

In DDD, is this an option? Or are Value Objects usually a group of columns (as opposed to a table)?  I'm kind of playing the devil's advocate here, because I don't think the database should dictate the domain model structure, but just making sure.

If so, where/when/how does the address lose its database identity so it can be used as a Value Object in the Domain Layer?  Or, am I supposed to keep the database identifier in the Value Object?

When the model needs to be persisted in the database, what's the process?  Am I supposed to go through a process of a) Find an address by these fields, b) if it doesn't exist, create a new one c) if it does, update the fields?

答:
In DDD, is this an option? Or are Value Objects usually a group of columns (as opposed to a table)? I'm kind of playing the devil's advocate here, because I don't think the database should dictate the domain model structure, but just making sure.

The database should not dictate the domain model structure so you're correct on that.  Value objects can be stored in the database as either a column or table depending on the type of data the value object is supposed to carry.

If so, where/when/how does the address lose its database identity so it can be used as a Value Object in the Domain Layer? Or, am I supposed to keep the database identifier in the Value Object?

Your domain code should not be riddled with properties that are for other concerns like persistence since they should be completely persistence ignorant.  You should really focus on your aggregate root.  You must have some way of identifying your aggregate root when you save it back to the database so, at that point, you would just need to check the Person table record (I'm assuming Person is your aggregate root) and see if there is a value in the MailingAddressID or BillingAddressID field.  At that point, you can decide whether to create new addresses and change the links to point to the new addresses or overwrite the addresses that are already linked.

When the model needs to be persisted in the database, what's the process? Am I supposed to go through a process of a) Find an address by these fields, b) if it doesn't exist, create a new one c) if it does, update the fields?

As I somewhat explained in the above answer, you should hydrate and de-hydrate your object graph based on your aggregate root.  Therefore, when your repository gets your aggregate root from the database, it will also hydrate all of the necessary entities and value objects under your aggregate root that are associated with your aggregate root in the database.  The same is true when you go to save the aggregate root back to the database.  Your repository should be able to handle your entire object graph under the aggregate root.


问:
Patterns for creating adaptive web crawler throttling
Im running a service that crawls many websites daily. The crawlers are run as jobs processed by a bunch of independent background worker processes, that picks up the jobs as they get enqueued.

Now currently I'm doing throttling "in-process" meaning that the threads will do a random sleep between each request. However having many asynchronous background workers running, that from time to time might be processing jobs for the same domain, is causing concurrency trouble, and I need a central monitoring system that my workers can talk to and get directions from. I have been looking into a few patterns e.g. leaky bucket and rate limiting using redis, feeling that I have still to find the silver bullet.

My main concern is, that not only do I have to track the requests and throttle them, but I also need to capture feedback like response code 429's and use it to adapt the rate level on a domain-individual basis.

Do any of you have some good ideas as to patterns you have used, good resources on the topic, general advice and other recommendations.

Thanks!

答:
I suggest looking into Zookeeper to help you with this.  We utilize Zookeeper to allow the servers to coordinate between each other as they're tasked with talking to domains.

Pattern works as follows :

Persistent nodes representing your domain set are populated into
Zookeeper.

Jobs affecting those domains "lock" those domains with ephemeral nodes.  You can tune how many locks are allowed in your code, thus specifying max concurrent consumers.

You can additionally use the body node itself to track individual requests for the purposes of limiting rate across your entire cluster or specifying the rate for each individual consumer - depending on your desired approach.  You could even use an "AtomicLong" recipe (look into Curator) to throttle by download sizes.

You then assign listeners to the relevant nodes to allow the state information to be propagated to your consumers as it updates.  FIFO ordering is guaranteed so that's not a concern for you.

Optionally, you can propagate additional cluster worker information to a centralized node and have a leader node (see the Curator 'Leadership Election' recipe) handle auditing that information so you can review actual performance over time.

This is how we do it and it works as advertised.


问:
Is it ok to have special domain factory - or something similar - directly in DAL?
In DDD application, I know that Domain Factory should be the single point of Domain object creation (input from the UI, the results of queries from persistence) - but I'm facing a problem that for very complex queries, we use stored procedures with multiple data sets - so data are translated to structures (classes) highly dependent on persistence implementation, e.g.

```<code>var reader = command.ExecuteReader();

... processing many record sets

reader.NextResult();
var userRows = ((IObjectContextAdapter)_context).ObjectContext
               .Translate<UserRow>(reader).ToList();
</code>```

In this case, userRows contains a table of relevant users (only few relevant columns from otherwise very complex table). And to tehe point - so far, we use static class DomainModelHelper defined in DAL, that in this case, e.g. from ID (obtained from the different table in the same query) and userRows creates domain object UserInfo (that contains basic information about the user), e.g.

```<code>// here we create aggregate root
...

foreach (var something in somethingRows)
{
    var createdBy = DomainModelHelper.CreateUserInfo(something.CreatedById ?? 0, userRows)
    ...
    // add this domain object to aggregate root
}
</code>```

This can work, but for some reason, this doesn't seem quite right. Is there any other - better - pattern or approach I'm now aware of?

答:
The repository is responsible for hydrating and de-hydrating your aggregate roots.  Therefore, it is responsible for building the object graph from your aggregate root down to all of its child entities and value objects.  The fact that the code used to do so is separated out into a helper class does not exclude the fact that the repository is still doing its job.

The domain factory is meant for application code that is wanting to create NEW domain objects and defines the requirements for what you need to instantiate a new aggregate root, but is not persistence related.

Think of it like this, when you buy a car, you need money, a license, and insurance.  So, the dealership is like a domain factory.  You can't get a new car until you have those things.  However, if you store your car in your garage, when you go retrieve your car from your garage, you expect it to be in the exact same condition it was in when you put it there.  The repository is like your garage.


答:
I have always found it useful for the repository to track the entities it hydrates along with their primary key values in such a way that it stays with the context of the application.  For instance, in your situation, I may have something like this on my BookRepository.</p>

```<code>public class SqlBookRepository : IBookRepository
{
    public static List<KeyValuePair<string, object>> BookReferences = new List<KeyValuePair<string, object>>();

    public Book this[ISBN isbn]
    {
        get
        {
            if (!BookReferences.Any(b => b.Value.ISBN == isbn))
            {
                DBBook bookWithISBN = //TODO:  Call db and get the book.
                Book book = HydrateBook(bookWithISBN);
                BookReferences.Add(new KeyValuePair(DBBook.ID, book));
                return book;
            }
            else
                return BookReferences.Single(b => b.ISBN == isbn);
        }
    }

    public bool Remove(Book book)
    {
        if (!BookReferences.Any(b => b.Value == book))
            return false;

        object bookId = BookReferences.Where(b => b.Value == book).Key;
        DataContext.Books.Remove(bookId);
    }
}
</code>```

Title: DDD: service/repo operations on IDs or instances?

Body:
This might be silly, but: let's say I want to delete a Book from the repo. Should I:

deleteBook(bookId) - send the ID since in the most of the time, the ID is passed from the UI

or

deleteBook(Book) - but then I need to fetch the book first? And this would be just a shortcut for above: deleteBook(book.getId()).

My guts tells me both should exist. Any wisdom on this?

Body:
I have always found it useful for the repository to track the entities it hydrates along with their primary key values in such a way that it stays with the context of the application.  For instance, in your situation, I may have something like this on my BookRepository.

public class SqlBookRepository : IBookRepository
{
    public static List<KeyValuePair<string, object>> BookReferences = new List<KeyValuePair<string, object>>();

    public Book this[ISBN isbn]
    {
        get
        {
            if (!BookReferences.Any(b => b.Value.ISBN == isbn))
            {
                DBBook bookWithISBN = //TODO:  Call db and get the book.
                Book book = HydrateBook(bookWithISBN);
                BookReferences.Add(new KeyValuePair(DBBook.ID, book));
                return book;
            }
            else
                return BookReferences.Single(b => b.ISBN == isbn);
        }
    }

    public bool Remove(Book book)
    {
        if (!BookReferences.Any(b => b.Value == book))
            return false;

        object bookId = BookReferences.Where(b => b.Value == book).Key;
        DataContext.Books.Remove(bookId);
    }
}


问:
Proper Model-View-_____ design
I've been reading up about Model View Controller, Model View Presenter, Model View ViewModel, and so on, and generally, the underlying concept seems pretty simple to understand: keep the pretty visuals and sciencey guts as separate and ignorant of each other as possible. No getting the logic peanut butter in the design chocolate; cool, I like that.

The problem is I'm still a bit fuzzy as to that third part... the not-model-or-view one. Everyone seems to have their own idea of what to call it, what it should do, what's proper, what's just plain wrong... and I'm going nuts trying to figure out when a Presenter becomes a ViewModel and when a View shouldn't be doing that because that's the Presenter's job and--

I'm rambling.

Rather than asking for someone to explain the difference between them--because that's already been done time and time again (I know; I've read more articles than I can count)--I'd be curious to hear the thoughts of a few programmers on the model I've cobbled together myself.

That said, what would you classify this design as, and perhaps more importantly, do you see anything about this that obviously sucks? Sure, I'd love to hear I'm doing good if this truly is solid design, but I'd much rather be given solid advice over praise.

Note: I'll be using "the Bridge" for the mysterious third part of Model-View-? to avoid any subconscious suggestions of what it "should" be.

Model

Is the authority on data.

Receives information about requested changes from the Bridge.

Contains and performs all logic for how data relates to other data.

<s>Informs the Bridge when data changes (for data the Bridge has expressed interest in).</s> Wording edit: Allows outside subscribers (about which it knows nothing) to monitor it's state or calculation results.

Has zero knowledge of the View.

View

Is concerned with providing the user a way to view and manipulate data.

Receives information about data updates from the Bridge.

Contains and performs all logic for how to present data and controls to the user.

Informs the Bridge when the user has performed an action that (possibly) affects the Model.

Informs the Bridge what information it's interested in.

Has zero knowledge of the Model.

Bridge

Is the coordinator and translator between the Model and the View.

Makes any appropriate formatting changes to information being passed between the Model and the View.

Retains information on "who needs to know what".

Has knowledge of both the Model and the View.

Additional Notes

In more complicated programs, it's common for there to be multiple Models. In this situation, the Bridge typically takes on the job of coordinating/translating between the multiple Models, and thus becomes the authority on what protocall/API/design Models should be built to. (e.g. if building a card game program, and you want to build an alternate deck shuffling model, you should use the Bridge for determining what functions are required for properly communication with the Bridge.)

In small simple programs with only one View and Model, it's common for the Bridge to "assume" what functionality is available on either side. However, as programs become more complex, it's recommended that the View(s) and Model(s) report their functionality to the Bridge so that it can avoid inefficiencies and buggy assumptions.

I think that just about covers it. By all means, I welcome any questions you might have about the design I tend to use, and I likewise encourage any suggestions.

And as always, thank you for your time.

答:
I suspect one of the things that's confusing you is that there are two entirely different patterns that are both commonly called model-view-controller.

There's the original, as implemented in smalltalk and which is useful for local gui systems, and theres what I tend to think of as web-mvc, which swaps around some of the responsibilities of views and controllers so that controllers can sit on the server with views being on the client (perhaps as rendered html, or maybe via ajax).

Your description sounds to me like it would sit within most definitions of web-mvc.

Title: Proper Model-View-_____ design


答:
All the actual code you've shown doesn't do anything, it just sets up properties, so any answer will involve some guessing.

It's not clear to me why having an unconstrained generic type on transition makes sense.  Could it take a string type?  My guess is that what you are trying to do is let the "extension" class know that the transition has occurred, and perhaps some information about it.

That sounds kind of like the transition should emit a TransitionComplete event - except that events can be subscribed to by any class, making it difficult for someone reading the code to know where the event is actually consumed.

In your case, it might be more transparent if you passed your extension class in to the constructor of the of the transition class, of type ITransitionHandler, and called its TransitionComplete method.

I can't say which is better for your program.

It's possible to follow either of my suggestions and still make the Transition class generic, just constrained to ITransitionHandler only.  But, why?  The only class that really cares about the extension class's type is the extension class itself, and it already knows.  So why make that part of Transition's type?

Again, without seeing your implementation, that may not be true, and making extension generic may be useful.

As an aside, I wouldn't spend a huge amount of time perfecting the design.  The number of automata types isn't likely to grow very fast, and the amount of code with visibility into the details of this design is likely pretty small.

Title: Class template specialization for implementing Automata

Body:
I'm implementing classes for simulating and generating different kind of automata. I'd prefer to use the same State and Transition classes for all the automata: NFA, DFA, PDA, etc.

For a PDA a transition from one state to another work require some sort of an extension, because the transition requires to pop something from and push something on the stack.

So I came up with the idea to let the transitions accept a extension class as template parameter:

```<code>public class Transition<T> {

    private State target;
    private T extension;

    public Transition(State target, T extension) {
        this.target = target;
        this.extension = extension;
    }

    public State getTarget() {
        return target;
    }

    public T getExtension() {
        return extension;
    }
}
</code>```

Note that there are EpsilonTransition and RegularTransition derived classes from this base class.

A PDA would require for instance this extension:

```<code>public class StackExtension {

    private Character toPop, toPush;

    public StackExtension(Character toPop, Character topush) {
        this.toPop = toPop;
        this.toPush = topush;
    }

    public Character getToPop() {
        return toPop;
    }

    public Character getToPush() {
        return toPush;
    }
}
</code>```

So that the PDA class can use Transition<StackExtension> instances.

Although this is a solution for my problem, it feels like bad design. Especially for the NFA and DFA, which do not require any extension.

Is there another design pattern for my particular problem?


问:
Should session variables be avoided?
I used to heavily rely on session variables in the past, but have recently found many of them to be unnecessary, using things like query string parameters instead.

A colleague of mine refuses to use session variables. Is this a realistic goal and should session variables be avoided for any practical reasons? Can session variables be avoided completely (except for session cookies to allow logins) and would this result in better designs?

Some of the reasons my colleague has for not using them:

Untyped nature of session variables

Session time-outs causing loss of state

Global scope nature of session variables

Load balancing servers losing sessions (.Net specific?)

Application pools/servers restarting

They are unnecessary

答:
Session variables are like the old Basic global variables to some degree.
The burden is on the user to keep track of them, what's in them, their scope and how they are used; just like in old versions of BASIC.
That being said, why would someone totally discount the use of a mechanism that is obviously designed to be an integral and very importaint part of the programming model (ASP, MVC etc.)?

The only bad thing that I've run into in using Session variables is that it puts the burden on you to keep track of them, make sure they are populated with relavent data and disposing of them.

Isn't that what we do when we are programming any way?

Title: Should session variables be avoided?


问:
How common is prototyping as the first stage of development?
I've been taking some software design courses in the past few semesters, and while I see the benefit in a lot of the formalism, I feel like it doesn't tell me anything about the program itself:

You can't tell how the program is going to operate from the Use Case spec, even though it discusses what the program can do.

You can't tell anything about the user experience from the requirements document, even though it can include quality requirements.

Sequence diagrams are a good description of how the software works as the call stack, but are very limited, and give a highly partial view of the overall system.

Class diagrams are great for describing how the system is built, but are utterly useless in helping you figure out what the software needs to be.

Where in all this formalism is the bottom line: how the program looks, operates, and what experience it gives? Doesn't it make more sense to design off of that? Isn't it better to figure out how the program should work via a prototype and strive to implement it for real?

I know that I'm probably suffering from being taught engineering by theoreticians, but I need to ask, do they do this in the industry? How do people figure out what the program actually is, not what it should conform to? Do people prototype a lot, or do they mostly use the formal tools like UML and I just didn't get the hang of using them yet?

答:
What do you mean by how the program "operates"?  You seem to be looking for exact implementation details in something other than the specific final implementation, which doesn't make sense.  Higher-level elements are supposed to guide implementation, not determine it.

From my experience, prototyping is somewhat uncommon.  I was certainly taught it in conjunction with specification, requirements, architecture, etc. though, and it can be very useful.

As for "what the software needs to be", that IS the requirements.  You appear to be missing the entire point.

Interfaces are often sketched out beforehand, and use cases can be used for interface "flow".  The user experience is not missing at all.  If you feel some element is missing, then do something else your professors haven't mentioned.  Design does not consist of a clear set of rules handed down from heaven.


问:
What is the best way to allow a user to specify a SQL server and database from a Windows application?
I am working on building a Windows application that will require a connection to at least two different Microsoft SQL Server databases (for example, a source and a target), which may or may not be on the same server.

So, in the application settings, I would like the user to be able to specify both the server(s) involved, as well as the source and target databases. I did a little bit of research and immediately found this article on Code Project:

http://www.codeproject.com/Articles/31826/SQL-Server-Authentication-using-SMO

It uses something I wasn't previously aware of called, SQL Server Management Objects:

http://msdn.microsoft.com/en-us/library/ms162169(v=sql.105).aspx

Anyway, I am wondering if SMO is the best way to handle establishing connections to data sources that are not known to me, but will be known by the user of the application. Part of the reason I am asking is that most information I am finding seems to be from roughly 5 years ago and want to make sure there isn't a better way to do this today.

Technical Details: I am looking at building it with Windows Forms or as a WPF application and will be dealing with Microsoft SQL Server 2008 R2 and up (likely 2012 and potentially 2014).

Thank you in advance for any advice, thoughts, or suggestions.

答:
If you want to allow users to discover servers/databases on the network SMO is the way to go. If you just want to allow them to enter known (to them) connection information, just collect the information in a form and use a SqlConnectionStringBuilder. Here is a nice article showing how to use it

```<code>using System.Data.SqlClient;

private void CreateConnectionString()
{
  SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();

  builder.DataSource = "(local)";
  builder.InitialCatalog = "Northwind";
  builder.UserID = "user1";
  builder.Password = "P@ssw0rd";

  MessageBox.Show(builder.ConnectionString);
}
</code>```

This is a pretty easy class to use. You can just fill in the basic information such as the DataSource, InitialCatalog, the UserId and
  Password and it will create a connection string for you. The output
  from the above code will be: "Data Source=(local);Initial
  Catalog=Northwind;User ID=user1;Password=p@ssword".

To add on additional keywords for your connection string you may use
  the Add method. This method takes the keyword and the value and will
  add them in the appropriate format to your connection string.

As mentioned, each ADO.NET data provider supplies one of these
  classes. For example, if you are using Oracle, you would use the
  System.Data.OracleClient namespace, then use the
  OracleConnectionStringBuilder.

The ConnectionStringBuilder class allows you to parse the individual
  elements of a connection string and put them into the corresponding
  properties in the ConnectionStringBuilder. In the following example
  you take an existing connection string like the one shown in the code
  below and place it into the ConnectionString property of the
  ConnectionStringBuilder. The ConnectionStringBuilder will then break
  it into the appropriate properties.

Body:
If you want to allow users to discover servers/databases on the network SMO is the way to go. If you just want to allow them to enter known (to them) connection information, just collect the information in a form and use a SqlConnectionStringBuilder. Here is a nice article showing how to use it

using System.Data.SqlClient;

private void CreateConnectionString()
{
  SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();

  builder.DataSource = "(local)";
  builder.InitialCatalog = "Northwind";
  builder.UserID = "user1";
  builder.Password = "P@ssw0rd";

  MessageBox.Show(builder.ConnectionString);
}

This is a pretty easy class to use. You can just fill in the basic information such as the DataSource, InitialCatalog, the UserId and
  Password and it will create a connection string for you. The output
  from the above code will be: "Data Source=(local);Initial
  Catalog=Northwind;User ID=user1;Password=p@ssword".

To add on additional keywords for your connection string you may use
  the Add method. This method takes the keyword and the value and will
  add them in the appropriate format to your connection string.

As mentioned, each ADO.NET data provider supplies one of these
  classes. For example, if you are using Oracle, you would use the
  System.Data.OracleClient namespace, then use the
  OracleConnectionStringBuilder.

The ConnectionStringBuilder class allows you to parse the individual
  elements of a connection string and put them into the corresponding
  properties in the ConnectionStringBuilder. In the following example
  you take an existing connection string like the one shown in the code
  below and place it into the ConnectionString property of the
  ConnectionStringBuilder. The ConnectionStringBuilder will then break
  it into the appropriate properties.


问:
Building a distributed system on Amazon Web Services
Would simply using AWS to build an application make this application a distributed system?

For example if someone uses

RDS for the database server,

EC2 for the application itself and

S3 for hosting user uploaded media,

does that make it a distributed system?

If not, then what should it be called and what is this application lacking for it to be distributed?

Update

Here is my take on the application to clarify my approach to building the system:

The application I'm building is a social game for Facebook.

I developed the application locally on a LAMP stack using Symfony2.

For production I used an a single EC2 Micro instance for hosting the app itself, RDS for hosting my database, S3 for the user uploaded files and CloudFront for hosting static content.

I know this may sound like a naive approach, so don't be shy to express your ideas.

答:
Your design is slightly distributed, but in very simple, minimal ways. You have functionally decomposed your workload across multiple servers. In 1980, that would have been considered a distributed system. But you do not distribute (aka, partition, shard) any of the individual parts of your workload across multiple servers. There is no substantial parceling of work, nor meaningful replication across multiple nodes or datacenters. Your storage (S3 and the CloudFront CDN) is the one exception; those services inherently distribute your storage-access.

Feel free to call it a "cloud app" or "cloud service," but by today's standards, it's not very distributed.