问:
How do I go about writing a programming language specification?
I really enjoy programming language design. Sometimes I think my language projects and their potential users would benefit from a comprehensive standards document. I've looked at many language standards, ranging from the very formal (C++) to the rather informal (ECMAScript), but I can't really get a handle on how I should break things down and organise such a document, even though I think I'm pretty good at technical writing in general.

Should I write it like a long tutorial, or more like a formal math paper? How do I keep it up to date if I'm developing it alongside a reference implementation? Should I just give up and treat the implementation and documentation as the de facto standard? Further, is there really any significant benefit to having a standard? Does requiring a standard mean that the language is needlessly complex?

答: Common Lisp and Haskell have language standards. Ruby and Python have implementations and documentation. So I would say that a language standard is not necessary, but it might be helpful if you expect there to be more than one implementation of the language you're designing. On the other hand, a standard is premature if you're expecting significant changes in your language definition.</p>


问:
What is needed write an interface to Microsoft Dynamics GP web services?
We've went ahead and purchased Microsoft Dynamics (see edit history for why) in order to write 2 functions to interact with one tiny part of it to fulfill one big need.

What I want to know is, from other programmers who have integrated their software with MS Dynamics GP. Is there any way to connect with it (fully) without having to write an interface in C#?

We want to use GP SOAP services so we can communicate to it from Delphi and eventually Java, but it seems like the only way we're going to be able to maximize it's usefulness is to write some sort of middleware program in C#.

答:
The preferred approach towards customizing the Great Plains (GP) is to access data via database.

You can write a application in any programming language you are comfortable with which can connect to a database. This is a risky approach though, but there are developers customizing GP in that fashion. The schema details for the GP database is not well documented. However, you can buy some documentation on it from this site or learn by discussing in a GP specific forum on what others might know. Otherwise, as in the comments to your question, you can connect with other developers in the GP community in the links posted in comments.

In a blog post, Other methods for connecting to GP could are listed -

Microsoft Integration Manager which uses excel sheets and delimited file

Dynamic GP Web Services which uses eConnect API to retrieve data.

Hope this helps. Do post the way the approach you have undertaken to benefit community.

ContentLicense: CC BY-SA 3.0


问:
Scrum task over estimation
In my current company we're using Scrum with 2 week iterations and a regular planning session.
How planning normally works in our company is that we take a predefined , prioritized (by PO before the planning) product backlog of user stories / PBIs, take PBIs from the top one by one  and break it down to tasks to then estimate them in hours (using poker planning and fibonacci) until we reach a given team's capacity.

While this works for most of the teams, there is one 2-person team where I'm a SM, that tends to systematicaly  overestimate the tasks by far (as those developers are being paid by an hour in this project, and from the record of working with them in another project I know for a fact they have a far better velocity).
Not being a part of this team as a developer, trying to adhere to Scrum I'm refraining from influencing those estimates by any means, however as we approach the deadlines in the project this situation is becoming more and more troublesome.

My question is - is there a way / good practice in such situations, to keep the team on the edge of their velocity and not influence their estimations, or maybe we're doing sth wrong in the process ?

答:
I would question every team that gets ever sprint completed all the time. This really isn't the goal. It's all right to push yourself even if it means missing a few. You can always adjust. If they can accomplish everything on time towards the end of the project, maybe they figured it out.

Developers are going to underestimate because:

There are serious consequences for not getting everything done.

They want the project to last longer, do less work, etc.

They are too caught up in the whole planning thing and think they have to be perfect. Maybe they take the whole thing too seriously or literally.

I'm sure there are more.

Regardless of how a team manages themselves, there is still a business to run, so there will be expectations of how much work you get done. Clients have expectations. People like to get paid eventually. Someone paying the bills needs to look at the project and determine if it is going to get completed in a reasonable amount of time. If not, adjust the requirements or adjust the team.

