问:
Are NoSQL databases the best choice for more efficiently querying large amounts of data?
We are planning to build a travel website in which we will be integrating multiple APIs (eg. DOTW, GTA, Expedia) for Hotels. I have initially tried to use MySQL but since there are huge amounts of data in hotels and it may contain numerous "one to many" relationships with Images, Amenities and Rooms, the search becomes very slow when we have data for around 200000 Hotels. Even fetching all details for just one hotel may results in a JOIN query from at least four tables, and scanning over all hotels records. So we are planning to migrate our product schema to any NoSQL database to make our search as fast as possible.

Also sometimes we need to run certain schedulers on our database for eliminating duplicates from our database and also updating the newly added hotels which are sent by our providers.

Our tech stack is basically on Java, J2EE along with Springs and Hibernate.

I have read about about MongoDB, Cassandra, Redis and ElasticSearch but I am now confused if simply using these tools can optimize the website search performance.  If so then what features differ between these tools that could help me make a determination?

答:
I think that your search results can greatly improve through a number of techniques or database design approaches that will improve performance in your typical RDBMS.  I suggest looking into and possibly prototyping the following improvements to see if they help you in performance testing first before you commit to an entirely new database technology that will require a great deal of new learning and experience to master.

Essentially you want to avoid the mindset of a "Magic Bullet".  There is a misconception that NoSQL can somehow magically solve all of our problems and performance issues with the RDBMS and that might be true sometimes but you really should try improving your database design first.

Identify your Non-Functional Requirements

Specifically identify your acceptable non-functional requirements for performance.  Determine what the maximum average query wait time and use that as your goal.  If you can tweak your database design to achieve this then you do not need to rearchitect your software to a NonSQL solution.

Avoid binary columns

It sounds like with the Image table that you have binary type media being stored within your database tables.  While this is highly dependent on your chosen database implements binary columns, it is generally accepted that binary columns can hurt the performance of your queries.  Binary columns typically invalidate the benefits that an index on a table column can provide.  If you don't believe me, join to the Image table and run an explain plan and notice how the index is probably not being used.

Use a Content Delivery Network

Instead of storing images and media in database records, store a URL that an application can use to retrieve that image, maybe in a browser.  That URL can point to a unique image that is being stored and managed in a Content Delivery Network.  There are a number of cloud services that can provide this or you can build your own with a number of tools.  This should make all aspects of your application much more efficient.

Evaluate your table indexes

Make sure that if you are not using indexes that you build them for columns that you typically filter on or join against.  To be honest, 4 tables is not a great deal of joins for a table so if you follow these guidelines you should see at least a modest improvement of performance.

If you follow these guidelines and you still cannot achieve your performance requirements then perhaps you can evaluate various NoSQL solutions and look for features that might help you.


答:
NoSQL is generally not very good with relational data. NoSQL is often great for non-relational but structured data like documents or time series.

Your "one to many" relationships may look quite like a document: e.g a "hotel" document may carry all its images, room info, etc stored together and fetched with one operation.

On the other hand, if you see a need for an SQL join, do not hesitate and use an SQL database. These are damn efficient with joins, and are quite good at pulling large amounts of data in one query.

WRT "searches become very slow", it's hard to tell what happened without seeing your DB structure first. Usually adding a relevant (or dropping an irrelevant) index can speed things up. Reworking the schema to make the few most important queries efficient is also known to work.

I don't think that NoSQL will help you at search too much — at least, not before I could see the types of searches you're going to run.

ContentLicense: CC BY-SA 3.0

Title: Are NoSQL databases the best choice for more efficiently querying large amounts of data?

Body:
We are planning to build a travel website in which we will be integrating multiple APIs (eg. DOTW, GTA, Expedia) for Hotels. I have initially tried to use MySQL but since there are huge amounts of data in hotels and it may contain numerous "one to many" relationships with Images, Amenities and Rooms, the search becomes very slow when we have data for around 200000 Hotels. Even fetching all details for just one hotel may results in a JOIN query from at least four tables, and scanning over all hotels records. So we are planning to migrate our product schema to any NoSQL database to make our search as fast as possible.

Also sometimes we need to run certain schedulers on our database for eliminating duplicates from our database and also updating the newly added hotels which are sent by our providers.

Our tech stack is basically on Java, J2EE along with Springs and Hibernate.

I have read about about MongoDB, Cassandra, Redis and ElasticSearch but I am now confused if simply using these tools can optimize the website search performance.  If so then what features differ between these tools that could help me make a determination?


问:
Why don't all UI Control methods RunOnUIThread
In both .NET and in Android and I'm sure other frameworks I've noticed this issue where you end up with a task that takes too long and so holds up the UI thread.

Say you have a method that updates a label with text from a network location/internet and comes back again after 3-4 seconds and sets the label appropriately.  That holds up the UI thread.
So your first port of call then is to move the method call to a different thread.
Only that doesn't just work... because you can no longer update the text of label since that can only be done in the UI thread....

So then the language provides something along the lines of

```<code>      runOnUiThread(() -> {
       label.setText(myNewFoundInformationFrom);
});
</code>```

That example is from Android using lambda's and is no doubt a massive improvement on what we might have used 10 years ago...

Maybe further down the line you find yourself doing this from various different places... so you might create a method

```<code>void setLabelText(string newText)
 runOnUiThread(() -> {
    label.setText(newText);
    });
</code>```

and at least in the case of Android... this works no matter which thread I run it from.

So this makes me wonder...  Why don't Microsoft/Google and all make it so that all update methods/functions to UI controls already make sure that they're running from the UI thread in this way - so that we don't have to?

答:
When you want to change just one label, there is not problem with the solution you have suggested. There are, however, at least two scenarios, in what this makes sense:

Synchronization. Say, you want to update a button text and enable/disable it. With runOnUiThread, there is no need for explicit synchronization or locking.

Bulk update. If you are updating many items, then calling runOnUiThread for every one item would hurt the performance. (Well, if there is horrible amount of items, you should divide them in several batches.)