Someone who knows something about how long things take to get built (It appears you've discovered this.) has to address the team. Probably some leader in the company. This is where Jeff Shurt's answer comes in. Can you identify why they're not attempting more? Is it knowing how to plan, being too worried about not finishing a sprint, being less skilled or just slacking off. As part of scrum, you don't look at one day or one sprint. Look at several and notice the trend.

Maybe the hourly people need to be split up? Being on a team that is getting more completed could help to move them along.

Title: Scrum task over estimation


答:
@JeffO There is one more which I want to go into detail about:

Thesis 1

These two programmers estimate right but have incomplete knowledge (So do I).

This is a two-programmers-team and those two programmers

are very disconnected from the other teams.

base their work on a lot of foreign work which is hard to estimate

Since they are only two people it can be more enforced not to communicate with bigger teams because

they have more on their sholders (50%), so they can not just go somewhere and chat

they are more of a completer-finisher (Belbin), very task oriented, not too connective if it is not for problem solving they do not see any need to exchange with other teams. They are very effective and efficient on their own.

Solution:

They change their working place and work as ambassadors in those teams they should communicate more with.

In case both are not fond of that idea and very perfectionistic, dislike such change, maybe it is the wrong tasks you pass to them? Maybe they really suffer from these incomplete hack-something-together tasks they get in their user stories. Maybe user-stories with another quality of code are better?

Theses 2

They do not reflect on the tasks or the set of tasks have not so much in common.

Thesis 3

You have got a communication problem. (People always have). You turning to programmers.stackexchange before you attempted to talk to them, could be an indicator. (I do not know)

Thesis 4

How come they overestimate? Story points are no time units. I mean: they need to increase the story points every time to overestimate. You can make a story-point to time mapping from the previous iteration and take this as a basis for time calculations.

xxx
This all is speculation but I had fun writing it.

Title: Scrum task over estimation

Body:
In my current company we're using Scrum with 2 week iterations and a regular planning session.
How planning normally works in our company is that we take a predefined , prioritized (by PO before the planning) product backlog of user stories / PBIs, take PBIs from the top one by one  and break it down to tasks to then estimate them in hours (using poker planning and fibonacci) until we reach a given team's capacity.

While this works for most of the teams, there is one 2-person team where I'm a SM, that tends to systematicaly  overestimate the tasks by far (as those developers are being paid by an hour in this project, and from the record of working with them in another project I know for a fact they have a far better velocity).
Not being a part of this team as a developer, trying to adhere to Scrum I'm refraining from influencing those estimates by any means, however as we approach the deadlines in the project this situation is becoming more and more troublesome.

My question is - is there a way / good practice in such situations, to keep the team on the edge of their velocity and not influence their estimations, or maybe we're doing sth wrong in the process ?


问:
How important is graceful degradation of JavaScript?
Should web developers continue to spend effort progressively enhancing our web applications with JavaScript, ensuring that features gracefully degrade, thereby ensuring accessibility?  Or should we spend that time focused on new features or other areas of development?

The subtext of that question would be:  How many of our customers/clients/users utilize our websites or applications with JavaScript disabled?  Do you have any projects with requirements that specifically demand JavaScript functionality (almost all of mine do), and do those requirements also demand graceful degradation?

For the sake of asking this question, I pulled up programmers.stackexchange.com without JavaScript enabled, and I was greeted with this message: "Programmers - Stack Exchange works best with JavaScript enabled".  It was difficult to log in, albeit the site seemed to generally work okay.  (I wasn't able to vote up any questions.)

I think this is a satisfactory approach to development.  Imagine the effort involved in making all of the site's features work with plain old HTML and server-side logic. On the other hand, I wonder how many users have been alienated by this approach.

We've all been trained (at least the good developers among us) to use progressive enhancement and to ensure our web applications' dynamic features degrade gracefully.  Is this progressive enhancement just pissing into the wind, or do some of our customers actually utilize certain web services without JavaScript enabled?

答:
Hmm, now I feel like the Omega Man. :) Apparently I am the last person who does actually turn JavaScript (and cookies) off. (Unless I need it for a specific site like, say, Stack Overflow.)

I doubt I'm missing much - usually when I do turn on JavaScript for a site, it does something totally useless, like allow me to spew tons of personal information to total strangers, or shows me some moving ads - just what I wanted, some random movement on the screen while I'm trying to concentrate on reading an article...

ContentLicense: CC BY-SA 2.5


问:
What does HATEOAS offer for discoverability and decoupling besides ability to change your URL structure more or less freely?
Lately I've been reading about Hypermedia as the Engine of Application State (HATEOAS), the constraint that is claimed to make a web API "truly RESTful". It boils down to basically including links with every response to the possible transitions you can make from the current state.

Let me illustrate what HATEOAS is based on my understanding - and please do correct me if I missed something.

```<code>/
    GET: {
        "_links": {
            "child": [
                { "href": "http://myapi.com/articles", "title": "articles" }
            ]
        }
    }

/articles?contains=HATEOAS
    GET: {
        "_items": [
            { "uri": "http://myapi.com/articles/0", "title": "Why Should I Care About HATEOAS?" },
            { "uri": "http://myapi.com/articles/1", "title": "HATEOAS: Problem or Solution?" }
        ],
        "_links": {
            "self": { "href": "http://myapi.com/articles", "title": "articles" },
            "parent": { "href": "http://myapi.com/", "title": "home" }
        }
    }

    POST: {
        "title": "A New Article",
        "body": "Article body",
        "tags": [ "tag1", "tag2" ]
    }

/articles/0
    GET: {
        "title": "Why Should I Care About HATEOAS?",
        "body": "Blah blah blah"
        "tags": [ "REST", "HATEOAS" ],
        "_links": {
            "self": { "href": "http://myapi.com/articles/0", "title": "article" },
            "parent": { "href": "http://myapi.com/articles", "title": "articles" }
        }
    }
</code>```

HATEOAS is claimed to provide two major benefits:

The entire service is discoverable starting form the root URI, documentation is no longer needed.

The client is decoupled from the server which can now change the URI structure freely. This eliminates the need for API versioning.

But in my view, a service is a lot more than its URI structure. To use it effectively, you also need to know:

what query parameters you can use and their possible values

the structure of the JSON/XML/whatever documents you need to send in your POST/PATCH/etc requests

the structure of the response sent by the server

the possible errors that might occur

...

Based on the above, HATEOAS only solves a tiny fraction of the discoverability and coupling problems. You still need to document the above four aspects and clients will still be strongly coupled to the server because of them. To avoid breaking clients, you still need to version your API.

The only benefit it provides is that you can change your URL structure more or less freely (by the way, what happened to the principle "Cool URIs don't change"?). Is my understanding correct?

答:
Where did you read that "documentation is no longer needed" for HATEAOS services?  As you say, you still need to document the semantics of the links. However, with HATEOAS you don't need to document, and hence keep forever, the structure of most of the URIs.

HATEOAS allows a service implementer to modify and scale the implementation significantly and efficiently without changing a small set of URIs on which the client depends.  It is easier to keep a small number of entry points unchanged than a large set. Hence, reducing the number of public entry points to the service and dynamically providing links to sub-resources (HATEOAS) actually supports "Cool URIs don't change" better than non-HATEOAS services.


问:
Why we should (not) develop on a server via RDP
I have a client who is requesting that we develop their fairly small web application directly in their environment by RDP to the server that will host the app. They have had a contractor do this for a while and it has worked "fine" for them, so they are comfortable with that approach. The client's biggest concern at this point is cutting costs - they have a very tight budget.

My manager does not seem to care or think that it makes a difference. However, I strongly do not agree with that practice.

How best can I convince the client that it is bad practice to do things that way? I need to use "management" language, not developer language.

I can think of a few advantages of developing locally (as a developer):

We can not guarantee code quality in the remote environment (why not?)

Internal team collaboration increases efficiency (how?)

Internally, we can take better advantage of source control (although that can also be installed on the server)

Internally, we can follow better quality control processes

With RDP, only one developer can work on project at a time

Developing locally increases a developer's efficiency (how? maybe because it is their comfort zone? maybe with multiple monitors? how does that benefit the client?)

Unfortunately, these do not necessarily translate to something management appreciates (e.g. dollars and cents)

Please help.

答:
Ah, the client with a small website who doesn't want to pay too much.

You can't argue your way is better when the client has evidence that the other developer was able to make it work. Let the client know that your group is not use to working that way and if you have to drastically alter the way you work, you cannot predict how effective you'll be. From a financial perspective, the client shouldn't want to pay you to experiment and learn on his time. Maybe it will work, but he cannot take that risk. You don't want to make promises you can't keep.

From a business and a technical perspective this is a bad client. The development environment restrictions are a feature the client doesn't want to really pay for.


答:
Whatever the methodology, a product will fail if participants aren't motivated.

As a Scrum Master, you're part of the team, not above. The good news is, that makes at least one motivated team member :)

You must ask "why are we failing ?", not "they".

The best time to do that is during a retrospective. Bring up the point that the team's velocity hasn't improved over X sprints and ask "how could we do better ?". Analyze the impediments you're facing. Suggest things that you, as a Scrum Master, could do to remove some of those, and ask the developers what they think they could do on their end.

If there's no particular obstacle but no particular incentive either, propose challenges such as adding an extra bonus story at each sprint as a stimulation, or try to work on delighting the customer with small unexpected features.

It might seem easier said than done, but don't make it a matter of slacking off, guilt, blame or management pressure. Make it about an agile team inspects, adapts, improves, sets itself challenges and gradually more complex goals and has fun and takes pride in doing it.

Edit : Also remember that you're not alone here. The Product Owner is your best ally to push the team forward.

I recall one hard to please PO who always expected small "icing on the cake" features or UI gimmicks during demos and let the team know quite bluntly if she thought we had underperformed. In the end, we started automatically thinking about what could surprise and please her and adding it to the product during the sprint so that the review would go fine. As a result, perceived product quality increased a lot as did team motivation.

Customer satisfaction is a strong incentive especially if approval happens during a public meeting where you don't want to appear unprofessional.

Title: Scrum task over estimation


问:
What is the pattern for a safe interface in C++
Note: the following is C++03 code, but we expect a move to C++11 in the next two years, so we must keep that in mind.

I'm writing a guideline (for newbies, among others) about how to write an abstract interface in C++. I've read both articles of Sutter on the subject, searched the internet for examples and answers, and made some tests.

This code must NOT compile!

```<code>void foo(SomeInterface & a, SomeInterface & b)
{
   SomeInterface c ;               // must not be default-constructible
   SomeInterface d(a);             // must not be copy-constructible
   a = b ;                         // must not be assignable
}
</code>```

All the behaviors above find the source of their problem in slicing: The abstract interface (or non-leaf class in the hierarchy) should not be constructible nor copiable/assignable, EVEN if the derived class can be.

0th Solution: the basic interface

```<code>class VirtuallyDestructible
{
   public :
      virtual ~VirtuallyDestructible() {}
} ;
</code>```

This solution is plain, and somewhat naive: It fails all our constraints: It can be default-constructed, copy-constructed and copy-assigned (I'm not even sure about move constructors and assignment, but I have still 2 years to figure it out).

We can't declare the destructor pure virtual because we need to keep it inline, and some of our compilers won't digest pure virtual methods with inline empty body.

Yes, the only point of this class is to make the implementers virtually destructible, which is a rare case.

Even if we had an additional virtual pure method (which is the majority of the cases), this class would be still copy-assignable.

So, no...

1st Solution: boost::noncopyable

```<code>class VirtuallyDestructible : boost::noncopyable
{
   public :
      virtual ~VirtuallyDestructible() {}
} ;
</code>```

This solution is the best, because it is plain, clear, and C++ (no macros)

The problem is that it still doesn't work for that specific interface because VirtuallyConstructible can still be default-constructed.

We can't declare the destructor pure virtual because we need to keep it inline, and some of our compilers won't digest it.

Yes, the only point of this class is to make the implementers virtually destructible, which is a rare case.

Another problem is that classes implementing the non-copyable interface must then explicitly declare/define the copy constructor and the assignment operator if they need to have those methods (and in our code, we have value classes that can still be accessed by our client through interfaces).

This goes against the Rule of Zero, which is where we want to go: If the default implementation is ok, then we should be able to use it.

2nd Solution: make them protected!

```<code>class MyInterface
{
   public :
      virtual ~MyInterface() {}

   protected :
      // With C++11, these methods would be "= default"
      MyInterface() {}
      MyInterface(const MyInterface & ) {}
      MyInterface & operator = (const MyInterface & ) { return *this ; }
      MyInterface(MyInterface && ) noexcept {}
      MyInterface & operator = (MyInterface && ) noexcept { return *this ; }
} ;
</code>```

This pattern follows the technical constraints we had (at least in user code): MyInterface cannot be default-constructed, cannot be copy-constructed and cannot be copy-assigned.

Also, it imposes no artificial constraints to implementing classes, which are then free to follow the Rule of Zero, or even declare a few constructors/operators as "= default" in C++11/14 without problem.

Now, this is quite verbose, and an alternative would be using a macro, something like:

```<code>class MyInterface
{
   public :
      virtual ~MyInterface() {}

   protected :
      DECLARE_AS_NON_SLICEABLE(MyInterface) ;
} ;
</code>```

The protected must remain outside the macro (because it has no scope).

Correctly "namespaced" (that is, prefixed with the name of your company or product), the macro should be harmless.

And the advantage is that the code is factored in one source, instead of being copy pasted in all interfaces. Should the move-constructor and move-assignment be explicitly disabled the same way in the future, this would be a very light change in the code.

Conclusion

Am I paranoid to want the code to be protected against slicing in interfaces? (I believe I'm not, but one never knows...)

What is the best solution among the ones above?

Is there another, better solution?

Please remember that this is a pattern that will serve as a guideline for newbies (among others), so a solution like: "Each case should have its implementation" is not a viable solution.

Bounty and results

I awarded the bounty to coredump because of the time spent to answer the questions, and the relevance of the answers.

My solution to the problem will probably go to something like that:

```<code>class MyInterface
{
   DECLARE_CLASS_AS_INTERFACE(MyInterface) ;

   public :
      // the virtual methods
} ;
</code>```

... with the following macro:

```<code>#define DECLARE_CLASS_AS_INTERFACE(ClassName)                                \
   public :                                                                  \
      virtual ~ClassName() {}                                                \
   protected :                                                               \
      ClassName() {}                                                         \
      ClassName(const ClassName & ) {}                                       \
      ClassName & operator = (const ClassName & ) { return *this ; }         \
      ClassName(ClassName && ) noexcept {}                                   \
      ClassName & operator = (ClassName && ) noexcept { return *this ; }     \
   private :
</code>```

This is a viable solution for my problem for the following reasons:

This class cannot be instantiated (the constructors are protected)

This class can be virtually destroyed

This class can be inherited without imposing undue constraints on inheriting classes (e.g. the inheriting class could be by default copiable/moveable)

The use of the macro means the interface "declaration" is easily recognizable (and searchable), and its code is factored in one place making it easier to modify (a suitably prefixed name will remove undesirable name clashes)

Note that the other answers gave valuable insight. Thank you to all you who gave it a shot.

Note that I guess I can still put another bounty on this question, and I value enlightning answers enough that should I see one, I would open a bounty just to assign it to that answer.

答:
Am I paranoid...

Am I paranoid to want the code to be protected against slicing in interfaces? (I believe I'm not, but one never knows...)

Isn't this a risk management issue?

do you fear that a bug related to slicing is likely to be introduced?

do you think it can go unnoticed and provoke unrecoverable bugs?

to what extent are you willing to go to avoid slicing?

Best solution

What is the best solution among the ones above?

Your second solution ("make them protected") looks good, but bear in mind that I am not a C++ expert.

At least, the invalid usages seem to be correctly reported as erroneous by my compiler (g++).

Now, do you need macros? I would say "yes", because even though you don't say what is the purpose of the guideline you are writing, I guess this is to enforce a particular set of best practices in your product's code.

For that purpose, macros can help detect when people effectively apply the pattern: a basic filter of commits can tell you whether the macro was used:

if used, then the pattern is likely to be applied, and more importantly, correctly applied (just check that there is a protected keyword),

if not used, you can try to investigate why it wasn't.

Without macros, you have to inspect whether the pattern is necessary and well-implemented in all cases.

Better solution

Is there another, better solution?

Slicing in C++ is nothing more than a peculiarity of the language.
Since your are writing a guideline (esp. for newbies), you should focus on teaching and not just enumerating "coding rules".
You have to make sure that you really explain how and why slicing occurs, along with examples and exercices (don't reinvent the wheel, get inspiration from books and tutorials).

For example, the title of an exercise could be "What is the pattern for a safe interface in C++?"

So, your best move would be to ensure that your C++ developpers understand what is going on when slicing occurs. I am convinced that if they do, they won't make as many mistakes in the code as you'd fear, even without formally enforcing that particular pattern (but you can still enforce it, compiler warnings are good).

About the compiler

You say :

I have no power on the choice of compilers for this product,

Often people will say "I don't have the right to do [X]", "I'm not supposed to do [Y]...", ... because they think this is not possible, and not because they tried or asked.

It is probably part of your job description to give your opinion regarding technical issues; if you really think the compiler is the perfect (or unique) choice for your problem domain, then use it. But you also said "pure virtual destructors with inline implementation is not the worst choking point I've seen"; from my understanding, the compiler is so special that even knowledgeable C++ developpers have difficulties using it: your legacy/in-house compiler is now technical debt, and you have the right (the duty?) to discuss that issue with other developpers and managers.

Try to assess the cost of keeping the compiler vs. the cost of using another one:

What does the current compiler brings you that no other one can?

Is your product code easily compilable using another compiler? Why not?

I don't know your situation, and in fact you probably have valid reasons to be tied to a specific compiler.

But in the case this is just plain inertia, the situation won't ever evolve if you or your coworkers don't report productivity or techical debt problems.

OwnerDisplayName: paercebal

ContentLicense: CC BY-SA 4.0


问:
Why write clean, refactored code?
From my experience of working on several Java based projects, I've seen tons of codes which we call 'dirty'. The unconventional class/method/field naming, wrong way of handling of exceptions, unnecessarily heavy loops and recursion etc. But the code gives the intended results.

Though I hate to see dirty code, it's time taking to clean them up and eventually comes the question of "is it worth? it's giving the desired results so what's the point of cleaning?"

In team projects, should there be someone specifically to refactor and check for clean code? Or are there situations where the 'dirty' codes fail to give intended results or make the customers unhappy?

What I mean by WHY is not the technical reasons, I'm asking about the motive.** We all are familiar with why we should write clean code in technical point of view. But, imagine in college if I write bad code, I get bad marks. So in your industrial environment what motivates you and your team to write clean code? And what de-motivates you and team from writing bad code?

It's so easy to write a method in a class to get the information you need without looking around and checking if there's a similar method! Result? 5000 + lines of code with few methods doing almost similar tasks.

答:
To me in practice this question translates to 'Why write smaller code?', because in practice smaller, more unit-able blocks of code invite the possibility of nicer and cleaner design.  Manipulating theses smaller blocks becomes much easier than the large ones, and they are more inviting to be refactored as needed.

Now, my answer:

after mulling over some significantly decent legacy code base refactoring, it has been my experience, that large blocks of code (classes, functions, etc), invite more code.  More code applied indiscriminately breaks up the things like responsibility principle, and other best practices.

So my answer as to why write smaller code?

it forces you to think about your code structure and layout more, while preventing mentality (and sometimes necessity) of "let's stuff more stuff into this code block".  I say necessity, because when coming across a huge block, it may be necessary to make things work now, rather than take time to refactor, due to time pressures.

It is easier to do refactoring work on a set of smaller self-contained code pieces even if they are ugly than to work on breaking up huge entangled ugly methods.

it helps future programmers who will be working on your code base to figure out what you were doing.  While not always true, smaller units of code that have their purpose and that are reasonably self-contained, will help you build a mental model faster than long ambiguous everything code spans.

it prevents future programmers from moments of what the [heck] was this code supposed to be doing? and why does this or that code piece doing these things in this particular and peculiar way?, as large code blocks tend to hide bad practices and various bugs and logic errors.

OwnerDisplayName: Shamal Karunarathne

Title: Why write clean, refactored code?


问:
Looking for a certain datatype if it exists
I'm looking for the kind of a certain datatypes.

The main idea of this datatype is to describe a productionline containing several steps. Each step should be represented as a "vertex" containing an object of any type. Then for every "vertex" there are possible "subproductionlines" joining the line.

So it could look something like:

```<code>                  O   ->   O   ->   |                    #   subproductionline
                                    |                    #   joiningpoint
O   ->   O   ->   O   ->   O   ->   O   ->   O   ->   O  # main productionline
                                    |                    #   joiningpoint
         O   ->   O   ->   O   ->   |                    #   subproductionline
                           |                             #   joiningpoint
                  O   ->   |                             #subsubproductionline
</code>```

Does anyone of you know such a datatype?

If I were to code such a datatype... I see there two options of doing this:

A datatype as an Array (main productionline) containing Arrays (containing as first element the containing data of each vertex) and the rest of elements containing subproductionlines as recursive this datatype

or

A datatype as an Array containing the data stored in the vertex. Last element is either the element, where this subproductionline is joining, or a specific element representing the end of a main productionline, if it is one.

What do yout think is the better solution?

The programming language I think of using for is c / c++.

答: I would characterise this as a directed graph. Each vertex (or node) is a stage in processing, and each edge links two stages in a production process.</p>


问:
New User Registration Logic
I am writing up a user registration application in PHP as part of my learning process. I have written up the general rules my code should follow. Please let me know what you guys think of it.

Have a form with the email address and password.

Generate 2 random tokens to be appended to the URL to validate the email and complete the registration. Send user en email with the URLs.
Use the first token to continue the registration and the second token to cancel (In the case where the registration request was unsolicited).

At this point, in the database table, I maintain a table with 6 columns - email, password, register_token, cancel_register_token, counter,
timer.

When user clicks on the link to continue with the registration process, prompt the user for the password. If the user had inadvertently
entered an incorrect email address, then that someone else obviously doesn't know the password and cant continue with the registration.

If the user who already has an active email in the db, waiting to register, wants an activation email sent again (maybe someone else
registered the email on his behalf, unsolicited and he doesn't have the password to continue), then create another 2 random tokens, erasing the first set from the table and keeping a counter, increasing the counter each time a new set of tokens are generated against an email. When the counter reaches a maximum, do not accept any more requests. Maybe a max of 5 such requests and no more.

Keep the register link alive for 1 day if there is no activity. Use the timer column for the same.

答:
You're well on your way to a successful implementation of a user registration process.  However, there are still some unknowns that you haven't addressed, that can impact your desired outcome.

How are you tracking that the user's account has been activated?  It seems that once the user clicks the link to activate, there's no record that it's been activated in your database, as you don't have an "active/ated" flag set.

You will be hashing the password in the database, correct?  You didn't really say either way in your question, but it's something to pay close attention to.  Leaving a plain-text password in the database is a big no-no.

I don't know if keeping a counter of the number of tokens created serves you much of a purpose.  If the user generates more than 5 (per your example), are you going to tell them "Sorry, tough luck, you've requested activation too many times"?  I am with you on generating a new set of tokens and blowing away the old ones each time they request one, but I don't think it serves much purpose to limit them (unless you're wanting to prevent them from being able to predict and determine your token generating algorithm - in which case you need to look at generating a better algorithm instead).

Your timer is probably a safe bet.  You might want to change it to be a "token_generation_datetime" or something instead, rather than a "timer".  That way you can use it more for what it is.  I think of a timer as a value demonstrating the length of time since an activity has started, or the amount of time remaining.  In your case, since the data in that column is static based on the date that the tokens were generated, I'd use a different column name instead of "timer".

I'm not a huge fan of having to reenter my password when clicking on a hashed activation link in my email account.  The fact that I received the email in my email account is verification enough that my email is valid.  I shouldn't have to reenter my password again just to validate my email address.

Other than those points, you're on the right track with a user registration process.  As @gnat pointed out, however, you need to look more at the big picture, and provide exactly what you're trying to do.  "Is business logic correct?" is hard to answer, without understanding the scope and end-goal of what it is that you're trying to accomplish.

Title: New User Registration Logic


问:
Parameterless & Empty-Paren methods in Scala
I'm learning Scala at the moment via Odersky's Programming Scala (2nd). I'm upto chapter 10 where he starts introducing parameterless and empty-paren methods. I just can't get my head around it.

So far, all I understand is that I should use empty-parens if a method has side-effects and parameterless methods otherwise.

I can't figure out what is the advantage of this convention. I read the posts on Stack Exchange, but to be honest, when the posts start discussing this topic in some depth I was lost.

I'm looking for a simple explanation of what are typical use cases for this language feature and what are the advantages to help me understand it better.

答:
That is a convention, not part of the language design.  It is used as a signpost to help the folks who have to read the code after you write it to understand it better.

From Scala's Style Guide on Method Invocation:

Scala allows the omission of parentheses on methods of arity-0 (no
  arguments):

```<code>reply()

// is the same as

reply
</code>```

However, this syntax should only be used when the method in question
  has no side-effects (purely-functional). In other words, it would be
  acceptable to omit parentheses when calling queue.size, but not when
  calling println().

Religiously observing this convention will dramatically improve code
  readability and will make it much easier to understand at a glance the
  most basic operation of any given method. Resist the urge to omit
  parentheses simply to save two characters!

In .NET, the convention is to use methods when the code can take awhile to run (say, longer than 50ms), and properties (essentially empty-paren methods) when it won't (i.e. it is a simple lookup).

Body:
That is a convention, not part of the language design.  It is used as a signpost to help the folks who have to read the code after you write it to understand it better.

From Scala's Style Guide on Method Invocation:

Scala allows the omission of parentheses on methods of arity-0 (no
  arguments):

reply()

// is the same as

reply

However, this syntax should only be used when the method in question
  has no side-effects (purely-functional). In other words, it would be
  acceptable to omit parentheses when calling queue.size, but not when
  calling println().

Religiously observing this convention will dramatically improve code
  readability and will make it much easier to understand at a glance the
  most basic operation of any given method. Resist the urge to omit
  parentheses simply to save two characters!

In .NET, the convention is to use methods when the code can take awhile to run (say, longer than 50ms), and properties (essentially empty-paren methods) when it won't (i.e. it is a simple lookup).


问:
Should performance tests be instrumented by build tools?
Should performance tests be instrumented by build tools as part of the build process, or should they live completely outside? If outside, then where in the deployment pipeline should they live?

I currently see performance tests being attached to integration testing lifecycle phases.  While it's fine for now, I know this doesn't seem quite right, and I'm having difficulty finding an actual answer as to where we should be attaching and running these performance tests.

For the sake of the question, we can assume an environment utilizing Jenkins for CI, and Maven as a build tool. We can also assume a scrum SDLC.

答:
There are typically two reasons for worrying about performance/load testing, either the team has trouble writing simple algorithms or specific performance requirements are part of an SLA. The third reason is that members of your team just like to worry about performance, aka Premature Optimization.

Performance tests should never be part of your unit testing. Unit tests are, by definition, for testing the correctness of the unit; Bubble Sort and Quick Sort are both valid implementations for a sorting requirement. Even if you have a performance requirement, that requirement will not be on the unit but on a vertical slice of the system. Assuming the bottleneck to be this unit is assuming too much. And if your unit tests take too long to run (ideally under one second, never more than 10) they become useless; developers start running them less frequently, not at all, or stop writing tests. Which leaves two options.

Make your performance tests part of your deployment pipeline. Performance tests are run after unit and integration tests as part of every commit (or whatever action triggers your pipeline). They will be run on your built artifact. Go this route if a SLA demands certain performance characteristics or if you're having trouble wrangling in your team's code quality ("Every time Jimmy makes a commit it brings the servers to their knees under heavy load and we spend days debugging the issue!").

Run your performance tests at night. Performance tests are scheduled to run at a certain time of the day. This is good for when your performance/load tests take a long time. Maybe you went the former route but these tests are becoming a bottleneck to releasing as frequently as you'd like. Now that you've gotten in the habit of running them more frequently maybe your team has gotten better at writing simple algorithms. Maybe now you can break your load tests apart into "tests that are absolutely required before we deploy to production" and "tests that keep us in good shape but problems with them don't surface that much".

It could be, as Doc Brown mentioned, that your performance tests take a week to run. But that's such an edge case I'll leave you to figure that one out when you get there. Report back here with your findings.

Running performance tests as part of your integration test phase doesn't feel right. Performance and load tests are generally used to track down problems with a vertical slice of your application so that you then have an indication of where to dive in. There wouldn't be much value to mocking out services as performance is a fickle beast. These services will respond differently under different loads. However, there could certainly be some 3rd party endpoint where they couldn't provide a sandbox for you. Maybe you can take production response time and stub them out appropriately. That response time could even be automated as new data comes in everyday.

There won't be a one size fits all and I suspect as you move forward you will come across a novel solution.


答:
I use NoScript along with the AdBlock Plus all the time.

The web today is too hostile (intrusive JavaScript + annoying ads) to go out unprotected.

Title: How important is graceful degradation of JavaScript?

Body:
Should web developers continue to spend effort progressively enhancing our web applications with JavaScript, ensuring that features gracefully degrade, thereby ensuring accessibility?  Or should we spend that time focused on new features or other areas of development?

The subtext of that question would be:  How many of our customers/clients/users utilize our websites or applications with JavaScript disabled?  Do you have any projects with requirements that specifically demand JavaScript functionality (almost all of mine do), and do those requirements also demand graceful degradation?

For the sake of asking this question, I pulled up programmers.stackexchange.com without JavaScript enabled, and I was greeted with this message: "Programmers - Stack Exchange works best with JavaScript enabled".  It was difficult to log in, albeit the site seemed to generally work okay.  (I wasn't able to vote up any questions.)

I think this is a satisfactory approach to development.  Imagine the effort involved in making all of the site's features work with plain old HTML and server-side logic. On the other hand, I wonder how many users have been alienated by this approach.

We've all been trained (at least the good developers among us) to use progressive enhancement and to ensure our web applications' dynamic features degrade gracefully.  Is this progressive enhancement just pissing into the wind, or do some of our customers actually utilize certain web services without JavaScript enabled?


答:
I took your question as why not design the language to prevent the need for a convention in the first place?  In other words, why doesn't Scala just force the use of parentheses all the time, instead of allowing programmers to omit them sometimes?

The answer is found in referential transparency.  Essentially, if a function has no side effects, a function call can be replaced with its result, without changing the behavior of the program.

That means a function without parameters or side effects is semantically equivalent to a val holding the return value of that function.  Because of this property, as a class evolves, the programmer might switch back and forth between using a val or using a function, as convenience or efficiency dictates.

Since you can omit the parentheses, that means code calling something like queue.size doesn't need to know nor care if size is a function or a val.  The implementer of the Queue class is therefore free to change between the two without having to change any of the calling code (although I believe it will need recompiling).  It stabilizes the public interface of the class.   For example, you might start out a queue.size by calling size on an underlying List, which is potentially O(n), then change size to a val for reasons of efficiency.

The convention suggests the parentheses when there are side effects to make it clear that this class member is definitely a function call, and therefore potentially not referentially transparent.  It's important for calling code to know if side effects are produced, so they can avoid calling it repeatedly.  If you don't care whether it's a function or not, you may as well treat it as if it's not.

Title: Parameterless & Empty-Paren methods in Scala

Body:
I'm learning Scala at the moment via Odersky's Programming Scala (2nd). I'm upto chapter 10 where he starts introducing parameterless and empty-paren methods. I just can't get my head around it.

So far, all I understand is that I should use empty-parens if a method has side-effects and parameterless methods otherwise.

I can't figure out what is the advantage of this convention. I read the posts on Stack Exchange, but to be honest, when the posts start discussing this topic in some depth I was lost.

I'm looking for a simple explanation of what are typical use cases for this language feature and what are the advantages to help me understand it better.


问:
Why isn't there an html tag "field"?
There is a <fieldset> tag for a set of fields.

Why isn't there a hierarchical child for fieldsets?

```<code><form>
    <fieldset>
        <legend>Thin Sandwich Options</legend>
        <field>
            <label>Meat</label>
            <div class='inputs'>
                <label>
                    <input type="radio" name="meat" value="turkey" />Turkey</label>
                <label>
                    <input type="radio" name="meat" value="monkey" />Monkey</label>
            </div>
            <div class='desc'>Pick one meat for the thin sandwich.</div>
        </field>
        <field>
            <label>Cheese</label>
            <div class='inputs'>
                <label>
                    <input type="checkbox" name="cheese" value="chedder" />Cheddar</label>
                <label>
                    <input type="checkbox" name="cheese" value="swiss" />Swiss</label>
            </div>
            <div class='desc'>Pick one meat for the thin sandwich.</div>
        </field>
    </fieldset>
    <fieldset>
        <legend>Beverage Options</legend>
        <field>
            <label for="carbonated">Carbonated</label>
            <div class='inputs'>
                <label>
                    <input type="radio" name="carbonated" value="coke" />Coke</label>
                <label>
                    <input type="radio" name="carbonated" value="mtn-dew" />Dew</label>
            </div>
            <div class='desc'>Pick one beverage per combo.</div>
        </field>
        <field>
            <label for="non-carbonated">Non Carbonated</label>
            <div class='inputs'>
                <label>
                    <input type="radio" name="non-carbonated" value="tea-sweet" />Tea (non sweetend)</label>
                <label>
                    <input type="radio" name="non-carbonated" value="tea" />Tea</label>
            </div>
        </field>
    </fieldset>
</form>
</code>```

http://jsfiddle.net/5dC8c/

I keep coming back to this question whenever I am working on my HTML form layouts.

As MDN defines it:

The HTML <fieldset> element is used to group several controls as
  well as labels () within a web form.

I see a <field> element as grouping a single control (or set of radio buttons) with a single label and a description. The field tag would have some of the same attributes that the input tag has, readonly, required, etc.

Why does bootstrap use the class 'form-group'?

Why does Wufoo use li tags for each field?

Enclosing related form elements into fields would add clarity.

Every major front-end framework has some class or tag to differentiate each field.

Why the heck don't we have a single HTML tag to bring some normality to form design?

Update: added a better HTML example of the usage of a <field> tag.

答:
Why does bootstrap use the class 'form-group'?

Why does Wufoo use li tags for each field?

The people you should be asking these questions are the authors of these frameworks.

Enclosing related form elements into fields would add clarity.

You can do this easily enough with the standard elements as they are now. A fieldset allows you to group multiple inputs. The label tag can be used to tie an input to its description.

Every major front-end framework has some class or tag to differentiate
  each field.

This is because each framework has a specific approach to styling these fields and no matter what standards you come up with, people will keep inventing their own ones... which leads us to the point...

Why the heck don't we have a single HTML tag to bring some normality
  to form design?

Because HTML tags are not about design. HTML is supposed to represent content, the structure of information and not how something looks. Apparently, the people responsible for the development of the standard consider the current state of the language sufficient in this matter. Web designers are given a lot of freedom as to how to style these elements with CSS as well as to use additional elements around them, which is exactly what you observed.

To sum up, design is not what the language is about. Semantics are the core of the specification. If you ever try to standardize designs, there's only one way this can turn out. Randall Munroe, the author of XKCD makes an excellent point about this phenomenon:

Title: Why isn't there an html tag "field"?


答:
The things is, HATEOAS must come with a second pillar that define what a RESTful API is : standardized media type. Roy fielding himself said

A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources".

With a standardized media type that define the transition explicitely, and hypertext to point resource to each other, you can create a resource graph that can take any form without breaking any client. Like the web work, really: you have link between document, and document are written in HTML that define how to follow those links.  is a GET, <form> is GET or POST (and define the url template to use in case of GET), <link type="text/css"> is GET... etc. This is how browsers can navigate arbitrary structured HTML page and the Web.

All the point you made

what query parameters you can use and their possible values

the structure of the JSON/XML/whatever documents you need to send in your POST/PATCH/etc requests

the structure of the response sent by the server

the possible errors that might occur

Are points that should be adressed by the definition of you standardized media type. Of course, this is much harder, and not something that most people think about when they define a "REST" API. You can't just take you business entities and shove their attributes into a JSON document to have a RESTful API.

Of course, what happened is REST got somehow diluted to mean "use HTTP instead of complicated SOAPy thingy". Just using HTTP and HyperText is not enough to be RESTful, this is what most people get wrong.

Not that this is necessary a bad things : REST make sacrifice of performance and ease of development in exchange for longer term maintainability and evolutivity. It was made for big entreprise application integration. A small web API with hard-coded JSON structure may be what you need. Just don't call it REST, its an ad-hoc web API, nothing more. And that don't mean it suck, it just mean it doesn't try to follow the constraint of REST.

Further reading

http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven

href="http://martinfowler.com/articles/richardsonMaturityModel.html" rel="nofollow">http://martinfowler.com/articles/richardsonMaturityModel.html

Hope this help clarify a bit :)

Title: What does HATEOAS offer for discoverability and decoupling besides ability to change your URL structure more or less freely?

Body:
Lately I've been reading about Hypermedia as the Engine of Application State (HATEOAS), the constraint that is claimed to make a web API "truly RESTful". It boils down to basically including links with every response to the possible transitions you can make from the current state.

Let me illustrate what HATEOAS is based on my understanding - and please do correct me if I missed something.

```<code>/
    GET: {
        "_links": {
            "child": [
                { "href": "http://myapi.com/articles", "title": "articles" }
            ]
        }
    }

/articles?contains=HATEOAS
    GET: {
        "_items": [
            { "uri": "http://myapi.com/articles/0", "title": "Why Should I Care About HATEOAS?" },
            { "uri": "http://myapi.com/articles/1", "title": "HATEOAS: Problem or Solution?" }
        ],
        "_links": {
            "self": { "href": "http://myapi.com/articles", "title": "articles" },
            "parent": { "href": "http://myapi.com/", "title": "home" }
        }
    }

    POST: {
        "title": "A New Article",
        "body": "Article body",
        "tags": [ "tag1", "tag2" ]
    }

/articles/0
    GET: {
        "title": "Why Should I Care About HATEOAS?",
        "body": "Blah blah blah"
        "tags": [ "REST", "HATEOAS" ],
        "_links": {
            "self": { "href": "http://myapi.com/articles/0", "title": "article" },
            "parent": { "href": "http://myapi.com/articles", "title": "articles" }
        }
    }
</code>```

HATEOAS is claimed to provide two major benefits:

The entire service is discoverable starting form the root URI, documentation is no longer needed.

The client is decoupled from the server which can now change the URI structure freely. This eliminates the need for API versioning.

But in my view, a service is a lot more than its URI structure. To use it effectively, you also need to know:

what query parameters you can use and their possible values

the structure of the JSON/XML/whatever documents you need to send in your POST/PATCH/etc requests

the structure of the response sent by the server

the possible errors that might occur

...

Based on the above, HATEOAS only solves a tiny fraction of the discoverability and coupling problems. You still need to document the above four aspects and clients will still be strongly coupled to the server because of them. To avoid breaking clients, you still need to version your API.

The only benefit it provides is that you can change your URL structure more or less freely (by the way, what happened to the principle "Cool URIs don't change"?). Is my understanding correct?

Body:
The things is, HATEOAS must come with a second pillar that define what a RESTful API is : standardized media type. Roy fielding himself said

A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources".

With a standardized media type that define the transition explicitely, and hypertext to point resource to each other, you can create a resource graph that can take any form without breaking any client. Like the web work, really: you have link between document, and document are written in HTML that define how to follow those links. <a href> is a GET, <form> is GET or POST (and define the url template to use in case of GET), <link type="text/css"> is GET... etc. This is how browsers can navigate arbitrary structured HTML page and the Web.

All the point you made

what query parameters you can use and their possible values

the structure of the JSON/XML/whatever documents you need to send in your POST/PATCH/etc requests

the structure of the response sent by the server

the possible errors that might occur

Are points that should be adressed by the definition of you standardized media type. Of course, this is much harder, and not something that most people think about when they define a "REST" API. You can't just take you business entities and shove their attributes into a JSON document to have a RESTful API.

Of course, what happened is REST got somehow diluted to mean "use HTTP instead of complicated SOAPy thingy". Just using HTTP and HyperText is not enough to be RESTful, this is what most people get wrong.

Not that this is necessary a bad things : REST make sacrifice of performance and ease of development in exchange for longer term maintainability and evolutivity. It was made for big entreprise application integration. A small web API with hard-coded JSON structure may be what you need. Just don't call it REST, its an ad-hoc web API, nothing more. And that don't mean it suck, it just mean it doesn't try to follow the constraint of REST.

Further reading

http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven

http://martinfowler.com/articles/richardsonMaturityModel.html

Hope this help clarify a bit :)


问:
Persistence frameworks and common sense
I have studied some persistence frameworks mainly Hibernate, DORM, TMS Aurelius and I'm wondering. In a model of type:

```<code>TOrderFiscal < > ----- > Items < > -------- > TOrderItem ------- > TProduct

TOrderFiscal --------- > TSuplier --------- > TCidade -------- > State
</code>```

Each class of this with countless attributes, all mapped correctly to their corresponding tables and fields. When carrying a note without using "Lazy Load" would always be done with several joins select all fields to come from each of these classes.

But it would be a waste since the note need only the supplier code and name attributes, the attributes OrderItem need only code, qty name. stock.

What solution should be taken to create a specific class supplier of note just with these attributes ? eg

```<code>TOrder <> ----- > Items <> -------- > TOrderItem ------- > TNotaItemProduct

TOrder -------- > TOrderSupplier
</code>```

If this is the solution , what happens when a business rule in TProduct should also be TOrderItemProduct? I duplicate code in both classes? Do heritage, eg TORderItemProduct and TProduct both inheriting from TBaseProduct ?

Or is this a concern that we programmers we should not have ?

答:
This is what we use the Hibernate Query Language (hql) for - to select only the desired data when the entire object web is not needed. For example:

```<code>select new map (s.code as sCode, s.name as sName, i.code as iCode, i.qty as qty, i.name as iName, i.stock as stock)
from TOrderFiscal tof
join tof.suplier s
join tof.items i
join i.product p
where p.id = 12345;
</code>```

You will get back a list of map of string to object, where each item in the list is a row in the result set represented as a map of the selected field aliases to the field values.

Title: Persistence frameworks and common sense

Body:
This is what we use the Hibernate Query Language (hql) for - to select only the desired data when the entire object web is not needed. For example:

select new map (s.code as sCode, s.name as sName, i.code as iCode, i.qty as qty, i.name as iName, i.stock as stock)
from TOrderFiscal tof
join tof.suplier s
join tof.items i
join i.product p
where p.id = 12345;

You will get back a list of map of string to object, where each item in the list is a row in the result set represented as a map of the selected field aliases to the field values.


答: I do. NoScript all the way. I'll quit when browsers are sandboxed, and not before.</p>


问:
Compile-time IOC
Has anyone started a project to do IOC at compile time (possibly using Roslyn or Linq MethodInfo emit)?

My experience with IOC containers has thus far been great, baring a few small issues

Many IOC containers are slow to start up, as much of the resolution logic occurs here

It is often hard to ensure that resolution is possible, as compilation no longer ensures that the constructor can be called

Often IOC containers add a small overhead to the runtime (some aren't even small, often the ones that start up quickly run slowly)

It seems to me that the ideal solution would be to add a compile step to the build chain that adds a Factory class instead of IOC.

Has anyone done this before? If not, why not?

答:
Dagger for Java/Android does that. It sacrifices some runtime magic (like Guice's) to offer an almost completely compile-time codegen experience, including converting most runtime errors to compilation errors. </p>

<p>Would be cool in .NET too. </p>

Title: Compile-time IOC

Body:
Dagger for Java/Android does that. It sacrifices some runtime magic (like Guice's) to offer an almost completely compile-time codegen experience, including converting most runtime errors to compilation errors.

Would be cool in .NET too.


问:
What is the process of determining which method in a class hierarchy should execute known as?
I thought I understood inheritance and polymorphism, but I was given this question, and I can't, for the life of me, figure out what the proper answer is or what they're trying to get at:

The process of determining which method in a class hierarchy should
  execute is known as:

a) inheritance

b) polymorphism

c) is-a

d) has-a

e) parent class

Looking at each of the terms, none of them seem like the proper answer.

Inheritance is just when a class automatically gets the public variables and methods in its parent class. So this clearly isn't the right answer.

Polymorphism allows us to write one method to handle object A, and as a result will work with everything that extends object A (or continues to extend it, IE Object B extends Object A. Object C extends Object B, etc) So this clearly isn't the right answer!

Is-a: This doesn't even make any sense. Is-a is just used to declare that a class is an instance of its parent class (dog is-an animal), so it inherits its public variables and methods. I don't see how this is "determining which method in a class hierarchy should execute"

Has-a: I'm not too familiar with this, but it's essentially composition, where Object-A has-a Object B, but object-B isn't an instance of Object A. This doesn't seem like the right answer either

Parent Class: This is just the base class, if we trace the tree of inheritance up, the top of the tree is the parent class.

Can someone please explain which term can also be defined as "The process of determining which method in a class hierarchy should execute is known as"?

Am I not understanding one or more of the terms? Is this simply a poorly worded question?

答:
The question asks "which process determines which method should execute?"

This is a bad question.

But, we can immediately eliminate three of the choices: Is-A, Has-A, and Parent Class, since those are object-oriented, but not certainly not processes.  Even if Is-A and Has-A were processes, they would be processes regarding class and composition, as you said, not method execution.

Inheritance is a process (also a concept), a process of inheriting the traits of the parent class.  By that definition alone, we can eliminate it.

That leaves us with only Polymorphism, which is part of why this is a bad question.  Polymorphism sounds like a concept, more than a process.  However, if considered to be a process, it would be a process of "polymorphing" or "taking a different shape".  An answer on Stack Overflow says:

So polymorphism is the ability (in programming) to present the same interface for differing underlying forms (data types).

By that definition, we're talking about a process where an object can act as one or more underlying real types.  You have an interface, and the underlying data types determine which method should actually be called.

We're looking for a process that matches the statement "determining which method in a class hierarchy should execute", and I think that matches pretty well.

It's also a bad question because that statement could mean many other things, and I don't think many people would really described the "determining" part to be the polymorphism -- instead, I'd consider polymorphism to be the definition part.


答:
None of the above. There is no universal term, it depends on the language and the community, but the correct answer is one of

message dispatch

(virtual) method dispatch

(virtual) method resolution

(virtual) method lookup

vtable lookup

or a similar term.

Title: What is the process of determining which method in a class hierarchy should execute known as?

Body:
I thought I understood inheritance and polymorphism, but I was given this question, and I can't, for the life of me, figure out what the proper answer is or what they're trying to get at:

The process of determining which method in a class hierarchy should
  execute is known as:

a) inheritance

b) polymorphism

c) is-a

d) has-a

e) parent class

Looking at each of the terms, none of them seem like the proper answer.

Inheritance is just when a class automatically gets the public variables and methods in its parent class. So this clearly isn't the right answer.

Polymorphism allows us to write one method to handle object A, and as a result will work with everything that extends object A (or continues to extend it, IE Object B extends Object A. Object C extends Object B, etc) So this clearly isn't the right answer!

Is-a: This doesn't even make any sense. Is-a is just used to declare that a class is an instance of its parent class (dog is-an animal), so it inherits its public variables and methods. I don't see how this is "determining which method in a class hierarchy should execute"

Has-a: I'm not too familiar with this, but it's essentially composition, where Object-A has-a Object B, but object-B isn't an instance of Object A. This doesn't seem like the right answer either

Parent Class: This is just the base class, if we trace the tree of inheritance up, the top of the tree is the parent class.

Can someone please explain which term can also be defined as "The process of determining which method in a class hierarchy should execute is known as"?

Am I not understanding one or more of the terms? Is this simply a poorly worded question?


问:
Is it common for the founder of a web app to lack technical expertise to scale it?
When I look at things like Twitter, it seems like the idea is so simple to implement initially that the founder does not have to be very technically talented. Basically it's just a guy with a good idea. But when an app / software blows up and entails much harder engineering problems, how does the founder deal with it?