问:
One-line functions that are called only once
Consider a parameterless (edit: not necessarily) function that performs a single line of code, and is called only once in the program (though it is not impossible that it'll be needed again in the future).

It could perform a query, check some values, do something involving regex... anything obscure or "hacky".

The rationale behind this would be to avoid hardly-readable evaluations:

if (getCondition()) {
    // do stuff
}
```

where getCondition() is the one-line function.

My question is simply: is this a good practice? It seems alright to me but I don't know about the long term...

答:
There are already a lot of good answers, but there is a special case worth mentioning.

If your one-line statement needs a comment, and you are able to clearly identify (which means: name) its purpose, consider extracting a function while enhancing the comment into API doc. This way you make the function call easier faster and to understand.

Interestingly, the same can be done if there is currently nothing to do, but a comment reminding of expansions needed (in the very near future1)), so this,

def sophisticatedHello():
    # todo set up
    say("hello")
    # todo tear down
```

<p>could as well changed into this</p>

<pre class="lang-py prettyprint-override"><code>def sophisticatedHello():
    setUp()
    say("hello")
    tearDown()
</code>```

1) you should be really sure about this (see YAGNI principle)

Body:
There are already a lot of good answers, but there is a special case worth mentioning.

If your one-line statement needs a comment, and you are able to clearly identify (which means: name) its purpose, consider extracting a function while enhancing the comment into API doc. This way you make the function call easier faster and to understand.

Interestingly, the same can be done if there is currently nothing to do, but a comment reminding of expansions needed (in the very near future1)), so this,

def sophisticatedHello():
    # todo set up
    say("hello")
    # todo tear down

could as well changed into this

def sophisticatedHello():
    setUp()
    say("hello")
    tearDown()

1) you should be really sure about this (see YAGNI principle)


问:
Identifying user of a webapp
For a small webapp I want to be able to identify a user.

The issue is, if the user cheats in some manner, I want to be able
to forbid him the usage of my application.

I already have done extensive research on that topic, but to no avail.

What is not an option:

cookies: can be disabled or deleted (to easily overridable)

ip adress: is dynamic or hidden through NAT

MAC adress: cannot be retrieved (as far as I know, or at least not without terrifying the user)

Flash: is not supported on a wide range of devices

This is a central part, so I can decide which technology to use along
this decision.

What are the options I have? (especially I do not want that the user gets a security warning as this is often the case with java applets)

Some kind of unique machine identifier would be okay.

-edit-

What I want to protect against:

It should be some kind of discussion board about recent topics.
There will be people that proof that they have not the attitude to discuss in the public, e.g. insult other people etc.

And I want to have a possibility to keep these people away.

There will be somekind of login. But what keeps people from creating simply another account and keep going?

Fingerprinting seems to be to weak, as is has some well known flaws. Using a bank account is way to hard to use, at least since there is nothing you can buy right now, it will keep users from using the site.

Isn't there something in the middle? Like a device id, which keeps users from one device away, despite it might be wrong, this would do the job in a vast majority of cases I believe.

答: Maybe you can add some benefits for long-term user or disadvantages for new users like more strict rate limiting or CAPTCHA. You can also use a reputation system. One can create a new account if banned, but without all the advantages of long-term user.</p>

Title: Identifying user of a webapp


问:
What is abstraction?
Is there a generally agreed upon definition for what a programming abstraction is, as used by programmers? [Note, programming abstraction is not to be confused with dictionary definitions for the word "abstraction."] Is there an unambiguous, or even mathematical definition? What are some clear examples of abstractions?

答:
This is something I actually wanted to blog about for a longer time, but I never got to it. Luckily, I am a rep zombie and there's even a bounty. My post turned out rather lengthy, but here's the essence:

Abstraction in programming is about
  understanding the essence of an object
  within a given context.

[...]

Abstraction is not only mistaken with
  generalization, but also with
  encapsulation, but these are the two
  orthogonal parts of information
  hiding: The service module decides
  what it is willing to show and the
  client module decides what it is
  willing to see. Encapsulation is the
  first part and abstraction the latter.
  Only both together constitute full
  information hiding.

Hope that helps.

Title: What is abstraction?

ContentLicense: CC BY-SA 2.5


问:
Should I create a single object for a common method call or use a throw away approach?
I'm creating a little rpg fight program just for fun and to practice my java (I'm pretty new hehe).

I have a class called Dice with a method called d20 that rolls a random number between 1 and 20. The method will be used frequently by all other classes in the program.

My question is, should I create a single instance of the Dice class in my main method that can be called by all the other classes too. Does that work? Does it need to be declared as a public reference variable to work? Is this just a poor practice?

Should I be making the method static instead so that I don't need to make an instance of the object at all?

Or should I create the object when the call is to be made and then throw it away afterwards using garbage collection?

I'm not sure the first way even works. The latter two I don't know which is good practice.

My main motivation here is to understand what the best practice is and why.

答:
Have any class that requires a random number source accept a Function<Integer, Integer> (or any equivalent functional interface you like) in its constructor.

Create a static method int rollDie(int sides) that generates a random number from 0 to sides, inclusive. This avoids the redundancy of rollD20, rollD8, etc. Interally this'll probably just be a call to Random.nextInt(sides + 1).

You can pass the static method to any class that needs it using a method reference:

```<code>new Character(Dice::rollDie)
</code>```

For unit testing, you can easily replace rollDie with a predictable function:

```<code>new Character(sides -> 5);
</code>```

This is equivalent to valenterry's approach but with less boilerplate and possibly more efficient, if the compiler/virtual machine can make use of the fact that the lambda refers to a static method. It's also a bit easier to reuse, since rollDie works with any interface containing one method that takes an Integer and returns an Integer, so you can use it in other contexts as well.

Body:
Have any class that requires a random number source accept a Function<Integer, Integer> (or any equivalent functional interface you like) in its constructor.

Create a static method int rollDie(int sides) that generates a random number from 0 to sides, inclusive. This avoids the redundancy of rollD20, rollD8, etc. Interally this'll probably just be a call to Random.nextInt(sides + 1).

You can pass the static method to any class that needs it using a method reference:

new Character(Dice::rollDie)

For unit testing, you can easily replace rollDie with a predictable function:

new Character(sides -> 5);

This is equivalent to valenterry's approach but with less boilerplate and possibly more efficient, if the compiler/virtual machine can make use of the fact that the lambda refers to a static method. It's also a bit easier to reuse, since rollDie works with any interface containing one method that takes an Integer and returns an Integer, so you can use it in other contexts as well.


问:
Scoping template variables in "has-a" (compositional) relationships
I'm developing a new templating language for PHP, and one of the features is an object-oriented approach to nested child templates.  For example, I can declare an object of type HtmlBuilder like this:

```<code>$template = "
  <div>
    <h1>{{field1}}</h1>
    <p>{{field2}}</p>
  </div>";

$content = [
   "field1" => "value1",
   "field2" => "value2"
];

$hb = new HtmlBuilder($content, $template);
echo $hb->render();
</code>```

In this case, HtmlBuilder does a simple find-and-replace on the fields.  But, I could also nest one HtmlBuilder (or one of its more specialized subtypes) inside of another:

```<code>// Child template
$template1 = "
  <p>{{field2}}</p>
  <p>{{field4}}</p>
  ";

$content1 = [
   "field4" => "something else"
];

$hb1 = new HtmlBuilder($content1, $template1);

// Parent template
$template2 = "
  <div>
    <h1>{{field1}}</h1>
    {{field3}}
  </div>";

$content2 = [
   "field1" => "value1",
   "field2" => "value2",
   "field3" => $hb1
];

$hb2 = new HtmlBuilder($content2, $template2);
echo $hb2->render();
</code>```

In this case, when $hb2 is rendered, $hb1 will be automatically rendered in the field3 placeholder.

My question is, does it make sense to design this system such that the value of field2 is automatically passed in from the parent template to the child template (while allowing it to be overridden in the child)?  Or, should I require that it be explicitly passed in $content1?

答:
Implicit dependencies are bad, especially if your template engine will not complain about missing variables. I believe that it would be beneficial for each template fragment to know which variables it needs, and to refuse to be rendered or instantiated with wrong arguments.

Here is an example where the lack of scoping will introduce difficulties:

```<code>$academic_staff_template = "
  <div>
    <h4>{{ title }} {{ name }}</h4>
    {{ bio }}
  </div>
";
$lecturer = new HtmlBuilder([], $academic_staff_template);

$lecture_template = "
  <html>
    <head>
      <title>{{ title }}</title>
    </head>
    <body>
      <h1>Lecture {{ title }}</h1>
      {{ description }}
      {{ lecturer }}
    </body>
  </html>
";
$vars = [
  "title" => "Archaeology 101",
  "description" => "...",
  "lecturer" => $lecturer,
  "name" => 'Henry Walton "Indiana" Jones, Jr.',
  "title" => "Dr.",
  "bio" => "...",
];
$lecture = new HtmlBuilder($vars, $lexture_template);
</code>```

Both template use a title variable, but use the same name to mean something completely different. Your current design would produce this rendered output:

```<code><html>
  <head>
    <title>Dr.</title>
  </head>
  <body>
    <h1>Lecture Dr.</h1>
    ...
    <div>
      <h4>Henry Walton "Indiana" Jones, Jr.</h4>
      ...
    </div>
  </body>
</html>
</code>```

Sometimes, it is extremely useful to include another template without entering a new variable scope. For example, {% include "snippet/footer" %} could be a useful directive to load a snippet. But if we try to create encapsulated, loosely coupled templates, that's running straight into namespace clashes and all kinds of issues.

Here's an idea: When you parse a template, you take note of all variables that are required. Such a parsed template can be rendered in one of two ways:

Via the API: $result = $engine->parse($source)->render(["var1" => "value1"]). The render method will throw an exception if not all necessary variables are provided.

Inside the template language: If block is bound to a parsed template object, then syntax like {{ block var1: "value" var2: someVariable }} could render the template. No variables except those passed explicitly would be available inside the block. If the given arguments don't match the arguments required by the block, an error would be thrown.

Since some data naturally belongs together, it would be great to offer access to arrays within your template language. Then we could pass a single dictionary with info about the lecturer to the academic staff template. Here is how I'd design that interface:

```<code>$lecturer_template = $engine->parse("
  <div>
    <h4>{{ person.title }} {{ person.name }}</h4>
    {{ person.bio }}
  </div>
");
$page_template = $engine->parse("
  <html>
    <head>
      <title>{{ course.title }}</title>
    </head>
    <body>
      <h1>Lecture {{ course.title }}</h1>
      {{ course.description }}
      {{ lecturer person: course.lecturer }}
    </body>
  </html>
");

$course = [
  "title" => "Archaeology 101",
  "description" => "...",
  "lecturer" => [
    "name" => "Henry Walton \"Indiana\" Jones, Jr.",
    "title" => "Dr.",
    "bio" => "...",
  ],
];

$result = $page_template->render(["course" => $course, "lecturer" => $lecturer_template]);
</code>```

Body:
Implicit dependencies are bad, especially if your template engine will not complain about missing variables. I believe that it would be beneficial for each template fragment to know which variables it needs, and to refuse to be rendered or instantiated with wrong arguments.

Here is an example where the lack of scoping will introduce difficulties:

$academic_staff_template = "
  <div>
    <h4>{{ title }} {{ name }}</h4>
    {{ bio }}
  </div>
";
$lecturer = new HtmlBuilder([], $academic_staff_template);

$lecture_template = "
  <html>
    <head>
      <title>{{ title }}</title>
    </head>
    <body>
      <h1>Lecture {{ title }}</h1>
      {{ description }}
      {{ lecturer }}
    </body>
  </html>
";
$vars = [
  "title" => "Archaeology 101",
  "description" => "...",
  "lecturer" => $lecturer,
  "name" => 'Henry Walton "Indiana" Jones, Jr.',
  "title" => "Dr.",
  "bio" => "...",
];
$lecture = new HtmlBuilder($vars, $lexture_template);

Both template use a title variable, but use the same name to mean something completely different. Your current design would produce this rendered output:

<html>
  <head>
    <title>Dr.</title>
  </head>
  <body>
    <h1>Lecture Dr.</h1>
    ...
    <div>
      <h4>Henry Walton "Indiana" Jones, Jr.</h4>
      ...
    </div>
  </body>
</html>

Sometimes, it is extremely useful to include another template without entering a new variable scope. For example, {% include "snippet/footer" %} could be a useful directive to load a snippet. But if we try to create encapsulated, loosely coupled templates, that's running straight into namespace clashes and all kinds of issues.

Here's an idea: When you parse a template, you take note of all variables that are required. Such a parsed template can be rendered in one of two ways:

Via the API: $result = $engine->parse($source)->render(["var1" => "value1"]). The render method will throw an exception if not all necessary variables are provided.

Inside the template language: If block is bound to a parsed template object, then syntax like {{ block var1: "value" var2: someVariable }} could render the template. No variables except those passed explicitly would be available inside the block. If the given arguments don't match the arguments required by the block, an error would be thrown.

Since some data naturally belongs together, it would be great to offer access to arrays within your template language. Then we could pass a single dictionary with info about the lecturer to the academic staff template. Here is how I'd design that interface:

$lecturer_template = $engine->parse("
  <div>
    <h4>{{ person.title }} {{ person.name }}</h4>
    {{ person.bio }}
  </div>
");
$page_template = $engine->parse("
  <html>
    <head>
      <title>{{ course.title }}</title>
    </head>
    <body>
      <h1>Lecture {{ course.title }}</h1>
      {{ course.description }}
      {{ lecturer person: course.lecturer }}
    </body>
  </html>
");

$course = [
  "title" => "Archaeology 101",
  "description" => "...",
  "lecturer" => [
    "name" => "Henry Walton \"Indiana\" Jones, Jr.",
    "title" => "Dr.",
    "bio" => "...",
  ],
];

$result = $page_template->render(["course" => $course, "lecturer" => $lecturer_template]);


答:
Why either/or?

I've worked very successfully with a hybrid approach, using a relational db (SQL Server, but pick your favourite) to hold data that needs a relational structure - most of this is IDs linking all the various domain objects, very little textual data and certainly no blobs - and a nosql db (Dynamo) to hold large relatively unstructured data, typically JSON documents picked up from third party sources. Obviously coding is more complex but it enables you to get the best of both worlds.

Of course it may be that a pure approach is ultimately best for you, but the hybrid may also help out in step-by-step refactoring.


答:
Even fetching all details for just one hotel may results in a JOIN
  query from at least four tables, and scanning over all hotels records.

A four-join query is absolutely trivial if you have the appropriate indexes for all joins.

The second part of this question is far more troubling.  Why the scan over all records?  Is is because of missing indexes? or do you need some aggregate data?  maybe compare to an average, give a ranking index, something like that?  If so, switching to NoSQL won't help; what you need is to precalculate those aggregates so you can derive the data for each hotel quickly.


问:
How to structure a loop that repeats until success and handles failures
I am a self-taught programmer. I started programming about 1.5 years ago. Now I have started to have programming classes in school. We have had programming classes for 1/2 year and will have another 1/2 right now.

In the classes we are learning to program in C++ (which is a language that I already knew to use quite well before we started).

I have not had any difficulties during this class but there is one recurring problem that I have not been able to find a clear solution to.

The problem is like this (in Pseudocode):

```<code> do something
 if something failed:
     handle the error
     try something (line 1) again
 else:
     we are done!
</code>```

Here is an example in C++

The code prompts the user to input a number and does so until the input is valid. It uses cin.fail() to check if the input is invalid. When cin.fail() is true I have to call cin.clear() and cin.ignore() to be able to continue to get input from the stream.

I am aware that this code does not check of EOF. The programs we have written are
  not expected to do that.

Here is how I wrote the code in one of my assignments in school:

```<code>for (;;) {
    cout << ": ";
    cin >> input;
    if (cin.fail()) {
        cin.clear();
        cin.ignore(512, '\n');
        continue;
    }
    break;
}
</code>```

My teacher said was that I should not be using break and continue like this. He suggested that I should use a regular while or do ... while loop instead.

It seems to me that using break and continue is the simplest way to represent this kind of loop. I actually thought about it for quite a while but did not really come up with a clearer solution.

I think that he wanted me to do something like this:

```<code>do {
    cout << ": ";
    cin >> input;
    bool fail = cin.fail();
    if (fail) {
        cin.clear();
        cin.ignore(512, '\n');
    }
} while (fail);
</code>```

To me this version seems alot more complex since now we also have variable called fail to keep track of and the check for input failure is done twice instead of just once.

I also figured that I can write the code like this (abusing short circuit evaluation):

```<code>do {
    cout << ": ";
    cin >> input;
    if (fail) {
        cin.clear();
        cin.ignore(512, '\n');
    }
} while (cin.fail() && (cin.clear(), cin.ignore(512, '\n', true);
</code>```

This version works exactly like the other ones. It does not use break or continue and the cin.fail() test is only done once. It does however not seem right to me to abuse the "short circuit evaluation rule" like this. I do not think my teacher would like it either.

This problem does not only apply to just cin.fail() checking. I have used break and continue like this for many other cases that involve repeating a set of code until a condition is met where something also has to be done if the condition is not met (like calling cin.clear() and cin.ignore(...) from the cin.fail() example).

I have kept using break and continue throughout the course and now my teacher has now stopped complaining about it.

What are your opinions about this?

Do you think my teacher is right?

Do you know a better way to represent this kind of problem?

答:
What you have to strive for is avoiding raw loops.

Move the complex logic into a helper function and suddenly things are a lot clearer:

```<code>bool getValidUserInput(string & input)
{
    cout << ": ";
    cin >> input;
    if (cin.fail()) {
        cin.clear();
        cin.ignore(512, '\n');
        return false;
    }
    return true;
}

int main() {
    string input;
    while (!getValidUserInput(input)) {
        // We wait for a valid user input...
    }
}
</code>```

Body:
What you have to strive for is avoiding raw loops.

Move the complex logic into a helper function and suddenly things are a lot clearer:

bool getValidUserInput(string & input)
{
    cout << ": ";
    cin >> input;
    if (cin.fail()) {
        cin.clear();
        cin.ignore(512, '\n');
        return false;
    }
    return true;
}

int main() {
    string input;
    while (!getValidUserInput(input)) {
        // We wait for a valid user input...
    }
}


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答:
My brother and I were working on a multimedia heavy-website for a very famous rock star many years ago.

When the client saw the site he noticed some compression artifacts on some of the JPEGs and asked what was wrong with them. We explained that images need compression for bandwidth purposes and that the images were currently compressed at about 80% quality. He was offended and said something to the effect of

I haven't gotten to where I am today
  by doing things at 80%, set it to
  100%.

We tried to explain how it would affect users, but he would have none of it. It resulted in the slowest "virtual world" website ever. This actually happened.


答:
to me, the most straight forward C translation of the pseudocode is

```<code>do
    {
    success = something();
    if (success == FALSE)
        {
        handle_the_error();
        }
    } while (success == FALSE)
\\ moving on ...
</code>```

i don't get why this obvious translation is a problem.

perhaps this:

```<code>while (!something())
    {
    handle_the_error();
    }
</code>```

that looks simpler.

Title: How to structure a loop that repeats until success and handles failures

Body:
I am a self-taught programmer. I started programming about 1.5 years ago. Now I have started to have programming classes in school. We have had programming classes for 1/2 year and will have another 1/2 right now.

In the classes we are learning to program in C++ (which is a language that I already knew to use quite well before we started).

I have not had any difficulties during this class but there is one recurring problem that I have not been able to find a clear solution to.

The problem is like this (in Pseudocode):

```<code> do something
 if something failed:
     handle the error
     try something (line 1) again
 else:
     we are done!
</code>```

Here is an example in C++

The code prompts the user to input a number and does so until the input is valid. It uses cin.fail() to check if the input is invalid. When cin.fail() is true I have to call cin.clear() and cin.ignore() to be able to continue to get input from the stream.

I am aware that this code does not check of EOF. The programs we have written are
  not expected to do that.

Here is how I wrote the code in one of my assignments in school:

```<code>for (;;) {
    cout << ": ";
    cin >> input;
    if (cin.fail()) {
        cin.clear();
        cin.ignore(512, '\n');
        continue;
    }
    break;
}
</code>```

My teacher said was that I should not be using break and continue like this. He suggested that I should use a regular while or do ... while loop instead.

It seems to me that using break and continue is the simplest way to represent this kind of loop. I actually thought about it for quite a while but did not really come up with a clearer solution.

I think that he wanted me to do something like this:

```<code>do {
    cout << ": ";
    cin >> input;
    bool fail = cin.fail();
    if (fail) {
        cin.clear();
        cin.ignore(512, '\n');
    }
} while (fail);
</code>```

To me this version seems alot more complex since now we also have variable called fail to keep track of and the check for input failure is done twice instead of just once.

I also figured that I can write the code like this (abusing short circuit evaluation):

```<code>do {
    cout << ": ";
    cin >> input;
    if (fail) {
        cin.clear();
        cin.ignore(512, '\n');
    }
} while (cin.fail() && (cin.clear(), cin.ignore(512, '\n', true);
</code>```

This version works exactly like the other ones. It does not use break or continue and the cin.fail() test is only done once. It does however not seem right to me to abuse the "short circuit evaluation rule" like this. I do not think my teacher would like it either.

This problem does not only apply to just cin.fail() checking. I have used break and continue like this for many other cases that involve repeating a set of code until a condition is met where something also has to be done if the condition is not met (like calling cin.clear() and cin.ignore(...) from the cin.fail() example).

I have kept using break and continue throughout the course and now my teacher has now stopped complaining about it.

What are your opinions about this?

Do you think my teacher is right?

Do you know a better way to represent this kind of problem?

Body:
to me, the most straight forward C translation of the pseudocode is

do
    {
    success = something();
    if (success == FALSE)
        {
        handle_the_error();
        }
    } while (success == FALSE)
\\ moving on ...

i don't get why this obvious translation is a problem.

perhaps this:

while (!something())
    {
    handle_the_error();
    }

that looks simpler.


问:
If using a VM as a development environment, should tooling live inside the VM or on the host?
There are a couple of questions already here for whether or not a VM should be used as a development environment. I don't wish to answer that question here but I'm assuming that a VM should be used as a development environment.

My question here is on guidelines for which tools should exist in the VM and which should exist on the host.

For example, I would generally use a VM in a headless mode for development as a Virtual GUI often means a lag. This would restrict the use of a text editor to either be a command line tool such as VIM or for a GUI text editor such as sublime text to be run in the host with a shared directory.

This then leads on to code generation (scaffolding) tools such as Yeoman's yo. What would be the benefit this inside a VM?

I'd like to know some general guidelines so that I can have a useful developer workflow.

答:
Here is what I do:

We have a VM for every component of our software, plus one that contains a SVN server which does version control for the code. I usually export a copy of the code from SVN on to my local machine, which is Windows and has better IDEs than Vim or Emacs (I use Eclipse). By exporting it, it is no longer in version control, so it is completely external to SVN. Our process here is that we don't commit any changes unless we are absolutely sure it works.

I develop on my local machine, then do an sftp on the changed files to the VM, which will run and test the code. Rinse, repeat until whatever I am doing is finished. Then, pull the repository from SVN into my Eclipse using Subclipse, make the changes that I know for sure are working, then commit.

Finally, have a VM that you use to do system testing, to make sure your changes work.

To answer your question: All tooling should live inside the VM. All you do on your local box is write code. At least, that's that I do.

Surprisingly, this is very similar to having a non-VM environment where each server hosts a big component of the software. The tradeoff of the VM "lag" is that you save a lot of rack space. I once redesigned a development lab and cut 5 full server racks into one half rack just by using VM. It saved a ton of cash.


问:
Class Table Inheritance: do child tables need a primary key?
I'm using the Class Table Inheritance architecture with my application and have read Fowler.  When mapping my database tables to classes in code, I've realized I have no need for an "ID" property on my derived classes, and, in fact, it can cause issues if it has the same name because it hides the base class property.

Do my child tables need to have their own surrogate primary keys, or should the foreign keys relating them to their parent record also serve as the primary key for the child records?  Fowler doesn't get that specific on CTI.  I'm used to always having surrogate keys, so a departure from this convention doesn't feel quite right and if there is a good reason to stick to it, I'll take it.

答:
Yes in general when using Table per Class Inheritance, the derived table has the same primary key as the base table.

I personally prefer table per-hierarchy when possible because it doesn't require an extra join. It does create unused columns in the table which might be cumbersome with large hierarchies, but many modern databases support this scenario adequately (e.g. SQL Server as of 2008 has support for a Sparse Column indicator that lets the DB optimize storage accordingly)


答:
I would say you should initialize just one d20 object for your application.

The inspiration for this style is that a real life DM only has one D20. He doesn't have a whole box where he pulls one out, rolls it, and throws it away.

You should not assign a dice property to your RPG characters simply because RPG characters don't roll dice, the dungeonmaster does.

Therefore a static method like GetD20Roll():Number is the most clear. It does not suggest the monster itself is rolling dice.

Title: Should I create a single object for a common method call or use a throw away approach?

Body:
I'm creating a little rpg fight program just for fun and to practice my java (I'm pretty new hehe).

I have a class called Dice with a method called d20 that rolls a random number between 1 and 20. The method will be used frequently by all other classes in the program.

My question is, should I create a single instance of the Dice class in my main method that can be called by all the other classes too. Does that work? Does it need to be declared as a public reference variable to work? Is this just a poor practice?

Should I be making the method static instead so that I don't need to make an instance of the object at all?

Or should I create the object when the call is to be made and then throw it away afterwards using garbage collection?

I'm not sure the first way even works. The latter two I don't know which is good practice.

My main motivation here is to understand what the best practice is and why.


问:
What differences are between "play-by-play", design and implementation of an OS?
From two books' review

Daniel Bovet and Marco Cesati. Understanding the Linux Kernel (2nd Edition or newer):

Note: this book has some tendency to function as a play-by-play of
  what happens inside Linux (on an x86) as opposed to a design book.
  You may find the BSD book or the Love book more design-oriented.

Robert Love. Linux Kernel Development:

We received some complaints about the 2003 edition containing too much
  play-by-play material, but the 2005 edition has received favorable student reviews. You may find that the BSD book provides more
  historical and design perspective. You should also know that
  people familiar with other operating systems may dispute some
  historical descriptions and claims of architectural novelty.

What differences are between "play-by-play", design and implementation of an OS?
 For example, how do they differ in terms of what they consider and what they want to accomplish?

What do "play-by-play", design and implementation of an OS mean? I don't know what "play-by-play" mean here. Does "design" mean creating a logical/abstract model, and does implementation mean implementing the logical/abastract model using hardware and programming?

I am always confused by the words "design" and "implementation" used in the tiles of books on OS, database, programming languages. There are also other books in the areas without the words. In general, what do such titles imply about the books' topics?

Are there other aspects about operating systems, besides design and implementation?

Thanks.

答:
It's a sports analogy.  Play-by-play is what you learn from a commentator while watching a game.  A "design" approach would be more akin to reading that game's rule book.

For a kernel book, a play-by-play example might start with an open call on a file, and trace that through the filesystem code, through the block device code, through the usb subsystem, through a device driver for a specific thumb drive chip, through primitives like kmalloc, and back on out to user space.

A lot of people learn well that way, but it only gives you a deep understanding of the specific use cases it covers.  A design approach would give you a broader understanding of how everything fits together at the high levels.  It's like the difference between a suite of unit tests and an architecture document.


问:
How to efficiently store big time series data?
I need to store and to be able to query some very large amounts time series data.

Properties of the data are as follows:

number of series : around 12.000 (twelve thousand)

number of data points, globally : around 500.000.000 per month (five hundred millions)

mixed value types: the majority of data points are floating point values, the rest are strings

sampling period : variable between series as well as within a series

timestamps : millisecond precision

data retention period : several years, without decay or downsampling

data archives need to be built in near realtime, but a reasonable delay (~1 hour) is acceptable

past data can be rebuilt if needed, but at a high cost

sometimes, but quite rarely, some past data needs to be updated

Properties of envisioned queries:

most of the queries against the data will be timestamp-based queries; ranging from one day to several months/years. 90%+ will be queries on the most recent data

Other requirements:

the solution must be free as in free beer and preferably opensource

My initial thought thought was to use PyTables / Pandas with HDF5 files as storing backend instead of an SQL database.

Questions :

Assuming PyTables / Pandas is the "best" route, would it be better to split the data in several HDF files, each one spanning a given period of time, or put everything in a single file that would then become huge ?

Should I go and prefer the fixed or the table format ? To me, fixed format looks OK if I keep one HDF file per month, as this way a whole series probably fits in RAM and I can slice in-memory without needing a table format index. Am I correct ?

And if that's not the best approach, how should I structure this data store or what technologies should I be considering?  I'm not the first to tackle storing large sets of time series data, what is the general approach to resolving this challenge?

Other approaches I have considered :

array databases: they are a superb fit for time series with constant sampling period, as you then only need to store start and end times and sampling period of the array, and then only values in the array itself and indexing is easy. But with variable sampling periods within series themselves, I need to keep a closer timestamp->value relation, that in my view is not such a good fit for array DBMS.

standard SQL database with timestamp,paramID,value as columns but by their nature they request a lot of disk I/O for any query

答:
You might want to take a look at carbon and whisper, part of the graphite project. Carbon can handle very large amounts of time series data. Though, now that I read the docs (it's been a few years since I've used it), it's only for numerical data. You said you also have string data so you might not find this useful. Though, you might be able to glean some wisdom about how they are able to process large amounts of data quickly.

To give you an idea of how well it scales, when graphite was first put into production at Orbitz, it was handling 160,000 metrics per minute.

OwnerDisplayName: flyingmig


问:
Jython and JRuby vs. Groovy (and Java)
I am very interested in Python for programming on the JVM, and I've worked in Java and Ruby (not JRuby) a lot, and to a certain extent in Groovy.

What are the limits to the Java-Jython and Java-JRuby integration right now? What about Groovy: are there any things that a Java class can do that a Groovy class cannot? And what about IDE integration (mostly Eclipse, but IntelliJ and Netbeans are also interesting)?

I'm not interested in whether Python, Ruby or Groovy is better/more-concise/whatever. I'm just interested in how well they are working in the JVM and tools (especially IDEs) right now. My main interest is not inside a web server, if that matters.

Simple examples of getting a HelloWorld which extends a custom Java class and implements a custom Java interface would be very useful to me.

答:
For the last year, I've been working a lot with Groovy (and Java as well, but more Groovy).

IDE integration: OK in Netbeans. Since Groovy is dynamic, don't expect the same level of IDE support like Java (Intelisense, Refactoring etc.). Some people say that InteliJ is even better, but my coworker who checked it out didn't like it. YMMV. Last time I checked, support in Eclipse was not as good as in Netbeans.

Groovy can be very easily integrated or mixed with Java. The syntax is relatively similar, so the mental switch doesn't hurt too much.

Especialy when used with the Grails framework, Groovy is fun to work with (IMO). I also like the similarity to JavaScript; therefore a project that mixed Groovy on the backend with JavaScript on the client doesn't require understanding two completely different languages; in many cases, it feels more like two dialects of the same language.

Title: Jython and JRuby vs. Groovy (and Java)


问:
Do I need to handle licenses of immediate dependenies?
Let's assume within my project which is GPLv3 based I'm using a single library called a-lib.jar. That jar itself is licensed using Apache v2 license, so I should be fine with the GPL as long as I respect the Apache v2 terms (basicly inclueding the license file).

Now when I look into the a-lib.jar that I'm using I see that it is using many other dependencies (packaged within a-lib.jar):

b-lib.jar

c-lib.jar

d-lib.jar

All of them are licensed on open source licenses, but the licenses may differ. E.g.:

b-lib.jar is licensed under MIT

c-lib.jar is licensed under Apache v2

d-lib.jar is licensed under some "custom made" open source license

The resulting file that I would like to release would look like this then:

```<code>myproject.jar
|--a-lib.jar
   |--b-lib.jar
   |--c-lib.jar
   |--d-lib.jar
</code>```

My question is: in order to avoid legal issues, do I have to comply with all the terms of the dependencies of the library that my project depends on? E.g. do I have to place some NOTICE file somewhere, saying that I'm using b-lib.jar and that it is under MIT? Then again: you can play that game forever: b-lib.jar may also include other 3rd-party licenses and so on and on.

Do I have to check EVERY SINGLE component and comply with it's terms, even if MY software is not useing it but instead a lib that I'm using is useing it? Or am I fine if I just take care of my projects dependencies and don't have to care about 3rd party dependencies? (Basic idea behind that would be that the creator of the a-lib.jar which released it under apache v2 is responsible for it's content).

Besides of that: is the situation of the example above any different if the 3rd party dependencies are not child-jars within the a-lib.jar but instead a-lib would be delivered as a maven project with dependencies to b-lib, c-lib and d-lib and those 3rd party dependencies would be packaged directly into my project *.jar file? So the resulting file would be:

```<code>myproject.jar
|--a-lib.jar
|--b-lib.jar
|--c-lib.jar
|--d-lib.jar
</code>```

答:
Surviving the treacherous landscape of open-source licenses can be difficult at times but you should respect the reason why programmers licence their software in the first place. In most instances they write open-source software out of the kindness of their heart. They don't get paid for it. They do get a warm fuzzy feeling from the fact they may have contributed something of value to society.

I have sat through countless hours of intellectual property presentations at work and I have a nice colourful matrix on my desk describing good and bad licenses for the creation of proprietary software (yes I have sold my soul and I get paid to write software). Generally we stick to MIT and BSD licensed software libraries because they're not infectious.

I could easily recommend that you simply concern yourself with the licencing of your immediate dependencies but you do expose yourself to a risk. Usually programmers to take care to make sure their licensing is compatible with dependencies (like you should be doing) but on the off chance, they may have made a mistake.

The bottom line is this, if you intend to make money from the software you write, you need to make sure you have permission tell sell other peoples work, implied by the licenses they ship with their libraries.


问:
Techniques for fitting multi language labels on forms
I am building a multi language website on ExtJS, where I have covered all the technical aspects of the multi language aspect.

How would deal with different string lengths? Lets say I design a 160px space for an specific label. That label is 120px long on Spanish, so everything ok with that; but that same label is 200px on Finnish; what would you do? trim that string? expand the original 160px space? What if we are talking about a form with several columns?

答:
There is no catch-all solution. The first step is to switch to a different unit. px is useless for text, because some users might have set a minimum font size in their browsers. The only way to adapt your layout to that is to use em for width and height.

And string length is not the only problem. Line height can be an issue too. Many non-Latin scripts need more vertical space.

You cannot resolve this just with code. You have to talk with the translators, and every translation must be tested visually.

I am working on a translation software with ten thousands of users. I talk with translators and developers every day, and I have never seen a layout that fits for all languages from the start. :)

BTW, I think this question would fit better on ux.stackexchange.com.


问:
What is the ideal mindset for a developer participating in a requirements gathering meeting?
As a mid-level developer on my team, I participate in requirements gathering/scope planning meetings of projects that I will be part of. I have been finding it difficult to come up with the questions that add value to the discussion or to my knowledge. After some self analysis, I found that knowing that there is a senior engineer in charge of the project who would lead the discussion, has caused me to be laid back in some of these discussions. But I do want to get to a point where I am entrusted with more responsibility and gain skills to handle projects on my own. Though mindset is a bit abstract term to ask about, I would like to get some advice on few things listed below:

What kind of preparation will I need to gain most out of these meetings. From observations from team members, I noticed that understanding what all systems that the project is going to impact, What business decisions will majorly impact the project design etc. are some of them.

Do I need to avoid thinking about low level implementation details for every requirement. On one hand, I feel it's important to consider them because I will know about the feasibility but I also understand it hinders considering all choices.

Finally, as a developer, what is something that I should not be worried about?

答:
What I try to emphasize when doing requirements gathering is that if this is for replacement for an existing system, to not think of how you do things in the existing system but rather what would be the ideal way to accomplish what you need to do.

So often users are stuck with the way things are done they can only describe their needs in that manner.

The most important thing for you as the implementer is to understand what they are truly trying to accomplish. One book that helped me as I was learning how to do business analysis was Software Requirement Patterns this book discusses how to get a deeper understanding of some of the implicit requirements that sometimes get over looked.

Also Domain Driven Design is a good book to study (especially with the concept of Ubiquitous Language which basically says use the terms that the domain experts use don't translate them to "developer speak" so much gets lost in translation).

Another item that's important is to become knowledgeable as quickly as possible about your target domain. When I developed for a logistics company, best believe I learned about Shippers, Cosignees, Responsible Parties, Less Than Truckload, Hubs, Docks, and everything else I needed to know to have an intelligent conversation with the business. When I worked for an Oil company I took the time to learn about Bores, Wells, Fields, Output, Saturation, and all that fun stuff that went with that industry.

That is the most valuable piece of advice I can give, learn the industry you're developing software for and you'll be able to gather better requirements from the users.


答:
I did following code, so I could measure the time in either option.

```<code>public static void multiple() {
    long start = System.currentTimeMillis();
    for (int i = 0; i < 100_000_000; i++) {
        Instance instance = new Instance();
        instance.rand();
    }
    long end = System.currentTimeMillis();
    long time = end - start;
    System.out.println("Multiple instance time: " + time);
}

public static void single() {
    long start = System.currentTimeMillis();
    Instance instance = new Instance();
    for (int i = 0; i < 100_000_000; i++) {
        instance.rand();
    }
    long end = System.currentTimeMillis();
    long time = end - start;
    System.out.println("Single instance time: " + time);
}

public static void statc() {
    long start = System.currentTimeMillis();
    for (int i = 0; i < 100_000_000; i++) {
        StaticInstance.rand();
    }
    long end = System.currentTimeMillis();
    long time = end - start;
    System.out.println("Static instance time: " + time);
}
</code>```

After run 100,000,000 time. The result was:

Multiple instance time: 2879

  Single instance time: 2714

  Static instance time: 2770

As expected, multiple instances is the worst option. Its important that in my samples, the constructor was dumb and light. If you got a heavy constructor, it will be big a pain for performance to multiple instances.

Single instance was the best one. But you must have a reference to the instance.

Static was a little worst than single instance.

Best regards,
Felipe

Body:
I did following code, so I could measure the time in either option.

public static void multiple() {
    long start = System.currentTimeMillis();
    for (int i = 0; i < 100_000_000; i++) {
        Instance instance = new Instance();
        instance.rand();
    }
    long end = System.currentTimeMillis();
    long time = end - start;
    System.out.println("Multiple instance time: " + time);
}

public static void single() {
    long start = System.currentTimeMillis();
    Instance instance = new Instance();
    for (int i = 0; i < 100_000_000; i++) {
        instance.rand();
    }
    long end = System.currentTimeMillis();
    long time = end - start;
    System.out.println("Single instance time: " + time);
}

public static void statc() {
    long start = System.currentTimeMillis();
    for (int i = 0; i < 100_000_000; i++) {
        StaticInstance.rand();
    }
    long end = System.currentTimeMillis();
    long time = end - start;
    System.out.println("Static instance time: " + time);
}

After run 100,000,000 time. The result was:

Multiple instance time: 2879

  Single instance time: 2714

  Static instance time: 2770

As expected, multiple instances is the worst option. Its important that in my samples, the constructor was dumb and light. If you got a heavy constructor, it will be big a pain for performance to multiple instances.

Single instance was the best one. But you must have a reference to the instance.

Static was a little worst than single instance.

Best regards,
Felipe


问:
Anybody use the Team Software Process (TSP) and/or Personal Software Process (PSP)?
More info on it here:
http://en.wikipedia.org/wiki/Team_Software_Process

What has your experience been?

答:
I’ve taken the PSP course and have been involved in creating on-line training for it.  I’ve seen a number of successful implementations of TSP/PSP in companies – e.g. Intuit, Adobe, HP.  The premise is strong: use accurate historical data of your own performance as a developer (in terms of time and, possibly more importantly, defects), analyse it (you’re given tools to do this), and base future predictions of your performance on this (that’s the PSP), and then roll this up with the data of your team members to create projections for your team’s performance (that’s the TSP).  Where teams "buy it", it’s remarkably effective at improving scheduling and reducing defect rates – there’s a lot of case studies and reports published.

Data privacy is a concern that is considered at some point by everyone who looks at the PSP.  The principle of the PSP is that your personal data is never shared.  When it’s rolled up with others' in your team, then the team can access the rolled-up data.  If you work for a company that violates this principle, then you’re likely to have put privacy concerns behind you.

Developers often buck at the prospect of logging time against their activities.  The key to this is an effective demonstration of the advantage of keeping a log, learning to analyse the data, and applying the lessons learnt to write less-defective code in the time you said you would.  Experiencing this is quite interesting.

Have a look at:

http://www.innerworkings.com/process  I'm only allowed 1 hyperlink in my post, so It'll be my own ;-)

Look also at the Web sites for the Software Engineering Institiute's TSP pages, their annual Symposium proceedings, and the Wikipedia entry for PSP (it's more comprehensive than the TSP page).

OwnerDisplayName: David Meaney

LastEditorDisplayName: David Meaney


问:
Nullable enumeration values vs. "NoValue" or "Undefined", etc
I often write code which translates entities in the database to domain objects.  These entities often have fields which are constrained and translate to enumerations in the domain objects.  In some cases, though, the fields can be null.

For example, imagine I have a PrintJob entity with a Status field that can be New, Submitted, or Completed and a Result field that can be Succeeded, FailedNoPaper, or FailedNoToner but it can also be NULL if the Status is not Completed.

On the one hand, I like having a one-to-one mapping of entity field values to domain object enum values, but on the other hand, it somehow feels "better" to always have values for properties with enumeration types.

My question is: is it better to represent the value of the Result field in my domain object as a nullable value (e.g. MyStatus? in C# or VB.NET) having essentially no value when the corresponding entity field is NULL, or should I create a special enum value along with the others, e.g. NoValue or Undefined?

答:
Compare your situation to the empty string / null string:

An empty string (in C: '\0') means the string is known to have no value, whereas the null string means it is not known to have a value.

As the result value is not known until the job finishes, the null value seems correct. Of course you can use an enum value to indicate "not known to be known". It also means you cannot query the result value until you have checked the status is "completed".


问:
Could programming ever have existed without error checking?
I think that in programming error checking is extremely important, not a secondary topic, what if your programme crashes without an error, just silently aborting? What if you must discover a SintaxError at line 1293 by manually checking all the lines? Would any programme longer than 5-10 lines be possible if error checking was never invented?

By no error checking I mean absolutely zero feedback if something goes wrong: not a line number, not a hint, nothing.

答:
Of course.

The only way you have syntax errors is if you have syntax. To have syntax, you need to have a language. To use a language, you need a compiler. At the very least then, the first compiler was a program written where there was no nice pleasant error messages when things went south.


问:
Good or bad idea to create a "fromJSON" static factory constructor for an object that is often created by parsing a JSON coming from API?
I have a "Product" POJO class in my app.
A Product object can either be created in-app by the user or by parsing a json that comes from the API.

Product has 20+ fields, but Im using only 2 here for clarity

Example:

```<code>JSON productJSON = networkCommunicator.getJSONFromStream();

Product product = new Product();
product.setId(productJSON.getInt("id");
product.setName(productJSON.getString("name");
</code>```

I want to create a fromJSON constructor in the Product class, but I dont know whether it is a good idea, because it couples the Product class to the API implementation of the JSON structure and the names of the keys in the JSON:

```<code>class Product {

    private int id;
    private String name;

    public Product(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public static Product fromJSON(JSONObject jsonObject) {
        return new Product(jsonObject.getInt("id"), jsonObject.getString("name");
    }

}
</code>```

This will make parsing the JSON coming from server much cleaner.

答:
The problem with your Product.fromJSON method is that it couples the Product to a specific serialization scheme. Furthermore, this violates the Single Responsibility Principle since the Product class isn't only concerned with modelling something, but also with data exchange.

In general, it makes sense to insulate your internal models from external data exchange via a de- and encoding layer. Instead of networkCommunicator.getJSONFromStream(), we want something like connection.getProduct(). Whether this connection uses JSON or XML or YAML is entirely irrelevant for your Product.

```<code> YOUR   | TRANSLATION | OUTSIDE
 MODEL  |    LAYER    |  WORLD
        |             |
   .------- decode  <---- JSON
   v    |             |
Product |             |
   `------> encode  ----> JSON
        |             |
</code>```

If you happen to be doing web development, you've probably heard about the MVC (Model-View-Controller) architecture or some variant of it. The Controller receives the external input and translates this to operations on the model. In the above diagram, this corresponds to the decoding step in the translation layer. If a part of the model is being displayed to the outside world, the model is rendered by the View. In the diagram, this is the encoding step.

Such a translation layer is almost never overkill, since the external data representation and your internal model are likely to be different. This is also the perfect place to do validation on the external input.

Body:
The problem with your Product.fromJSON method is that it couples the Product to a specific serialization scheme. Furthermore, this violates the Single Responsibility Principle since the Product class isn't only concerned with modelling something, but also with data exchange.

In general, it makes sense to insulate your internal models from external data exchange via a de- and encoding layer. Instead of networkCommunicator.getJSONFromStream(), we want something like connection.getProduct(). Whether this connection uses JSON or XML or YAML is entirely irrelevant for your Product.

 YOUR   | TRANSLATION | OUTSIDE
 MODEL  |    LAYER    |  WORLD
        |             |
   .------- decode  <---- JSON
   v    |             |
Product |             |
   `------> encode  ----> JSON
        |             |

If you happen to be doing web development, you've probably heard about the MVC (Model-View-Controller) architecture or some variant of it. The Controller receives the external input and translates this to operations on the model. In the above diagram, this corresponds to the decoding step in the translation layer. If a part of the model is being displayed to the outside world, the model is rendered by the View. In the diagram, this is the encoding step.

Such a translation layer is almost never overkill, since the external data representation and your internal model are likely to be different. This is also the perfect place to do validation on the external input.


答:
There's nothing stopping you from doing this on a practical level, IMO. Yes, technically it is a violation of separation of concerns, but pragmatically speaking it's no worse than, say, the Active Record pattern, which is widely used and many have no issue with it.

Alternatively, as suggested in comments, you could use a separate builder object to construct your objects:

```<code> Product product = new ProductBuilder().setJSON(jspnObject).build ();
</code>```

(the implementation of ProductBuilder should be obvious)

A third option is the use of a data binding library, e.g. Jackson.

Title: Good or bad idea to create a "fromJSON" static factory constructor for an object that is often created by parsing a JSON coming from API?

Body:
I have a "Product" POJO class in my app.
A Product object can either be created in-app by the user or by parsing a json that comes from the API.

Product has 20+ fields, but Im using only 2 here for clarity

Example:

```<code>JSON productJSON = networkCommunicator.getJSONFromStream();

Product product = new Product();
product.setId(productJSON.getInt("id");
product.setName(productJSON.getString("name");
</code>```

I want to create a fromJSON constructor in the Product class, but I dont know whether it is a good idea, because it couples the Product class to the API implementation of the JSON structure and the names of the keys in the JSON:

```<code>class Product {

    private int id;
    private String name;

    public Product(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public static Product fromJSON(JSONObject jsonObject) {
        return new Product(jsonObject.getInt("id"), jsonObject.getString("name");
    }

}
</code>```

This will make parsing the JSON coming from server much cleaner.

Body:
There's nothing stopping you from doing this on a practical level, IMO. Yes, technically it is a violation of separation of concerns, but pragmatically speaking it's no worse than, say, the Active Record pattern, which is widely used and many have no issue with it.

Alternatively, as suggested in comments, you could use a separate builder object to construct your objects:

 Product product = new ProductBuilder().setJSON(jspnObject).build ();

(the implementation of ProductBuilder should be obvious)

A third option is the use of a data binding library, e.g. Jackson.


问:
What is the proper relationship between the software developer and the business customer?
IT professionals are experts who are trusted with the IT assets of a business or organisation. As trusted professionals we have responsibilities that extend beyond things that a non-IT customer can be expected to understand or be aware of. So I think the proper relationship between an IT professional and his internal/external customers is more like that between a doctor and patient than a servant and master. Am I right?

Here's an analogy to think about. A patient insists that his leg needs to be amputated. His doctor disagrees but the patient cannot be persuaded. Should the doctor amputate the leg just to satisfy the patient?

Another analogy. A customer wants a civil engineer to build a bridge to an unsafe design. Even when the engineer explains that it is unsafe the customer doesn't believe him. Should the engineer build the bridge anyway?

I think the right answer in both these analogies is NO. The medical professional and engineering professional are supposed to be in a position of trust and ought to exercise their own judgement, even in the face of patient/customer disapproval. Shouldn't the same apply to IT professionals when the IT professional is qualified to make the decision but his customer is not?

答:
The key difference is licensing.  Doctors and civil engineers hold professional licenses, and need them to perform their job and make their living, and they also have legal personal responsibility for more things.

This can put more pressure on doctors and engineers, when pushed towards doing something that may cause them personal and professional risk, but it gives them more push-back, since they can argue that they can't do something because of professional ethics, and that they'll lose their licenses if they do.  A threat to fire a civil engineer for refusing to sign off on a plan loses force when the consequence of signing off is that the engineer will lose his or her license, and be unable to work in the field anyway.

This is connected with legal requirements.  I can't prescribe many drugs, and if I do certain things to somebody that a doctor can legally do I'd committing a crime.  Similarly, most governments around here will not permit a company to build a bridge without a licensed civil engineer approving the design.

There have been proposals to license programmers, but none I'm aware of have ever gone anywhere.  It would probably be necessary to have a legal requirement to have licensed programmers to work on projects first, and that isn't happening any time soon.  There are professional organizations with codes of ethics comparable to medical or engineering codes, but without any legal force they're more like guides for personal codes of ethics.


问:
int * vs int [N] vs int (*)[N] in functions parameters. Which one do you think is better?
When programming in C (or C++) there are three different ways to specify the parameter in a function that takes an array.

Here is an example (implementing std::accumulate from C++ in C) that shows you what I mean.

I can write it like this:

```<code>int accumulate(int n, int *array)
{
    int i;
    int sum = 0;
    for (i = 0; i < n; ++i) {
        sum += array[i];
    }
    return sum;
}
</code>```

This can also be written to this (which means the very same thing):

```<code>int accumulate(int n, int array[])
{
    int i;
    int sum = 0;
    for (i = 0; i < n; ++i) {
        sum += array[i];
    }
    return sum;
}
</code>```

I can also write it like this:

```<code>int accumulate(int n, int (*array)[])
{
    int i;
    int sum = 0;
    for (i = 0; i < n; ++i) {
        sum += (*array)[i];
    }
    return sum;
}
</code>```

All these options are very similar and generate the same executable code but they have a slight difference which is how the caller passes the arguments.

This is how the first two options gets called:

```<code>int main(void)
{
    int a[] = {3, 4, 2, 4, 6, 1, -40, 23, 35};
    printf("%d\n", accumulate(ARRAY_LENGTH(a), a));
    return 0;
}
</code>```

This is how the thrid option gets called:

```<code>int main(void)
{
    int a[] = {3, 4, 2, 4, 6, 1, -40, 23, 35};
    printf("%d\n", accumulate(ARRAY_LENGTH(a), &a));
    return 0;
}
</code>```

Note that the third option requires to user to explicitly specify the address of a
with &a. The first two options does not require this because arrays implicitly gets converted into pointers to the same type in C.

I have always preferred the third approach.

This is why:

It is more consistent with how other types are passed by pointers.

```<code>int draw_point(struct point *p);

int main()
{
    struct point p = {3, 4};
    draw_point(&p); // Here is the 'address of' operator required.
}
</code>```

It makes it possible to use macros like ARRAY_LENGTH to get the amount of elements in the array.

```<code>#include <stdio.h>
#define ARRAY_LENGTH(A) (sizeof(A) / sizeof(A[0]))

void this_works(int (*array)[10])
{
    /* This works! */
    printf("%d\n", ARRAY_LENGTH(*array));
}

void this_is_invalid_and_dangerous(int array[10])
{
    /* This does NOT work because `array` is actually a pointer. */
    printf("%d\n", ARRAY_LENGTH(array));
}
</code>```

The only advantage I see with int array[] (and int *array) is that you get to write array[X] instead of (*array)[X] when you wish to grab an index.

What are your professional thoughts on this? Which approach do you think is better and why? Do you ever mix the two? If so when do you choose what?

Like I said have I always preferred using int (*array)[N] but I see that the other two approaches are quite common as well.

答:
In C, when the array notation is used for a function parameter, it is automatically transformed into a pointer declaration, so declaring parameter as int* array and int array[] are equivalent. I tend to use second one because it is more clear that function expects an array as an argument.

Declaring function parameter as int (*array)[] is not equivalent to previous two, it is transformed to int** and it should be used when value of the parameter itself could be changed in function, i.e. reallocation of the array.


答:
Programming is often done without any error checking, even now. It's just considered sloppy, and should only be done for quick prototypes (or code golfs) that you're likely to throw away or rewrite later. Scripting languages tend to be good for this in part because they handle errors reasonably well whether or not you write any error handling code yourself.

If you mean "could we have gotten where we are without any piece of software ever doing error checks?", then the answer is no, unless someone invented a computer with infinite memory and no hardware faults, along with a network with 100% uptime for everyone forever, and so on.

If you're thinking of a specific convention such as checking the error codes returned by a function call, throwing and catching exceptions, or passing in success and failure callbacks, then yes we could have used different techniques.

There's also the philosophical problem (as pointed out by delnan) that you can't always draw a fine line between "error checking code" and "real code". If I'm writing a sqrt() function, checking that the input is positive is definitely an error check. But if I'm writing an HTML form with a bit of Javascript that automatically hyphenates phone numbers regardless of how the user entered them, is that considered "error handling" or "presentation logic"?

Title: Could programming ever have existed without error checking?

Body:
I think that in programming error checking is extremely important, not a secondary topic, what if your programme crashes without an error, just silently aborting? What if you must discover a SintaxError at line 1293 by manually checking all the lines? Would any programme longer than 5-10 lines be possible if error checking was never invented?

By no error checking I mean absolutely zero feedback if something goes wrong: not a line number, not a hint, nothing.


问:
Users in SQL databases
I took up programming a couple of months ago (alongside my day job) and am struggling with a couple of basic concepts. Currently, I'm trying to learn how to build a database based PHP login/logout for a web app.

Can anyone help me understand the concept of database users? The way I see it, there is:

a database server (which serves all the databases created, sort of like an "OS serves all the apps installed")

all the databases, with their tables inside

users (? this is where it gets confusing for me - how many and which users do I need?, what are basic good practices?)

users from the table "users", which will get into this table by registering on the website are not the same as users that the app uses to connect to the database? Or are they?

I apologize, I understand that these are basic concepts but I find the available web tutorials lacking in good concept explanations. Everyone seems to want to jump right into the coding part asap whereas I find that programming is more about ideas and concepts and then about syntax and languages.

Many thanks for any reply!
Alex

答:
There are two classes of users here:

users of the database

users of your web application

They are entirely different. (Or should be.)

The database users would be on the order of root (the database "superuser") and wordpress (if you were running WordPress, say, and chose that as the name to represent WordPress when connecting to the database). All of your application's requests on the database would funneled through just one (or a few) database user accounts.

Then your application would have its own table (myapp_users say, or wp_users for WordPress) that stores the application users.

I have seen applications that conflate these two kinds of users, and depend on the database access mechanisms entirely. That is a very, very, very bad idea, violating a number of least privilege, separation of concerns, and isolation of failure domains principles.

Your basic question answered, I'd like to also address an important unmentioned issue / "elephant in the room": Building user identification, authentication, and authorization is very difficult and tricky to get right.  Simple implementations almost invariably fail to protect security and privacy. First-time and novice implementations, even more so. If you are developing code to be used in any production setting, please consider depending on an existing, proven library such as Laravel, Opauth, or uLogin to manage user login instead of writing your own. (I'm not trying to endorse any specific framework here; just the idea of not writing user management/login yourself.)

Title: Users in SQL databases


问:
Using the optional 'self' reference in instance methods in Swift as a matter of style
Swift allows optional prefixing of method calls and property references to the current object instance via self. Removing these prefixes can declutter code but, depending on the length of the method and number of parameters and local variables, it can also make variable scope ambiguous.

Perhaps the answer is to refactor into smaller classes and methods, but sometimes that isn't always practical. Common examples are things like UIViewController subclasses and custom viewDidLoad() implementations or complex action handlers for UIGestureRecognizer subclasses. I've thought about this a bit since diving into developing an iOS app in Swift but am still on the fence. My ideal answer(s) would touch on:

If not referencing self has an practical downsides.

Whether mixing implicit and explicit references to self is worse that sticking to one or the other (I'm leaning towards yes).

Overall stylistic concerns with a focus on readability.

Instance variable naming styles versus local variable naming styles to mitigate ambiguity.

References to similar issues in other languages.

答:
Specifically in the case of Swift, I believe there are a few benefits to leaving out self unless explicitly required by the compiler:

Using self only where required (i.e. in closures where self is captured) makes it much easier to spot situations where references to self may be improperly retained.

I ran into an interesting issue where the use of self appears to prevent warning messages from being shown:

```<code>class MyObject {
    var myRange: Range‹Int›? {
        willSet {
            // This line has a warning that you are operating on a property that is about to change
            myRange?.startIndex = 2
            // This line does not show any warning
            self.myRange?.endIndex = 3
        }
    }
}
</code>```

You might argue that this is a bug, but I think it's important that self changes the way some expressions are treated, if only for warnings.

Body:
Specifically in the case of Swift, I believe there are a few benefits to leaving out self unless explicitly required by the compiler:

Using self only where required (i.e. in closures where self is captured) makes it much easier to spot situations where references to self may be improperly retained.

I ran into an interesting issue where the use of self appears to prevent warning messages from being shown:

class MyObject {
    var myRange: Range‹Int›? {
        willSet {
            // This line has a warning that you are operating on a property that is about to change
            myRange?.startIndex = 2
            // This line does not show any warning
            self.myRange?.endIndex = 3
        }
    }
}

You might argue that this is a bug, but I think it's important that self changes the way some expressions are treated, if only for warnings.


问:
What are the pros and cons of a language using whitespace vs. {}'s to indicate scope?
There seems to be a conflict over whether its better to use whitespace or tokens like brackets to indicate scope. I've seen many praise python's solution to the inconsistent indentation problem, but many disagree:

Any language that has whitespace as tokens needs to die.

posted later on the same answer:

I was sortof anti-whitespace-as-tokens, until I actually tried it. It probably helped that my personal white-space layout pretty much matches what everyone in python-land uses. Perhaps it's that I am a bit minimalist, but if you're going to indent anyways, why bother with the {}s?

I can see some clear arguments for each side:

using whitespace:

helps reduce inconsistent indentation in code

clears the screen by replace visible tokens with whitespace to serve the same purpose

using tokens:

much easier to cut and paste code to different levels (you don't have to fix the
indentation)

more consistent. Some text editors display whitespace differently.

more popular currently.

Are there any points I missed? Which do you prefer? Any words of wisdom after having worked with one or the other for a long time?

PS. I hate it when languages don't use the same token for each control structure. VB is really annoying with its End If and End While statements, most other languages just use {}'s for everything. But maybe that's a topic for a different question...

答:
I don't think it's really a versus.

Pythoneers often criticize braces programmers as if they would readily violate indentation because they can.

In fact I always used 100% consistent indentation even before knowing about Python and its indentation scoping.

The fact is that braces languages could also impose correct indentation in the compiler and we would have the best of both worlds. See? no versus at all.

Pythoneers would argue that braces are useless when indentation is part of the syntax, but they are not, braces improve readability.  I tried programming Python and it's a very interesting language for me, but have you tried having if-elif chains of more than 2 or 3 indentation levels? they don't look so neat anymore.

PS: I wrote braces but in a more general way, I mean delimiter tokens. The opening brace can be seen as redundant, but a language could go like this (in fact I'm sure there are languages exactly like this but I don't know them well):

```<code>if condition:
    statement
    other_statement()
end
</code>```

PS2: 2019, 4 years after this answer. I learned Python and totally got used to its semantic indentation and don't find it difficult to read at all. Especially with the aid of modern IDEs that draw vertical bars to aid in identifying indent blocks.

Body:
I don't think it's really a versus.

Pythoneers often criticize braces programmers as if they would readily violate indentation because they can.

In fact I always used 100% consistent indentation even before knowing about Python and its indentation scoping.

The fact is that braces languages could also impose correct indentation in the compiler and we would have the best of both worlds. See? no versus at all.

Pythoneers would argue that braces are useless when indentation is part of the syntax, but they are not, braces improve readability.  I tried programming Python and it's a very interesting language for me, but have you tried having if-elif chains of more than 2 or 3 indentation levels? they don't look so neat anymore.

PS: I wrote braces but in a more general way, I mean delimiter tokens. The opening brace can be seen as redundant, but a language could go like this (in fact I'm sure there are languages exactly like this but I don't know them well):

if condition:
    statement
    other_statement()
end

PS2: 2019, 4 years after this answer. I learned Python and totally got used to its semantic indentation and don't find it difficult to read at all. Especially with the aid of modern IDEs that draw vertical bars to aid in identifying indent blocks.

ContentLicense: CC BY-SA 4.0


答:
There is actually  a third type of users, perhaps that is causing some of your confusion.

There is the SQL User, aka login, in companies these may be Active Directory users or groups.  This type of user has the right to connec to the SQL database engine and one or more databases.  This user does not have to use the application to do whatever he can do.

The database user. This is typically linked to a login, and is used as the basis for defining database rights.  Are you denied from reading table B, allowed to Select from table F and update table U and delete rows in D? A typical public facing web application will have one or two database users.  Watch out for the anti-pattern of making that user be the database owner.  Multiple users/logins is more common for company reporting or desktop apps.  Again, this user does not have to be using the applicaion to do whatever he can do.  Other tools can be used.

The registered user.  This is the user that has registered with the application, and is then given permissions to do certain things inside the application.  This user can not directly connect to the database engine, all interaction is through the application.  Which is why the login/database user should not be dbo, but instead have restricted permissions.  You have probably heard of little Bobby tables by now, if the user that the application uses to connected to the database wasn't dbo, the students table wouldn't be dropped.

Title: Users in SQL databases

Body:
I took up programming a couple of months ago (alongside my day job) and am struggling with a couple of basic concepts. Currently, I'm trying to learn how to build a database based PHP login/logout for a web app.

Can anyone help me understand the concept of database users? The way I see it, there is:

a database server (which serves all the databases created, sort of like an "OS serves all the apps installed")

all the databases, with their tables inside

users (? this is where it gets confusing for me - how many and which users do I need?, what are basic good practices?)

users from the table "users", which will get into this table by registering on the website are not the same as users that the app uses to connect to the database? Or are they?

I apologize, I understand that these are basic concepts but I find the available web tutorials lacking in good concept explanations. Everyone seems to want to jump right into the coding part asap whereas I find that programming is more about ideas and concepts and then about syntax and languages.

Many thanks for any reply!
Alex


答: I'm not thinking of the ethical dimension, but the proper relationship to the customer/user base can be quite variable depending upon the type of market. Where I work we have a highly technical product, and highly technical users, and the average revenue per customer is fairly high. So our business boundaries are a bit blurry: we have customers and value added resellers who act as consultants, who assist in code checkout and may even submit modules for inclusion into the software. It we were selling a mass market application this model would make no sense whatsoever.</p>

Title: What is the proper relationship between the software developer and the business customer?

Body:
IT professionals are experts who are trusted with the IT assets of a business or organisation. As trusted professionals we have responsibilities that extend beyond things that a non-IT customer can be expected to understand or be aware of. So I think the proper relationship between an IT professional and his internal/external customers is more like that between a doctor and patient than a servant and master. Am I right?

Here's an analogy to think about. A patient insists that his leg needs to be amputated. His doctor disagrees but the patient cannot be persuaded. Should the doctor amputate the leg just to satisfy the patient?

Another analogy. A customer wants a civil engineer to build a bridge to an unsafe design. Even when the engineer explains that it is unsafe the customer doesn't believe him. Should the engineer build the bridge anyway?

I think the right answer in both these analogies is NO. The medical professional and engineering professional are supposed to be in a position of trust and ought to exercise their own judgement, even in the face of patient/customer disapproval. Shouldn't the same apply to IT professionals when the IT professional is qualified to make the decision but his customer is not?


答:
I'm not sure why anyone has been downvoting; I think this is a valid question, even if it seems absurd or the answer is obvious to everyone else.

If there is a language with a compiler that has no error/syntax reporting, the programmer can implement their own error reporting with basic tests and their program has to meet those expectations when they run they run the test program; when all the expectations in the test are met, the program has no known errors.  If a part of the test doesn't receive the expected value from the program, then the programmer can know where something went wrong.  There might not be error reporting per se, but this would definitely allow for large applications to be written with a stupid compiler or interpreter.  This, of course, is under the assumption that we are dealing with languages that have construct which would allow interaction with specific components(functions/methods/classes/modules/libraries/etc.).  Even without that, one could write a test routine that would go to a specific line of code and test whatever value gets returned.

Today, what I described is Behavior Driven Development(aka BDD).

Even without such tests, people have written applications with huge code bases without much useful feedback.  Depending on what form of assembly language one writes in, you may get no feedback except unexpected behavior.  Many C compilers don't have much useful feedback; not like that of modern interpreted languages.  Chris Sawyer wrote the original Roller Coaster Tycoon in mostly assembly and some C, which was definitely larger than 10 lines and I'm willing to bet that much of his development was based upon seeing whether or not he was getting the expected behavior from his code.

EDIT: Better yet, it just so happens that I had an experience about 5 days ago where I wrote 126 lines of Python code and it worked the first time I ran it.  That doesn't happen too often, but it shows that even a mediocre programmer such as myself can write more than 10 lines of useful code without error checking.  It just takes a lot of thought and planning.

Let's also not forget that before QWERTY keyboards and modern file systems, people wrote programs and even simple games by punching holes in cards and the programs were stored on big stacks of punched cards that were inserted into a giant computer; the program either worked or it didn't, and it was simply not practical to rely on feedback from the computer.  Using a computer was also a privilege for most, as not everyone had ownership or access to one on a regular basis.  The equivalent of 10+ lines of working code was written this way.


答:
You'll get into religious wars here, but let me say that I am on the "ignore SRP" side on this one.  Yes, you are coupling to a specific Serialization scheme, as correctly pointed out by @amon.  But, in this example, you are coupling to a very abstract and standard scheme, which makes it "o.k.".  Lots of Java classes have valueOf(String), and all have toString(), and the world hasn't ended due to lack of SRP.

SRP exists not because SRP itself a goal, but because SRP lessens the effect of change, an admirable goal.  In this example, what is more likely to change?

Product, e.g. by adding a new field named newFeature, changing it to an array, etc...  or

The JSON specification and library that you use.

In my experience, "#1" is always the right answer.  YMMV.

If Product changes, and fromJSON() is a method of Product, one class changes.  And it was going to change anyway, so there's no "extra" change.  Also, you could keep the new fields of Product private and final, increasing data-hiding and thread-safety.

OTOH, if you are using a ProductBuilder or ProductSerializer layer, then two classes change.  You are adding stuff about newFeature in multiple places, which violates DRY.  It is trickier to keep the new field private and final.  It is just plain extra work and tedium for little or no benefit, violating LEAN or YAGNI.  See, I can cite principles too.  :-)

One more thing:  consider making fromJSON a real instance method, not a static class function.  (It still returns a new Product object)   Yes, it feels weird, and you may decide against it.  But we "just tried it" in one project and it was wonderful.  You may need to add a final static Product.PROTOTYPE (or similar - maybe call it builder?).  But, it opens up some good features:

It can go into an interface, JSONable.  Static methods cannot be in an interface

Now you can have a Collection<JSONable> which suddenly does a lot for you.

You can provide a testing version, a mock version, etc.  If there is a class for which @amon is right and you really do want to decouple the logic into a ProductBuilder, you could call it here.

Caveats:

If you do change JSON libraries, you will have to change a lot of your classes, so be sure to write them in an intelligent way so that the JSON code is abstracted, as it should be, and as all the libraries do.  This is easy.

And, if you were serializing to some weird, offbeat, non-standard, very specific, and likely to change format, yes, then I agree with @amon that the code should be separated.  Or it you were tracking somebody else's JSON and they kept changing the names of their field, that would be an issue.  Or if the parsing is exceedingly complex, involves combining / "joining" a couple of JSON streams, etc.


问:
How does big O notation indicate upper bound on a function?
Suppose we have a function, f(n)=n+10.
We say that f(n)∈O(n), meaning O(n) represents the upper bound of the function.

It is also true that f(n)∈O(n2) or f(n)∈O(n3) and so on.

So how can we say that O(n) is the upper bound when O(n2) is comparatively bigger bound and O(n3) is much bigger bound?

Please forgive if I have understood the concept wrongly.

答:
f(n) = O(g(n)) states that if there exists some constant c>0 and n0>0, then f(n) <= cg(n) for all n >= n0. Here n0 is a limit above which we consider n i.e. we try to find asymptotic notation that itself means that we want to find time complexity for large values of n. So, we consider n0 as lower limit of n and above n0 this statement holds.

So, you have misunderstood that O(g(n)) with O(n), if we have two function with time complexity f(n1) = O(n1) and f(n2)= O(n22) then there is a property of Big-O which is O(resulting function) = max(O(n1),O(n22)). So, by this in this case O(n2) is upper bound in comparison to O(n).