Have we seen cases in which the original guy with the good idea somehow falls off the enterprise as it becomes more about technical challenges and less about ideas?

答:
When you get large enough that scaling well really matters and you have to start dealing with things like caching and database tuning, hopefully you are making enough money that you can hire somebody who specializes in performance tuning (or even better, a team of people, each specialized in a different sub-area).

When a startup begins, each founder has to do a bit of everything. I'm a coder, but I help with marketing and do some of the accounts, because there are just not enough hands to have everybody do only the thing they are best at. You want a small number of generalists.

In an established business, you want everybody just doing the thing they are best at. If you have a gap in expertise, you fill it with somebody who has that expertise. You want a large number of specialists.


问:
Was getting a computing science degree easier 10 years ago
I am currently a 3rd year computing science student at a Canadian University. I find it quite challenging, and extremely interesting. One thing  that i have noticed is that each person i speak to that took a class 3 or so years ago learned much less than i did in the same class, and people who are taking 1st year classes are doing more than i remember doing in my 1st year classes. Is this just me remembering stuff bad, or do you believe that getting a computing science degree was easier 10 (or even 5) years ago? </p>

答:
Interesting question.  You don't really classify why you think this or what empirical evidence you're using to come to this conclusion.

There was a period of time 95-05'ish or so where I believe that most CS graduates did not have the same level of problem solving, practical algorithms and language understanding that those that came before that time.  With no bias nor cause, I attributed this to the mass introduction of Microsoft platforms into the University vs. the more time-shared systems.

I once helped with a mandated summer practicum where students spent quite literally weeks converting a 16-bit number to ASCII output.  First, they didn't think about using something like  sprintf(), but second they didn't really understand 2's compliment or what ASCII even meant.  Growing up in the FidoNet world, I just couldn't fathom how they didn't know ASCII.

We evolve though, and there are some seriously good languages now and CS certainly ain't the hip thing to do anymore, so our statistical population of CS majors is probably a little less diluted?


问:
Design Hash table with simple hash function
I want to learn to Design Hash table with simple hash function for better understanding. I understand that the hash table will work as long as the hash function maps each key to a non-negative integer less than the size of the hash table, but it will only perform well if it distributes different keys across different buckets.

My question is : What's a alternative ways to implement hash function using ASCII code.

I found ASCII code hash function implementation it's easy to build a hash function on the idea of treating each character of the string as a digit in a number. I try to represent a number is to use a radix-10 system with the Arabic numerals.

For example, I could represent numbers using the letters "a" - "z" for the numbers 0 through 25 to obtain the Radix-26 system described in your text book. Characters in the computer are often stored using 7-bit ASCII codes (with values 0-127). So we can treat a string of ASCII characters as a Radix-128 number.

答:
Using ASCII codes of a string is actually not a bad method of hashing a value.

Individual letters are not equally common - e is more common than g, and g is much more common than x, so the buckets would become somewhat unbalanced, but taking a MOD 26 sum over several letters will work much better, because the rare and common letters combine so that all values between 0 and 26 will occur a lot.

The problem is that checking every letter in a string takes a lot of time. That is why production code usually uses mathematical operations like division on carefully selected fields and constants that are already numeric and equidistributed. But for learning to program a hash table, go ahead and use letter codes.


问:
DDD - Business rule that depends on a service
I got confused about if a domain is required to access an external service in some state of it's life cycle.

The business rule is this :

If an Employee is accepting a JobSeeker's JobApplication, then the
  Employee must create an Appointment and have it e-mailed to the
  JobSeeker.

My current solutions are:

1 - Leave the mailing responsibility to the JobApplication domain

```<code>class JobApplication {
    public function makeAppointment(IMailService $mailService, IMailGenerator $mailGen, \DateTime $time, Address $address = null) {
        $employer = $this->getVacancy()->getEmployer();

        $this->accept();

        $appointment = new Appointment($employer,
            $this->applicant,
            'Interview Invitation - '.$employer,
            $time,
            $address ?: $employer->getAddress()
        );

        $mailService->send(
            $appointment->getJobSeeker()->getMail(),
            $appointment->getTitle(),
            $mailGen->generateAppointmentMail($appointment)
        );

        return $appointment;
    }
}
</code>```

I kinda feel awkward about this option, since it leaves the JobApplication entity to depends on the Mailing services.

2 - Create a new AppointmentService

```<code>class AppointmentService {
    private $mailService;
    private $mailGen;

    public function __construct(IMailService $mailService, IMailGenerator $mailGen) {
        $this->mailService = $mailService;
        $this->mailGen = $mailGen;
    }

    public function makeAppointmentFromJobApplication(JobApplication $application, \DateTime $time, Address $address = null) {
        $jobApplication->accept();

        $appointment = new Appointment($application->getCompany(),
            $application->getApplicant(),
            'Interview Invitation - '.$application->getCompany(),
            $time,
            $address ?: $application->getCompany()->getAddress()
        );

        $mailService->send(
            $appointment->getJobSeeker()->getMail(),
            $appointment->getTitle(),
            $mailGen->generateAppointmentMail($appointment)
        );

        return $appointment;
    }
}
</code>```

This option is nice since I only need to inject AppointmentService to the controller, but it leaves the Appointment class anemic.

I once read to never leave your domain to be dependent to domain services, the other way is fine. But some business rules do require services that existed out of the domain scope.

Is there another options?

Update - 1

A third option would be like this:

```<code>class Employer {
    public function acceptApplication(JobApplication $application) {
        if($application->isRejected()) throw new \Exception('Cannot make appointment for rejected application');

        $application->setAccepted();
    }

    public function makeAppointment(IAppointmentService $appointmentService, JobApplication $application, \DateTime $time, Address $address = null) {
        if(!$application->isAccepted()) $this->acceptApplication($application);

        return $appointmentService->makeAppointment($this, $application->getApplicant(), $time, $address ?: $this->getAddress());
    }
}

class AppointmentService {
    private $mailService;
    private $mailGenerator;

    public function makeAppointment(Employer $company, JobSeeker $jobSeeker, \DateTime $time, Address $address = null) {
        $appointment = new Appointment($company,
            $jobSeeker,
            'Interview Invitation - '.$application->getCompany(),
            $time,
            $address
        );

        $this->mailAppointment($appointment);

        return $appointment;
    }

    private function mailAppointment(Appointment $appointment) {
        return $mailService->send($appointment->getJobSeeker, $appointment->getTitle, $mailGenerator->generateApplicationAppointment());
    }
}
</code>```

答:
The rule is not to depend on infrastructure, but instead you can create an interface in terms of the business to communicate with that infrastructure. These are your services.

Sending mail is a business requirement, or service, but how you send mail is up to you. You may want to create your own business-specific mail interface, and one of the implementations of could bridge whatever mail library you are using.

Having said that, given your two options, I think #2 is more correct.

One major point which you've alluded to is to separate data from behaviour. You should be passing data around, and typically services are dependencies rather than business objects being passed around.

However, the current design still feels too focused on the services rather than the business object. Nothing about converting a job application into appointment mentions mail.

This leaves you with something like

```<code>class AppointmentScheduler {
    public function makeAppointmentFromJobApplication(JobApplication $application, \DateTime $time, Address $address = null) {
        $jobApplication->accept();

        return new Appointment($application->getCompany(),
            $application->getApplicant(),
            'Interview Invitation - '.$application->getCompany(),
            $time,
            $address ?: $application->getCompany()->getAddress()
        );
    }
}
</code>```

The next question is, can a $jobApplication really accept itself? Who is accepting it? The applicant? the company?

I'd rather see the company explictly interacting with the application rather than hiding that internally. That's the real interaction that is happening here.

It seems there are a few richer interactions hiding within your code:

a Company accepting a JobApplication

the Company scheduling an Interview

and, as side effects from that:

the Company mailing the Applicant the Invitation

the Application being accepted

Body:
The rule is not to depend on infrastructure, but instead you can create an interface in terms of the business to communicate with that infrastructure. These are your services.

Sending mail is a business requirement, or service, but how you send mail is up to you. You may want to create your own business-specific mail interface, and one of the implementations of could bridge whatever mail library you are using.

Having said that, given your two options, I think #2 is more correct.

One major point which you've alluded to is to separate data from behaviour. You should be passing data around, and typically services are dependencies rather than business objects being passed around.

However, the current design still feels too focused on the services rather than the business object. Nothing about converting a job application into appointment mentions mail.

This leaves you with something like

class AppointmentScheduler {
    public function makeAppointmentFromJobApplication(JobApplication $application, \DateTime $time, Address $address = null) {
        $jobApplication->accept();

        return new Appointment($application->getCompany(),
            $application->getApplicant(),
            'Interview Invitation - '.$application->getCompany(),
            $time,
            $address ?: $application->getCompany()->getAddress()
        );
    }
}

The next question is, can a $jobApplication really accept itself? Who is accepting it? The applicant? the company?

I'd rather see the company explictly interacting with the application rather than hiding that internally. That's the real interaction that is happening here.

It seems there are a few richer interactions hiding within your code:

a Company accepting a JobApplication

the Company scheduling an Interview

and, as side effects from that:

the Company mailing the Applicant the Invitation

the Application being accepted


答:
If you want to build a hash table in Java, you should take advantage of the hashCode and equals methods which every object has, so there is no need to devise a custom hash function. Note that all Java “characters” are already numbers in the range 0x00 – 0xFFFF (they are UTF-16 code units, not ASCII characters or bytes).

Your idea of having the hash code be a Base-26 or Base-128 interpretation is a good idea for alphabetic-only/ASCII-only texts. But there are a few issues I can see:

Strings do not only contain ASCII letters, but also symbols or spaces. Frequently, text will contain Unicode characters which have no ASCII equivalent.

A hash code is an integer. To find a bucket, you'd do buckets.get(hashCode % buckets.size()). However, Java integers hold 32 bits, which offers enough bits for roughly 4.5 ASCII characters. Assuming your implementation left-shifts by seven bits and “or”s the new bits to the current hash code,

```<code>int hashCode = 0;
for (char c : str) {
    hashCode <<= 7;
    hashCode |= c & 0x7F;
}
</code>```

then only the last 5 characters would be significant. This makes it extremely easy to create hash collisions: civilisation and train station.

This can be avoided by a cleverer hash function where any bit will stay somehow significant. E.g the bits in the hash code could be rotated rather than shifted, and new bits could be “xor”ed to the existing value:

```<code>int hashCode = 0;
for (char c : str) {
    // rotate the bits
    hashCode = (hashCode << 1) | (hashCode >> (32 - 1));
    // xor new bits
    hashCode ^= c;
}
</code>```

Java uses a slightly different hash function:

```<code>for (char c : str) {
    hashCode = 31 * hashCode + c;
}
</code>```

The multiplication with 31 makes sure that all bits are eventually used without making any bit irrelevant. Overflow is no problem due to the modulo operation when determining a bucket. The value of 31 is largely unimportant, but it being a prime number avoids hash collisions.

Body:
I want to learn to Design Hash table with simple hash function for better understanding. I understand that the hash table will work as long as the hash function maps each key to a non-negative integer less than the size of the hash table, but it will only perform well if it distributes different keys across different buckets.

My question is : What's a alternative ways to implement hash function using ASCII code.

I found ASCII code hash function implementation it's easy to build a hash function on the idea of treating each character of the string as a digit in a number. I try to represent a number is to use a radix-10 system with the Arabic numerals.

For example, I could represent numbers using the letters "a" - "z" for the numbers 0 through 25 to obtain the Radix-26 system described in your text book. Characters in the computer are often stored using 7-bit ASCII codes (with values 0-127). So we can treat a string of ASCII characters as a Radix-128 number.

Body:
If you want to build a hash table in Java, you should take advantage of the hashCode and equals methods which every object has, so there is no need to devise a custom hash function. Note that all Java “characters” are already numbers in the range 0x00 – 0xFFFF (they are UTF-16 code units, not ASCII characters or bytes).

Your idea of having the hash code be a Base-26 or Base-128 interpretation is a good idea for alphabetic-only/ASCII-only texts. But there are a few issues I can see:

Strings do not only contain ASCII letters, but also symbols or spaces. Frequently, text will contain Unicode characters which have no ASCII equivalent.

A hash code is an integer. To find a bucket, you'd do buckets.get(hashCode % buckets.size()). However, Java integers hold 32 bits, which offers enough bits for roughly 4.5 ASCII characters. Assuming your implementation left-shifts by seven bits and “or”s the new bits to the current hash code,

int hashCode = 0;
for (char c : str) {
    hashCode <<= 7;
    hashCode |= c & 0x7F;
}

then only the last 5 characters would be significant. This makes it extremely easy to create hash collisions: civilisation and train station.

This can be avoided by a cleverer hash function where any bit will stay somehow significant. E.g the bits in the hash code could be rotated rather than shifted, and new bits could be “xor”ed to the existing value:

int hashCode = 0;
for (char c : str) {
    // rotate the bits
    hashCode = (hashCode << 1) | (hashCode >> (32 - 1));
    // xor new bits
    hashCode ^= c;
}

Java uses a slightly different hash function:

for (char c : str) {
    hashCode = 31 * hashCode + c;
}

The multiplication with 31 makes sure that all bits are eventually used without making any bit irrelevant. Overflow is no problem due to the modulo operation when determining a bucket. The value of 31 is largely unimportant, but it being a prime number avoids hash collisions.


问:
What is the right way to parse HTML?
I've heard, that parsing HTML using the Cthulhu way is not very good. But what are the right ways to parse HTML? Or is it possible to parse it at all?</p>

答:
Or is it possible to parse it at all?

Some say it's possible, and that even webbrowsers use this feature to display web pages.

what are the right ways to parse HTML?

Basically you need a parser able to express the idea that an html element can be composed of other html elements.

```<code><div>
  some text
  <div>
    nested element!!
  </div> <!--a regular expression cannot tell if this closes the first or second div-->
</div>
</code>```

This cannot be done with regular expression. But you can do it with more general kinds of parsers.

see https://stackoverflow.com/questions/590747/using-regular-expressions-to-parse-html-why-not

Title: What is the right way to parse HTML?

Body:
Or is it possible to parse it at all?

Some say it's possible, and that even webbrowsers use this feature to display web pages.

what are the right ways to parse HTML?

Basically you need a parser able to express the idea that an html element can be composed of other html elements.

<div>
  some text
  <div>
    nested element!!
  </div> <!--a regular expression cannot tell if this closes the first or second div-->
</div>

This cannot be done with regular expression. But you can do it with more general kinds of parsers.

see https://stackoverflow.com/questions/590747/using-regular-expressions-to-parse-html-why-not


问:
Is there a purely technical term for 'monkey patching'
EDIT The original title of the question was Is there a non-derogatory term for 'monkey patching'. As I have learned that the term is actually not derogatory, or is at least not meant to be, I changed the name to free it from mistaken implications.

I would like to describe a piece of software, and try not to use emotionally biased language. However I am not aware of an unbiased alternative to 'monkey patching'.

The term is meant to be derogatory for a reason. Many see it as a useful but problematic technique.

I am aware of an alternative, but it is equally derogatory: 'duck punching'.

I see 'open classes' not as an alternative name, but as a prerequisite for monkey patching.

'Overriding' does not seem right either. I would like to differentiate between monkey patching and the regular overriding as part of inheritance-based polymorphism.

答:
As someone who was actually working at Zope Corporation (then still called Digital Creations) when the term came into being, I can emphatically state it is very much not derogatory.

The term is a tongue-in-cheek reference to runtime patching (or dynamic patching, if you will).

We talked about sneaking in and altering Python code at runtime; the term Guerrilla Patching was used because sometimes dynamic patches could interfere and conflict. Conflict -> Guerrilla warfare, as the conflict was dynamic and depended on the terrain.

Then someone who had misheard the term and thought it was Gorrilla Patching, had come up with a way to wrap a method and re-use it in their dynamic patch. This meant that even if the method had already been patched, you would not undo that work. Because this was a gentler, more caring form of patching, he used the name Monkey Patch instead. The name stuck as it spread through the wider Python community.

If you feel you cannot use terms like that because they have too many other connotations for you, then so be it.

The technical, colorless and humorless version you are looking for is dynamic runtime patching.


问:
Best practice for projects architecture - server side
The usual way (that I'm familiar with) to divide the server side is the n-layer architecture :

DAL - data access layer, usually has the Entities and the context (and maybe include also a repository)

BLL - business logic layer

Contract - Interfaces

Services - classes which implement the interfaces ( could be a Web API for E.G )

Of course there is also the n-tier Architecture which i don't want to discuss .

lately I've seen more and more a "Modules" architecture and i was wondering about it ( I'm not familiar with the professional term of this architecture )

Where each module is not a table in the database but a group of tables that have a shared concept .

something that looks like that :

Is there any known good architecture that separate the layers by modules on the server side? if so, what is the professional term for this kind of architecture and what are the advantages / disadvantages of each of this architectures ?

答:
Is there any known good architecture that separate the layers by modules on the server
  side?

Modules and layers are two different concepts. Layers are typically used to describe the way code is deployed in a environment. However, Modules is about organizing code according to the functionality. There are other perspectives to modules where it could be based on project need, release order etc. The bottom line is module is a code organization mechanism in a solution layout.

What is the professional term for this kind of architecture and what are the advantages / disadvantages of each of this architectures

I am not aware of a professional term for the code organization shown in the image. However, let me convey what I think on the image. It is a mere code organization technique in a solution. It has very little to do with the architecture. Agreed, code organization is part of architecture. But, not sure if there is nomenclature for that. My opinion on such an code organization would be

The project focuses more on functional organization of code indicating a rich domain. People in team understand domain much better. Thus the team might have found this organization as more natural.

Disadvantage for this type of code organization is many C# projects. Instead of having a project for all contracts and sub folders based on modules, you are having projects for each functionality which are later stiched together.

Another disadvantage I could see is lot of assemblies involved might drag your performance down.

Hope this helps.


问:
Using a relational database vs JSON objects for event/activity data
I am working on a project where I am trying to decide between using a standard SQL relational database or JSON objects to store data about an event or activity.

The project will store data on multiple event types so I have decided to just describe one event type for this question.

The live music event (described in full using the JSON schema at the bottom of this question) is an object that stores data such as where the event will take place, the time/date of the event and the cost of the event. The live music event object has both one-to-one (event--> name, event --> description) and one-to-many (event--> venues, event--> dates, event--> ticket types) relationships. Furthermore, the event object can contain one or more performer IDs, which link to the performer object. The performer object stores data on musicians who are performing at the live music event.

The data will be queried by users using both simple ("Find me events with 'x' name") and complex ("Find me events with 'x' music genre and 'y' cost within a radius of 'z' from my current location") queries. The data will be submitted by users using a web form.

As you can probably tell from the defined JSON schema, I was originally going to use JSON objects to store this data but I've heard from some people who say that because my data is purely relational, I should stick to the older methods.

I would appreciate any thoughts on the pros and cons of each approach given my needs. If you need anything clarified, please feel free to ask.

```<code>{
    "event": {
        "eventID":{
            "type":"string"
        },
        "eventType":{
            "type":"array",
            "eventTypeItem":{
                "type":"string"
            }
        },
        "eventName":{
            "type":"string"
        },
        "eventDescription":{
            "type":"string"
        },
        "eventVenueList":{
            "type":"array",
            "eventVenueListID":{
                "type":"integer"
            }
        },
        "eventURL":{
            "type":"string"
        },
        "eventTwitter":{
            "type":"string"
        },
        "eventFB":{
            "type":"string"
        },
        "eventInstagram":{
            "type":"string"
        },
        "eventEmail":{
            "type":"string",
            "format":"email"
        },
        "eventContactPerson":{
            "type":"string"
        },
        "eventDoorTime": {
            "type":"string",
            "format":"date-time"
        },
        "eventPerformerIDList":{
            "type":"array",
            "liveMusicPerformerID":{
                "type":"integer"
            }
        },
        "eventSetList":{
            "type":"array",
            "eventPerformerID":{
                "type":"integer"
            },
            "eventPerformerStartTime":{
                "type":"string",
                "format":"date-time"
            },
            "eventPerformerEndTime":{
                "type":"string",
                "format":"date-time"
            }
        },
        "eventDateList": {
            "type":"array",
            "eventDateItem": {
                "type":"string",
                "format":"date-time"
            }
        },
        "eventDateStartTime": {
            "type":"string",
            "format":"date-time"
        },
        "eventDateEndTime": {
            "type":"string",
            "format":"date-time"
        },
        "eventTicket":{
            "type":"array",
            "eventTicketType":{
                "type":"string"
            },
            "eventTicketLowPrice":{
                "type":"number"
            },
            "eventTicketHighPrice":{
                "type":"number"
            },
            "eventDatesAdvancePrice": {
                "type":"number"
            }
        }
    },
    "performer": {
        "performerID": {
            "type":"integer"
        },
        "performerType": {
            "type":"string"
        },
        "performerName": {
            "type":"string"
        },
        "performerAlternateName": {
            "type":"array",
            "performerAlterateNameItem":{
                "type":"string"
            }
        },
        "performerGenreList": {
            "type":"array",
            "performerGenreItem":{
                "type":"string"
            }
        },
        "performerURL": {
            "type":"string"
        }
    }
}
</code>```

答:
In most applications there are requirements to

Input data, perform some processing, save the data,retrieve the data and query the data. There may also be a requirement to generate reports on the data.

Exchange data between different parts of the system or with external systems

In order to achieve the requirements for Item 1 a method of persisting data is required. Typically if the volume of data is very small and the type of data is simple and does not require extensive search capabilities then a simple file structure may be used. As data becomes more complex a XML (or even JSON) structure may be used with the data still stored in files. Searching though becomes more problematic. As the volume of data increases and the complexity of searches increases a database is normally selected which provides industry standard methods for data persistence, querying etc. The databases can designed to handle large volumes of data and store,retrieve and search the data quickly and efficiently.

In order to achieve the requirements for Item 2 there are various different methods for allowing data interchange between systems including XML, JSON etc.

These methods allow the data structure to be defined by a user and are language independent allowing dissimilar system to exchange data.

In your particular case you are correctly using JSON is describing a set of music events.
While you could store the data in JSON format searching this data as the number of music events grows will be slow and inefficient.

Using a separation of concerns approach then better approach is to collect the data, store in a database, perform your query based on user input in the database and then return the results in JSON format to the Client side to display the data.

An additional problem with the JSON approach is a changing data structure. Currently your structure is relatively simple. You may use this structure for several months and then an additional field is identified. What do you then do with all of your existing JSON objects ? Updating these would be problematic.

If you used a database then adding an additional field is relatively simple and only your code to generate the JSON would need to be modified in a single place thus giving you all new JSON with the new field.

In short use each piece of technology for what it was designed for JSON for data interchange and a Database for data persistence.