问:
Designing a single look up entity
In almost every application you have this look up entity that provides a dynamic references. This are things like type, category, etc. These entities will always have

```<code>id, name, desc
</code>```

So at first I designed different entities for each look up. Like

```<code>education_type, education_level, degree_type....
</code>```

But on a second thought I decided to have on entity for each of these kinds of entities. But when I am done with the design and check the relation this entity will be referenced by almost all entities in the system and I don't believe that is appropriate. So What is your take on this? Can you give me some clear pros and cons?

答:
I find that whenever I have many ways of accessing entities, I tend to create a general query method taking generic parameters and using them to access data.  That method stays hidden, and other public methods access it properly according to what you pass it.

In other words, to search for an entity by id, I'd make a method getById(id) which then simply calls an inner method get which takes an array of parameters that I would pass to the query.

If you have to perform cross-relation checks, I would make the database do as much work as I possibly could before handling it in my program.  This is both for reasons of efficiency as well as simplicity in your code.  If you allow yourself to handle relations, you'll find that you'll be rewriting database logic, with all the complication that comes with it and none of the efficiency.

I'm not sure what you mean by entity, but my definition of entity is like the object-equivalent of a database table.  Relations between entities may require a database table (many-to-many), but they shouldn't get their own entity.

Title: Designing a single look up entity


问:
Is there any alternative to function pointers in c++?
I am a novice c++ programmer who kept an idea that function pointers are a thing of C and OOP in C++ does not recommend its usage.

I know what I write here is vague/broad. But it will be great if somebody could comment whether my idea is completely wrong or something sensible.

Thanks.

答:
Certainly C programmers used to use function pointers a lot, but most of those uses have been surpassed with OO alternatives - though they might not be obvious without examining the problem being solved rather than the solution itself.  For example, they were popular in implementing state machines but a C++ programmer would prefer to use a factory pattern.

One concept they are still necessary for is implementing a delegate (possibly the only reason to use one in the 21st century!?).  Provided as part of the language in other places the poor c++ developer still has to write his own - but it's fun to do (no!?) and you can find a description of how to do it here:  Stack Overflow

ContentLicense: CC BY-SA 3.0


问:
Requring static class setter to be called before constructor, bad design?
I have a class, say Foo, and every instance of Foo will need and contain the same List object, myList.

Since every class instance will share the same List Object, I thought it would be good to make myList static and use a static function to set myList before the constructor is called.

I was wondering if this was bad, because this requires the setter to be called before the constructor? If the person doesn't, the program will crash. Alternative way would be passing myList every time.

答:
Yes, it's bad.

Consider the alternative where you always pass in the list in constructor; you can still make each object receive the same list, e.g. by storing the list in the factory for the object, and passing it on new.

And since the class advertises that it needs a list instance by only offering a constructor that takes this instance, the user knows he's passing in null if he's not using the factory. This is much more obvious than requiring to call a static function.


答: It's a but unclear to me what are you actually asking but I would model things like education type and education level simply as enumerations (not as entities you need to load from the database or even instanciate). In many languages you can augment your enumerations with additional identity and description fields.</p>

Title: Designing a single look up entity

Body:
In almost every application you have this look up entity that provides a dynamic references. This are things like type, category, etc. These entities will always have

```<code>id, name, desc
</code>```

So at first I designed different entities for each look up. Like

```<code>education_type, education_level, degree_type....
</code>```

But on a second thought I decided to have on entity for each of these kinds of entities. But when I am done with the design and check the relation this entity will be referenced by almost all entities in the system and I don't believe that is appropriate. So What is your take on this? Can you give me some clear pros and cons?


问:
In an online questionnaire, what is a best way to design a database for keeping track of users all attempts?
We have a web app where users can take online exams.

Exam admin will create a questionnaire. A questionnaire can have many Questions. Each question is a multiple choice question (MCQ).

Let's say an admin creates a questionnaire with 10 questions. Users attempt those questions. Now, unlike real exams users can attempt single questionnaire multiple times. And we have to keep track of his all attempts.

e.g.

```<code> +-------+-----------------+------------+-------+------------+----------+
 |User_id|Questionnaire_id |question_id |answer |attempt_date|attempt_no|
 +-------+-----------------+------------+-------+------------+----------+
 |1      |1                |1           |a      |1 June 2013 |1         |
 |1      |1                |2           |b      |1 June 2013 |1         |
 |1      |1                |1           |c      |2 June 2013 |2         |
 |1      |1                |2           |d      |2 June 2013 |2         |
 +-------+-----------------+------------+-------+------------+----------+
</code>```

Now it can also happen that  after user has attempted same questionnaire twice, admin can delete a question from same questionnaire, but users' attempt history should still have reference to that so that user can see his that question in his attempt history in spite of admin deleting that question.

If user now attempts this changed questionnaire he should see only 1 question.

```<code> +-------+-----------------+------------+-------+------------+----------+
 |User_id|Questionnaire_id |question_id |answer |attempt_date|attempt_no|
 +-------+-----------------+------------+-------+------------+----------+
 |1      |1                |1           |a      |3 June 2013 |3         |
 +-------+-----------------+------------+-------+------------+----------+
</code>```

Also, after this user modified some part of question, users attempt history should show question before modification while any new attempt should show the modified question.

How do we manage this at database level?

My first gut feeling was that,

For deletes, do not do physical delete, just make a question inactive so that history can still keep track of users attempt.

For modifications, create versions for questions and each new attempt refres to latest version of each question and history keeping reference to version of question at attempt time.

答:
Mark the records as inactive using an 'active' flag (set to false) and...

create database views that show all records, active records and inactive records (using that 'active' flag) and then use them in your application as desired.


答:
If you just add the timestamp to the answer table, then you are either committing yourself to multiple queries, or to bringing back extra data when you only need the latest.  Here is a sample query with a sub-query (which is slow):

```<code>select * from answer
    where question_id = ? and user_id = ?
        and update_time =  (select max(update_time) from answer
                                where question_id = ? and user_id = ?)
</code>```

To avoid this, you can declare a separate table for history.  For instance, if your latest answers are in the answer table, you could have an answer_history table which is exactly the same (both tables should have a last_updated_time timestamp column).  This way you can store unlimited answer attempts and your queries against the latest answers will never slow down from history bloat, and never return extra records.

Not sure how far along you are with your design, but have you considered using Datomic?  It stores all history by default and has the ability to query history in different ways.  I don't think you have to declare any schema.  It breaks data structures into their component parts on save and reassembles the ones you need on read.  It's compatible with most JVM languages, though it was developed by the Clojure community.  It's not SQL, and it's not the record-based No-SQL that is currently popular.  Its design should be able to handle high loads comparable with SQL databases.  By pulling the "transactor" apart from the rest of the database, it allows you to scale your storage engine on cloud instances that you spin up as needed to handle load.

Title: In an online questionnaire, what is a best way to design a database for keeping track of users all attempts?

Body:
We have a web app where users can take online exams.

Exam admin will create a questionnaire. A questionnaire can have many Questions. Each question is a multiple choice question (MCQ).

Let's say an admin creates a questionnaire with 10 questions. Users attempt those questions. Now, unlike real exams users can attempt single questionnaire multiple times. And we have to keep track of his all attempts.

e.g.

```<code> +-------+-----------------+------------+-------+------------+----------+
 |User_id|Questionnaire_id |question_id |answer |attempt_date|attempt_no|
 +-------+-----------------+------------+-------+------------+----------+
 |1      |1                |1           |a      |1 June 2013 |1         |
 |1      |1                |2           |b      |1 June 2013 |1         |
 |1      |1                |1           |c      |2 June 2013 |2         |
 |1      |1                |2           |d      |2 June 2013 |2         |
 +-------+-----------------+------------+-------+------------+----------+
</code>```

Now it can also happen that  after user has attempted same questionnaire twice, admin can delete a question from same questionnaire, but users' attempt history should still have reference to that so that user can see his that question in his attempt history in spite of admin deleting that question.

If user now attempts this changed questionnaire he should see only 1 question.

```<code> +-------+-----------------+------------+-------+------------+----------+
 |User_id|Questionnaire_id |question_id |answer |attempt_date|attempt_no|
 +-------+-----------------+------------+-------+------------+----------+
 |1      |1                |1           |a      |3 June 2013 |3         |
 +-------+-----------------+------------+-------+------------+----------+
</code>```

Also, after this user modified some part of question, users attempt history should show question before modification while any new attempt should show the modified question.

How do we manage this at database level?

My first gut feeling was that,

For deletes, do not do physical delete, just make a question inactive so that history can still keep track of users attempt.

For modifications, create versions for questions and each new attempt refres to latest version of each question and history keeping reference to version of question at attempt time.

Body:
If you just add the timestamp to the answer table, then you are either committing yourself to multiple queries, or to bringing back extra data when you only need the latest.  Here is a sample query with a sub-query (which is slow):

select * from answer
    where question_id = ? and user_id = ?
        and update_time =  (select max(update_time) from answer
                                where question_id = ? and user_id = ?)

To avoid this, you can declare a separate table for history.  For instance, if your latest answers are in the answer table, you could have an answer_history table which is exactly the same (both tables should have a last_updated_time timestamp column).  This way you can store unlimited answer attempts and your queries against the latest answers will never slow down from history bloat, and never return extra records.

Not sure how far along you are with your design, but have you considered using Datomic?  It stores all history by default and has the ability to query history in different ways.  I don't think you have to declare any schema.  It breaks data structures into their component parts on save and reassembles the ones you need on read.  It's compatible with most JVM languages, though it was developed by the Clojure community.  It's not SQL, and it's not the record-based No-SQL that is currently popular.  Its design should be able to handle high loads comparable with SQL databases.  By pulling the "transactor" apart from the rest of the database, it allows you to scale your storage engine on cloud instances that you spin up as needed to handle load.


问:
Why do programming languages allow shadowing/hiding of variables and functions?
Many of the most popular programming languges (such as C++, Java, Python etc.) have the concept of hiding / shadowing of variables or functions. When I've encountered hiding or shadowing they have been the cause of hard to find bugs and I've never seen a case where I found it necessary to use these features of the languages.

To me it would seem better to disallow hiding and shadowing.

Does anybody know of a good use of these concepts?

Update:

I'm not refering to encapsulation of class members (private/protected members).

答:
If you disallow hiding and shadowing, what you have is a language in which all variables are global.

That's clearly worse than allowing local variables or functions that may hide global variables or functions.

If you disallow hiding and shadowing, AND you attempt to "protect" certain global variables, you create a situation where the compiler tells the programmer "I'm sorry, Dave, but you can't use that name, it is already in use."  Experience with COBOL shows that programmers almost immediately resort to profanity in this situation.

The fundamental issue is not hiding/shadowing, but global variables.


答:
Does anybody know of a good use of these concepts?

Using accurate, descriptive identifiers is always a good use.

I could argue that variable hiding doesn't cause many bugs since having two very similarly named variables of the same/similar types (what you'd do if variable hiding was disallowed) is likely to cause just as many bugs and/or just as severe bugs. I don't know if that argument is correct, but it's at least plausibly debatable.

Using some kind of hungarian notation to differentiate fields vs local variables gets around this, but has its own impact on maintenance (and programmer sanity).

And (perhaps most likely the reason that the concept is known of in the first place) it's far easier for languages to implement hiding/shadowing than to disallow it. Easier implementation means that compilers are less likely to have bugs. Easier implementation means that the compilers take less time to write, causing earlier and broader platform adoption.

Title: Why do programming languages allow shadowing/hiding of variables and functions?

Body:
Many of the most popular programming languges (such as C++, Java, Python etc.) have the concept of hiding / shadowing of variables or functions. When I've encountered hiding or shadowing they have been the cause of hard to find bugs and I've never seen a case where I found it necessary to use these features of the languages.

To me it would seem better to disallow hiding and shadowing.

Does anybody know of a good use of these concepts?

Update:

I'm not refering to encapsulation of class members (private/protected members).


问:
Effective and simple matching for 2 unequal small-scale point sets
I need to match two sets of 3D points, however the number of points in each set can be different. It seems that most algorithms are designed to align images and trimmed to work with hundreds of thousands of points. My case are 50 to 150 points in each of the two sets.

So far I have acquainted myself with Iterative Closest Point and Procrustes Matching algorithms. Implementing Procrustes algorithms seems like a total overkill for this small quantity. ICP has many implementations, but I haven't found any readily implemented version accounting for the so-called "outliers" - points without a matching pair.

Besides the implementation expense, algorithms like Fractional and Sparse ICP use some statistics information to cancel points that are considered outliers. For series with 50 to 150 points statistic measures are often biased or statistic significance criteria are not met.

I know of Assignment Problem in linear optimization, but it is not suitable for cases with unequal sets of points.

Are there other, small-scale algorithms that solve the problem of matching 2 point sets? I am looking for algorithm names, scientific papers or C++ implementations. I need some hints to know where to start my search.

答:
You want to find the maximum points in both of the sets? Then the brute force search means for every point P in the first set, traverse the second set to find
the point that match with point P. It costs O(M*N), which will be suit for your case.
Of course, you can sort the points first(first by x-axis,then y-axis,then z-asix.)
Then you can traverse these two sorted set to search for the matching points.</p>


问:
Store data for multiple User Type
I am developing an app where four types of user share same module. So is it a good idea to create:

one table and user_type and user_id (something like that)

table prefixes basically 4 diff tables of same columns

your own suggestion

(keeping in mind its a CakePHP App so joins and contain will be there)

答:
Your first option is likely the better of the two.

As points of considerations against the second option:

What happens when you get a 5th user type?  Do you now need to create a 5th table?  What about a 6th or 7th type?  what happens when you need to create a hybrid type that is based upon one but has some of the permissions of another?

What happens when you need to perform maintenance on the tables?  You have quadrupled your work (and opportunity for error!) by having 4 tables instead of 1.

Think through the logic of how a user would access the data.  Essentially, you'll have 4 separate pathways through your code because they access their own specific table.  That's 4 times the amount of work and debugging you now need to do at your php layer.

How does the 2nd solution scale when there's more than one table that needs to be access controlled?  All of the above considerations multiply by the number of tables affected.

Back to the first option.  Generally, group based permissions are the easiest to implement and most scalable for this scenario.

Users will belong to groups (types, in the language of your question), and the groups will have permissions to perform the CRUD actions against the table(s).

I would advise against having user based permissions as the maintenance costs are higher.  The difference is this:

Group based: user belongs to group and the group has permissions

User based: user has permissions.

If you keep the permissions in another table, it adds another join against your queries in order to make sure the user has the correct authorization.

On the other hand, if you hard-code the permissions into the queries at the php layer then you have a tighter coupling between your DB and your code as well as potentially additional code paths.

Either way, by using the first option you'll still have less code and chances for errors to deal with than you would in the second option.

Title: Store data for multiple User Type


问:
Story Point Estimation vs Ideal Days Estimation
In my project we assign 4 hours for 1 story point and estimate based on story point. So in this case one ideal day of work will be done in 2 elapsed days. From an agile standpoint are we doing story point estimation or ideal days estimation or none of these?</p>

答:
I too agree with the answer above. Most of the people who follow agile misinterpret estimates as 'hours required to complete the task". This could be because most of these people are moving from traditional waterfall to agile and they are very much into keeping track of all the hours spent on a particular chunk of work.
Instead of estimating just relatively size all the stories wrt each other. When we look at a group of stories it is pretty easy to compare them relatively to each other and have a good understanding of which ones are similar. The hard part is to predict how fast we will finish each story.

Now you'll ask - Why does it matter if we size our story if we are not mentioning the hours of work?

Well when you talk about estimates to client, they naturally start to think about time and cost. This leads to change in number of points because 'it is taking longer than estimate'. Just because a story has taken longer than anticipated, does that mean its relative size is different to all the other stories? Maybe… but most often it is that our velocity is not what we initially thought it would be. Thus when we talk about story size, we are trying to focus on velocity being the value different from expectation and not the story points. This way we'll move from updating story points from time to time and will try to improve the velocity.


答:
It sounds like an "Attribute Type" "Attribute Value" situation. With this scenario you always know the "Attribute Type" ahead of time because you will be very close to your data. The benefit allows for adding "Attribute Values" when the need arises.

Here is a couple things to keep in mind...

Obsolete Attribute Values probably need to stay in the database indefinetely

You need to allow for "None" and "Other" conditions

A separate "Sort Order" field at the "Attribute Value" level is a nice feature

Title: Designing a single look up entity


问:
Class design for calling "the same method" on different classes from one place
Let me introduce my situation:

I have Java EE application and in one package, I want to have classes which will act primarily as cache for some data from database, for example:

class that will hold all articles for our website

class that will hold all categories

etc.

Every class should have some update() method, which will update data for that class from database and also some other methods for data manipulation specific for that data type.

Now, I would like to call update() method for all class instances (there will be exactly one class instance for every class) from one place.

What is the best design?

答:
While you might be tempted to create an abstract class or interface. I would strongly advise against that approach.

Reasons Against Interfaces

You'll end up with two classes that do a lot of the same work.

It defines a contract but doesn't improve cohesion of code.

Reasons Against Abstraction

You'll end up with 3 classes. The base class and 2 implementing classes.

Most of the abstract methods will be public. Abstraction works best when the scope of the re-used methods are protected. This makes it clear that the abstract class is truly there to assist inherited classes.

Recommended Approach

Define a sealed caching class that doesn't care when it caches. Create a class called DatabaseCacher that knows how to keep ICachable objects in memory.

Articles and Categories then implement the ICachable interface.

DatabaseCacher should be used to modify the properties of ICachable. Don't implement any setter methods on your ICachable objects. Instead, create a generic setter method on DatabaseCacher that takes the name of the property as a parameter with it's value. This allows you to localize all caching and write operations of those objects.

I would avoid using a property change event listening approach. As it creates a large number of binding between only two entities (DatabaseCacher and ICachable objects). Property change listeners work best when the connection is ambiguous.


答: You should seriously consider using the observer pattern and, rather than calling an Update method which iterates through a list of objects that need an Update, you simply call an event to which all of your objects are subscribed for as long as they are valid to be updated?</p>

Title: Class design for calling "the same method" on different classes from one place

Body:
Let me introduce my situation:

I have Java EE application and in one package, I want to have classes which will act primarily as cache for some data from database, for example:

class that will hold all articles for our website

class that will hold all categories

etc.

Every class should have some update() method, which will update data for that class from database and also some other methods for data manipulation specific for that data type.

Now, I would like to call update() method for all class instances (there will be exactly one class instance for every class) from one place.

What is the best design?


答:
To implement this approach, you need to have the following columns:

TableID (or a categorization column)

Code

Description

IsActive (to avoid delete)

You will assign tableID=1 for education level, tableID=2 for degree type, etc.

Issues:

0 - Lookup values will not be easily sharable across projects.

1 - You need to build a Primary Key on the composite columns of (TableID and Code) to ensure uniqueness or have the code by sequentially generated column. This would lead to a composite FK which is not very nice. Alternatively, you could add an artificial column to be the PK (auto sequence for ex.).

2 - Each SELECT will have a hard-coded tableID. This could lead to ugly bugs.

3 - Be ware not to loose relationships between entries. For example, eduction level is related to degree type.

4 - Your data model (if you care) will not have meaningful relationships with this look-up table since some of the entries will not apply.

More on that can be found in: Why is using a common-lookup table to restrict the status of entity wrong?

In summary, if you have a small application, this may be tolerable, but if you are developing a large application it is not OK to have several look-ups in 1 big look-up table, at least conceptually.

Title: Designing a single look up entity


答:
I keep them separate from the app, stored in the database, one table per look up type.

I would also consider ways to filter them out of your UI, such as an "Enabled" flag (so a lookup item can be switched on or off), or possibly even a live from/to date.

This way changes can be made to your data without having to redeploy the whole application.

Title: Designing a single look up entity


问:
Can anyone explain representation of float in memory?
Can anyone help me in understanding how float values are stored in the memory.

My doubt is here float values contain '.' (for example 3.45) how the '.' will be represented in the memory?

Can anyone please clarify me with a diagram?

答:
The decimal point is not explicitly stored anywhere; that's a display issue.

The following explanation is a simplification; I'm leaving out a lot of important details and my examples aren't meant to represent any real-world platform.  It should give you a flavor of how floating-point values are represented in memory and the issues associated with them, but you will want to find more authoritative sources like What Every Computer Scientist Should Know About Floating-Point Arithmetic.

Start by representing a floating-point value in a variant of scientific notation, using base 2 instead of base 10.  For example, the value 3.14159 can be represented as

```

    0.7853975 * 2<sup>2</sup>

```

0.7853975 is the significand, a.k.a. the mantissa; it's the part of the number containing the significant digits.  This value is multiplied by the base 2 raised to the power of 2 to get 3.14159.

Floating-point numbers are encoded by storing the significand and the exponent (along with a sign bit).

A typical 32-bit layout looks something like the following:

```<code> 3 32222222 22211111111110000000000
 1 09876543 21098765432109876543210
+-+--------+-----------------------+
| |        |                       |
+-+--------+-----------------------+
 ^    ^                ^
 |    |                |
 |    |                +-- significand
 |    |
 |    +------------------- exponent
 |
 +------------------------ sign bit
</code>```

Like signed integer types, the high-order bit indicates sign; 0 indicates a positive value, 1 indicates negative.

The next 8 bits are used for the exponent.  Exponents can be positive or negative, but instead of reserving another sign bit, they're encoded such that 10000000 represents 0, so 00000000 represents -128 and 11111111 represents 127.

The remaining bits are used for the significand.  Each bit represents a negative power of 2 counting from the left, so:

```

    01101 = 0 * 2<sup>-1</sup> + 1 * 2<sup>-2</sup> + 1 * 2<sup>-3</sup> + 0 * 2<sup>-4</sup> + 1 * 2<sup>-5</sup>
          = 0.25 + 0.125 + 0.03125
          = 0.40625

```

Some platforms assume a "hidden" leading bit in the significand that's always set to 1, so values in the significand are always between [0.5, 1).  This allows these platforms to store values with a slightly greater precision (more on that below).  My example doesn't do this.

So our value of 3.14159 would be represented as something like

```

    0 10000010 11001001000011111100111
    ^     ^               ^
    |     |               |
    |     |               +--- significand = 0.7853975...
    |     |
    |     +------------------- exponent = 2 (130 - 128)
    |
    +------------------------- sign = 0 (positive)

    value= -1<sup>(sign)</sup> * 2<sup>(exponent)</sup> * (significand)
    value= -1<sup>0</sup> * 2<sup>2</sup> * 0.7853975...
    value= 3.14159...

```

Now, something you'll notice if you add up all the bits in the significand is that they don't total 0.7853975; they actually come out to 0.78539747.  There aren't quite enough bits to store the value exactly; we can only store an approximation.  The number of bits in the significand determines the precision, or how many significant digits you can store.  23 bits gives us roughly 6 decimal digits of precision.  64-bit floating point types offer enough bits in the significand to give roughly 12 to 15 digits of precision.  But be aware that there are values that cannot be represented exactly no matter how many bits you use.  Just as values like 1/3 cannot be represented in a finite number of decimal digits, values like 1/10 cannot be represented in a finite number of bits.  Since values are approximate, calculations with them are also approximate, and rounding errors accumulate.

The number of bits in the exponent determines the range (the minimum and maximum values you can represent).  But as you move towards your minimum and maximum values, the size of the gap between representable values increases.  That is, if you can't exactly represent values between 0.785397 and 0.785398, then you can't exactly represent values between 7.85397 and 7.85398 either, or values between 78.5397 and 78.5398, or values between 785397.0 and 785398.0.  Be careful when multiplying very large (in terms of magnitude) numbers by very small numbers.

ContentLicense: CC BY-SA 4.0

Body:
The decimal point is not explicitly stored anywhere; that's a display issue.

The following explanation is a simplification; I'm leaving out a lot of important details and my examples aren't meant to represent any real-world platform.  It should give you a flavor of how floating-point values are represented in memory and the issues associated with them, but you will want to find more authoritative sources like What Every Computer Scientist Should Know About Floating-Point Arithmetic.

Start by representing a floating-point value in a variant of scientific notation, using base 2 instead of base 10.  For example, the value 3.14159 can be represented as

    0.7853975 * 22

0.7853975 is the significand, a.k.a. the mantissa; it's the part of the number containing the significant digits.  This value is multiplied by the base 2 raised to the power of 2 to get 3.14159.

Floating-point numbers are encoded by storing the significand and the exponent (along with a sign bit).

A typical 32-bit layout looks something like the following:

 3 32222222 22211111111110000000000
 1 09876543 21098765432109876543210
+-+--------+-----------------------+
| |        |                       |
+-+--------+-----------------------+
 ^    ^                ^
 |    |                |
 |    |                +-- significand
 |    |
 |    +------------------- exponent
 |
 +------------------------ sign bit

Like signed integer types, the high-order bit indicates sign; 0 indicates a positive value, 1 indicates negative.

The next 8 bits are used for the exponent.  Exponents can be positive or negative, but instead of reserving another sign bit, they're encoded such that 10000000 represents 0, so 00000000 represents -128 and 11111111 represents 127.

The remaining bits are used for the significand.  Each bit represents a negative power of 2 counting from the left, so:

    01101 = 0 * 2-1 + 1 * 2-2 + 1 * 2-3 + 0 * 2-4 + 1 * 2-5
          = 0.25 + 0.125 + 0.03125
          = 0.40625

Some platforms assume a "hidden" leading bit in the significand that's always set to 1, so values in the significand are always between [0.5, 1).  This allows these platforms to store values with a slightly greater precision (more on that below).  My example doesn't do this.

So our value of 3.14159 would be represented as something like

    0 10000010 11001001000011111100111
    ^     ^               ^
    |     |               |
    |     |               +--- significand = 0.7853975...
    |     |
    |     +------------------- exponent = 2 (130 - 128)
    |
    +------------------------- sign = 0 (positive)

    value= -1(sign) * 2(exponent) * (significand)
    value= -10 * 22 * 0.7853975...
    value= 3.14159...

Now, something you'll notice if you add up all the bits in the significand is that they don't total 0.7853975; they actually come out to 0.78539747.  There aren't quite enough bits to store the value exactly; we can only store an approximation.  The number of bits in the significand determines the precision, or how many significant digits you can store.  23 bits gives us roughly 6 decimal digits of precision.  64-bit floating point types offer enough bits in the significand to give roughly 12 to 15 digits of precision.  But be aware that there are values that cannot be represented exactly no matter how many bits you use.  Just as values like 1/3 cannot be represented in a finite number of decimal digits, values like 1/10 cannot be represented in a finite number of bits.  Since values are approximate, calculations with them are also approximate, and rounding errors accumulate.

The number of bits in the exponent determines the range (the minimum and maximum values you can represent).  But as you move towards your minimum and maximum values, the size of the gap between representable values increases.  That is, if you can't exactly represent values between 0.785397 and 0.785398, then you can't exactly represent values between 7.85397 and 7.85398 either, or values between 78.5397 and 78.5398, or values between 785397.0 and 785398.0.  Be careful when multiplying very large (in terms of magnitude) numbers by very small numbers.


问:
Designing a user-defined list to be stored in a relational database - Should I include user index?
By index, I mean, as the user creates the list, each item receives an integer index for its place in that particular list.  Since there will be a table of ListItems, I'd prefer to avoid using the name "Index" for the field.

Then I was thinking - should I even include the list index in the database?  I figured I would because the list would be created in the same fashion every time, then.  Or I could order the list for the user based on its actual primary key, since the list items are created in succession anyway...

What should I do?

答:
Presenting the items of a list in the same order is strongly recommended for every GUI. However the ordering logic should be part of the presentation layer. Different users will have different orderings. This should be stored as a user preference.

If you want a simpler solution just use a hardwired ordering, doesn't matter as long as you don't rely on unspecified behavior.


答:
You are correct to avoid using the word index in the column name. I suggest that you avoid names that could be misinterpreted if you have a reasonable substitute.

One option is to call the column "SortOrder" or "DisplayOrder".

Is there a requirement for the list of items to be displayed or sorted in a particular order? If it's not required, you might save time by skipping it. On the other hand, sorting is a feature that many people do not think to ask for until the instant they see something that is not sorted to their liking.

Title: Designing a user-defined list to be stored in a relational database - Should I include user index?

Body:
By index, I mean, as the user creates the list, each item receives an integer index for its place in that particular list.  Since there will be a table of ListItems, I'd prefer to avoid using the name "Index" for the field.

Then I was thinking - should I even include the list index in the database?  I figured I would because the list would be created in the same fashion every time, then.  Or I could order the list for the user based on its actual primary key, since the list items are created in succession anyway...

What should I do?


问:
Get Info From Database, or Build Inferred Info?
Does it make more sense to store and retrieve properties or information directly related to an item in a database, or, say in such a case that a product's ID could describe information about it, should the information be gathered from that?

Example: Item SKU -- 4HBU12

4 - is the number of motors

H - the voltage

B - the color, blue

U - the model

12 - the length

Should I store those individual attributes as well as the SKU, or should I store only the SKU and build the attributes from it?

答:
It would be better to store the individual attributes of the product and store the SKU as well.

This is in order to allow more flexibility in the way you design your attributes as well as to allow you to query specific products more efficiently through SQL. If relied on the SKU to derive the attributes of the products, its going to be really hard to write select * from item where voltage = 'H'.

While one may argue that you can simply do a wildcard query to do the searching for you, this makes it hard for you to extend your database in the future. For example, after a year or two, you now have to use two characters for your voltage attribute instead of one, effectively all queries built with a wildcard query like this select * from product where SKU like '_H__%' will not get you the right result all the time.


答:
Putting reporting aside.

Store the Individual Attributes... Heres why, What if a mistake is made?

Suppose you manufacture 5000 black units then realize that they have been made red accidentally? What do you do?

You could have pre-orders and receiving history and this SKU can exist on a 100 tables in the system before you realize it. Even if you can change the SKU throughout the system, what about all the paperwork, such as PO from customer\vendors (It may even be printed on  the product itself!).
As a general rule a key should never define attributes. Naming conventions are great, but should be just that a convention, not a hard system enforced rule.

Title: Get Info From Database, or Build Inferred Info?

Body:
Does it make more sense to store and retrieve properties or information directly related to an item in a database, or, say in such a case that a product's ID could describe information about it, should the information be gathered from that?

Example: Item SKU -- 4HBU12

4 - is the number of motors

H - the voltage

B - the color, blue

U - the model

12 - the length

Should I store those individual attributes as well as the SKU, or should I store only the SKU and build the attributes from it?


问:
Do activity diagrams always end in one endpoint?
For example an activity diagram for a simple program:

Get User data.

If User Exists DO something, ELSE do nothing.

End.

I often see diagrams with multiple endpoints but also with just one. Should activity diagrams merge both ways to one final state, regardless of the previous paths?

答:
Multiple endpoints are acceptable within an activity diagram.

Here's a number of sites backing up that assertion.

This DeveloperWorks article

every activity diagram should have at least one final state symbol

with "at least one" implying that multiples are allowed.

This snippet from the book Java Server Programming on page 1551

An activity diagram has a start and may have multiple endpoints.

This Xpdian article on activity diagrams

An activity diagram has a start and may have multiple end points. The UML 2 also provides for a flow final (a circle with a cross) that indicates that the process stops.


问:
How to avoid big and clumsy UITableViewController on iOS?
I have a problem when implementing the MVC-pattern on iOS. I have searched the Internet but seems not to find any nice solution to this problem.

Many UITableViewController implementations seems to be rather big. Most examples I have seen lets the UITableViewController implement <UITableViewDelegate> and <UITableViewDataSource>. These implementations are a big reason why UITableViewControlleris getting big. One solution would be to create separate classes that implements <UITableViewDelegate> and <UITableViewDataSource>. Of course these classes would have to have a reference to the UITableViewController. Are there any drawbacks using this solution? In general I think you should delegate the functionality to other "Helper" classes or similar, using the delegate pattern. Are there any well established ways of solving this problem?

I do not want the model to contain too much functionality, nor the view. I believe that the logic should really be in the controller class, since this is one of the cornerstones of the MVC-pattern. But the big question is:

How should you divide the controller of a MVC-implementation into smaller manageable pieces? (Applies to MVC in iOS in this case)

There might be a general pattern for solving this, although I am specifically looking for a solution for iOS. Please give an example of a good pattern for solving this issue. Please provide an argument why your solution is awesome.

答:
Here is roughly what I'm currently doing when facing similar problem:

Move data related operations to XXXDataSource class(which inherits from BaseDataSource : NSObject). BaseDataSource provides some convenient methods like - (NSUInteger)rowsInSection:(NSUInteger)sectionNum; , subclass overrides data loading method(as apps usually have some sort of offlie cache load method looks like - (void)loadDataWithUpdateBlock:(LoadProgressBlock)dataLoadBlock completion:(LoadCompletionBlock)completionBlock; so that we can update UI with cached data received in LoadProgressBlock while we are updating info from network, and in completion block we refresh UI with new data and remove progess indicators, if any). Those classes do NOT conform to UITableViewDataSource protocol.

In BaseTableViewController(which conforms to UITableViewDataSource and UITableViewDelegate protocols) I have reference to BaseDataSource, which I create during controller init. In UITableViewDataSource part of controller I simply return values from dataSource(like
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [self.tableViewDataSource sectionsCount];
}).

Here is my cellForRow in base class(no need to override in subclasses):

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = [NSString stringWithFormat:@"%@%@", NSStringFromClass([self class]), @"TableViewCell"];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [self createCellForIndexPath:indexPath withCellIdentifier:cellIdentifier];
    }
    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}
</code>```

configureCell must be overriden by subclasses and createCell returns UITableViewCell, so if you want custom cell, override it too.

After base things are configured(actually, in first project which uses such scheme, after that this part can be reused) what is left for BaseTableViewController subclasses is:

Override configureCell(this usually transforms to asking dataSource for object for index path and feeding it to cell's configureWithXXX: method or getting object's UITableViewCell representation like in user4051's answer)

Override didSelectRowAtIndexPath:(obviously)

Write BaseDataSource subclass which takes care of working with necessary part of Model(suppose there are 2 classes Account and Language, so subclasses will be AccountDataSource and LanguageDataSource).

And that's all for table view part. I can post some code to GitHub if needed.

Edit: some recomendations can be found at http://www.objc.io/issue-1/lighter-view-controllers.html (which has link to this question) and companion article about tableviewcontrollers.

Body:
Here is roughly what I'm currently doing when facing similar problem:

Move data related operations to XXXDataSource class(which inherits from BaseDataSource : NSObject). BaseDataSource provides some convenient methods like - (NSUInteger)rowsInSection:(NSUInteger)sectionNum; , subclass overrides data loading method(as apps usually have some sort of offlie cache load method looks like - (void)loadDataWithUpdateBlock:(LoadProgressBlock)dataLoadBlock completion:(LoadCompletionBlock)completionBlock; so that we can update UI with cached data received in LoadProgressBlock while we are updating info from network, and in completion block we refresh UI with new data and remove progess indicators, if any). Those classes do NOT conform to UITableViewDataSource protocol.

In BaseTableViewController(which conforms to UITableViewDataSource and UITableViewDelegate protocols) I have reference to BaseDataSource, which I create during controller init. In UITableViewDataSource part of controller I simply return values from dataSource(like
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [self.tableViewDataSource sectionsCount];
}).

Here is my cellForRow in base class(no need to override in subclasses):

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = [NSString stringWithFormat:@"%@%@", NSStringFromClass([self class]), @"TableViewCell"];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [self createCellForIndexPath:indexPath withCellIdentifier:cellIdentifier];
    }
    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}

configureCell must be overriden by subclasses and createCell returns UITableViewCell, so if you want custom cell, override it too.

After base things are configured(actually, in first project which uses such scheme, after that this part can be reused) what is left for BaseTableViewController subclasses is:

Override configureCell(this usually transforms to asking dataSource for object for index path and feeding it to cell's configureWithXXX: method or getting object's UITableViewCell representation like in user4051's answer)

Override didSelectRowAtIndexPath:(obviously)

Write BaseDataSource subclass which takes care of working with necessary part of Model(suppose there are 2 classes Account and Language, so subclasses will be AccountDataSource and LanguageDataSource).

And that's all for table view part. I can post some code to GitHub if needed.

Edit: some recomendations can be found at http://www.objc.io/issue-1/lighter-view-controllers.html (which has link to this question) and companion article about tableviewcontrollers.


答: It makes sense to end the activity diagram at 1 point if the activity will return no value to caller or if it is returning the same object (or value) in all cases except a major error. If the activity may result in separate actions multiple end points would be valid. In your example, I would prefer a single end point. As an example of multiple end points would be a controller sending different messages to different devices based on a condition.</p>

Title: Do activity diagrams always end in one endpoint?

Body:
For example an activity diagram for a simple program:

Get User data.

If User Exists DO something, ELSE do nothing.

End.

I often see diagrams with multiple endpoints but also with just one. Should activity diagrams merge both ways to one final state, regardless of the previous paths?


问:
How does TDD address interaction between objects?
TDD proponents claim that it results in better design and decoupled objects. I can understand that writing tests first enforces the use of things like dependency injection, resulting in loosely coupled objects. However, TDD is based on unit tests - which test individual methods and not the integration between objects. And yet, TDD expects design to evolve from the tests themselves.

So how can TDD possibly result in a better design at the integration (i.e. inter-object) level when the granularity it addresses is finer than that (individual methods)?

答:
I think you want to look at integration tests, where you might mock out the classes which are the individual components and their expected results and perform actions on a collection of those.

You should set the output of test or mocked objects to known/expected values, you are then purely testing methods which interact on those specific objects.

Take an example where you have two classes, Person and Car for example. The individual class based unit tests would test say functions on each of those classes Person.SetName() and Car.SetMake() for example.

Your integration test might be the testing of a CarParkService where you'd pass in a Car and Person in a known state (potentially mocked) and call the method ParkACar(Person p, Car c).
With this way of working you're purely testing the integration of the person and the car within the context of a service.

You can test this a lot further, but as far as I view it, in a simple sense integration tests will test the combination of classes/methods as a group (such as a service).

OwnerDisplayName: Gigi

OwnerDisplayName: dougajmcdonald


答:
It depends. In TDD it doesn't have to be that there is a one-to-one relationship between a test and a class. Refactoring can produce many classes that are essentially under one set of tests. In that sense, those class interactions are tested.

That being said, there are boundaries where you would mock out certain interactions, whether using a mocking framework, or just in terms of decoupling. Those boundaries are subject to different testing, that is beyond TDD. In terms of TDD, you make the surface and the complexity of creating the coupling as small as reasonably possible and then the actual coupling doesn't get tested by TDD.

The coupling should generally be a line or two of code. If it is too complicated, you may need to test the coupling mechanism independent of the whole system, but that gets back to one of those boundaries.

Then you are left with an issue which is beyond TDD - I wrote a class or group of classes to do A, with the idea that class or group of classes B would interact with it. But did I mess that up? Is there a subtle difference in what I was thinking when I wrote one vs what I was thinking when I wrote the other? And of course in a multi-person project each side might not have been written by the same person.

That is integration testing, acceptance testing, QA, etc. It is test after, not test driven, even if your acceptance tests are written before, it isn't really the same.

Title: How does TDD address interaction between objects?

Body:
TDD proponents claim that it results in better design and decoupled objects. I can understand that writing tests first enforces the use of things like dependency injection, resulting in loosely coupled objects. However, TDD is based on unit tests - which test individual methods and not the integration between objects. And yet, TDD expects design to evolve from the tests themselves.

So how can TDD possibly result in a better design at the integration (i.e. inter-object) level when the granularity it addresses is finer than that (individual methods)?

OwnerDisplayName: Yishai


答:
I disagree with your assumption that unit tests have to be method-scope. Unit tests don't have to be limited to testing individual methods, they can test interactions between objects too.

The difference between a unit test and an integration test is that the integration test requires some kind of external resource (database, queue, file system, etc.) to be present. The unit test would use mocks to stand in for things at the boundaries of the application.

There is an idea that unit tests should be small. The wikipedia article on Unit testing says:

In computer programming, unit testing is a method by which individual
  units of source code, sets of one or more computer program modules
  together with associated control data, usage procedures, and operating
  procedures are tested to determine if they are fit for use.1
  Intuitively, one can view a unit as the smallest testable part of an
  application. In procedural programming, a unit could be an entire
  module, but is more commonly an individual function or procedure. In
  object-oriented programming, a unit is often an entire interface, such
  as a class, but could be an individual method. [2] Unit tests are
  created by programmers or occasionally by white box testers during the
  development process.

So the idea of what constitutes a unit seems very flexible to me.

There's no reason a unit test can't instantiate different objects and test the results of using them together, that can be a valuable way of testing that the code is internally self-consistent.

OwnerDisplayName: Nathan Hughes


答:
To answer your question, I would say, what you state is right, partly.

TDD makes extensive use of unit tests, but also acceptance test. If you look at the full TDD test cycle described in Growing Object-Oriented Software, Guided by Tests, it is:

Write a failing acceptance test

Write a failing unit test

Make the failing test pass

Refactor

Repeat steps 2-4 until the failing acceptance test passes

By definition acceptance tests are end-to-end tests that start from the user input level through all your application stack (including domain objects, external services and databases).

Because of this you will not only test your components and define interaction there, but also base them on overarching acceptance tests that proof your components work together.

This will provide you with enough certainty so you are able to impose structural and architectural improvements on your code whenever required.

If you want to see this in action check this TDD session with Uncle Bob.

OwnerDisplayName: Jesko R.


答:
Unfortunately the definition of unit test is very fuzzy. One of the most cited definitions is done through the properties the tests should have, which are

runs fast

is isolated (no interactions between tests, i.e. run them in any order and always get the same result)

requires no external configuration

provides a consistent pass/fail result
It's from Roy Osherove's book, the art of unit testing.

If I were to add a definition, I'd say a unit test asserts against the result of a logical path through a method where you have control over the result of all dependencies involved (fwiw, that's just my definition).

Imagine you have to create a method that checks if a string is valid, and if so does something, if not does something different.
This is how we could write that method if we want it to be unit testable:

```<code>class SomeClass
{
    IStringAnalyzer stringAnalizer;
    ILogger logger;

    public SomeClass(IStringAnalyzer stringAnalyzer, ILogger logger)
    {
        this.logger = logger;
        this.stringAnalyzer = stringAnalyzer;
    }

public void SomeMethod(string someParameter)
    {

    if (stringAnalyzer.IsValid(someParameter))
    {
        //do something with someParameter
    }else
    {
        logger.Log("Invalid string");
    }
}
</code>```

stringAnalyser and logger are dependencies because we want to be able to control what they return (through a stub) and how they are used (through a mock).

This is so you can write a test like this (that has all the nice characteristics that Roy describes in his book):

```<code>[Test]
public void SomeMethod_InvalidParameter_CallsLogger
{
    Rhino.Mocks.MockRepository mockRepository = new Rhino.Mocks.MockRepository();
    IStringAnalyzer s = mockRepository.Stub<IStringRepository>();
    s.Stub(s => s.IsValid("something, doesnt matter").IgnoreParameters().Return(false);
    ILogger l = mockRepository.DynamicMock<ILogger>();
    SomeClass someClass = new SomeClass(s, l);
    mockRepository.ReplayAll();

    someClass.SomeMethod("What you put here doesnt really matter because the stub will always return false");

    l.AssertWasCalled(l => l.Log("Invalid string"));
}
</code>```

The benefits are that the "several concerns" are all decoupled and they are very easy to spot when you are doing the test first. You'd see that you would need to leave the logic of StringAnalizer out of the class you are testing because the need for controlling if a string is valid or not would be evident.

That test makes use of an isolation framework (rhino mocks) and I explain what that is here: http://blinkingcaret.wordpress.com/2012/11/20/interaction-testing-fakes-mocks-and-stubs/

Regarding the discussion of TDD really produces better designs all I can say is this: http://blinkingcaret.wordpress.com/2012/10/02/tdd-bdd-add-every-other-method-that-promises-software-quality-here-and-the-tea-tasting-lady/
And this: http://vimeo.com/9270320

Body:
Unfortunately the definition of unit test is very fuzzy. One of the most cited definitions is done through the properties the tests should have, which are

runs fast

is isolated (no interactions between tests, i.e. run them in any order and always get the same result)

requires no external configuration

provides a consistent pass/fail result
It's from Roy Osherove's book, the art of unit testing.

If I were to add a definition, I'd say a unit test asserts against the result of a logical path through a method where you have control over the result of all dependencies involved (fwiw, that's just my definition).

Imagine you have to create a method that checks if a string is valid, and if so does something, if not does something different.
This is how we could write that method if we want it to be unit testable:

class SomeClass
{
    IStringAnalyzer stringAnalizer;
    ILogger logger;

    public SomeClass(IStringAnalyzer stringAnalyzer, ILogger logger)
    {
        this.logger = logger;
        this.stringAnalyzer = stringAnalyzer;
    }

public void SomeMethod(string someParameter)
    {

    if (stringAnalyzer.IsValid(someParameter))
    {
        //do something with someParameter
    }else
    {
        logger.Log("Invalid string");
    }
}

stringAnalyser and logger are dependencies because we want to be able to control what they return (through a stub) and how they are used (through a mock).

This is so you can write a test like this (that has all the nice characteristics that Roy describes in his book):

[Test]
public void SomeMethod_InvalidParameter_CallsLogger
{
    Rhino.Mocks.MockRepository mockRepository = new Rhino.Mocks.MockRepository();
    IStringAnalyzer s = mockRepository.Stub<IStringRepository>();
    s.Stub(s => s.IsValid("something, doesnt matter").IgnoreParameters().Return(false);
    ILogger l = mockRepository.DynamicMock<ILogger>();
    SomeClass someClass = new SomeClass(s, l);
    mockRepository.ReplayAll();

    someClass.SomeMethod("What you put here doesnt really matter because the stub will always return false");

    l.AssertWasCalled(l => l.Log("Invalid string"));
}

The benefits are that the "several concerns" are all decoupled and they are very easy to spot when you are doing the test first. You'd see that you would need to leave the logic of StringAnalizer out of the class you are testing because the need for controlling if a string is valid or not would be evident.

That test makes use of an isolation framework (rhino mocks) and I explain what that is here: http://blinkingcaret.wordpress.com/2012/11/20/interaction-testing-fakes-mocks-and-stubs/

Regarding the discussion of TDD really produces better designs all I can say is this: http://blinkingcaret.wordpress.com/2012/10/02/tdd-bdd-add-every-other-method-that-promises-software-quality-here-and-the-tea-tasting-lady/
And this: http://vimeo.com/9270320

OwnerDisplayName: Rui


答:
So how can TDD possibly result in a better design at the integration
  (i.e. inter-object) level when the granularity it addresses is finer
  than that (individual methods) ?

Because granularity evolves as a result of TDD :)

The fact that the entry point in a test (Act part in Arrange Act Assert) is a single method doesn't mean all resulting production code will be contained in that method at the end of the TDD cycle.

A (the most ?) important step in TDD is refactoring. Through refactoring, code can be moved to another method or another class.


问:
Nested Entities and calculation on leaf entity property - SQL or NoSQL approach
I am working on a hobby project called Menu/Recipe Management.

This is how my entities and their relations look like.

A Nutrient has properties Code and Value

An Ingredient has a collection of Nutrients

A Recipe has a Collection of Ingredients and occasionally can have a collection of other recipes

A Meal has a Collection of Recipes and Ingredients

A Menu has a Collection of Meals

The relations can be depicted as

In one of the pages, for a selected menu I need to display the effective nutrients information calculated based on its constituents (Meals, Recipes, Ingredients and the corresponding nutrients).

As of now am using SQL Server to store the data and I am navigating the chain from my C# code, starting from each meal of the menu and then aggregating the nutrient values.

I think this is not an efficient way as this calculation is being done every time the page is requested and the constituents change occasionally.

I was thinking about a having a background service that maintains a table called MenuNutrients ({MenuId, NutrientId, Value}) and will populate/update this table with the effective nutrients when any of the component (Meal, Recipe, Ingredient) changes.

I feel that a GraphDB would be a good fit for this requirement, but my exposure to NoSQL is limited.

I want to know what are the alternative solutions/approaches to this requirement of displaying the nutrients of a given menu.

Hope my description of the scenario is clear.

答:
It greatly depends on how you do to get the menus and the nutrients initially. Why do you think it will not be efficient?

From what I understand, you go to the DB, get the menu, then go again, get each recipe, then go again and get each ingredient and so on. This is really inefficient, as there are a lot of queries and round-trips to the server, which is the main source of delays. This is known as the SELECT N+1 problem.

What you should do is to fetch all the data in a single query, by using JOINs for all tables from the menu up to the nutrients, so the DB server can use all the relationships and indexes to get the data all at once. The client C# app only processes and display the final result. Doing so is much more efficient than going one by one.

In general, using proper querying techniques and the right indexes for critical queries, relational databases can perform very well on big tables under load.

OwnerDisplayName: Chandu

OwnerDisplayName: Alejandro


答:
Based on the requirements and  architecture, there may be performance improvement options:

You may use indexed views(matrialized) To improve read
performance on RDBMS(Sql server) level.
 Basically, all you
need to do is:
 Create a regular view.
 Create a clustered index
on that view.

Using a cashing mechanism in application level will improve
performance.
 If its possible and feasible to use cashing, having
a cash strategy like singleton lazy cashing will help you.

NoSql:

There are lots of good articles about Sql vs NoSql, like this and this

The parts interests me :

Where to use NoSql:

If your DB is 3NF and you don’t do any joins (you’re just selecting a
  bunch of tables and putting all the objects together, AKA what most
  people do in a web app.

When used be ready to:

You end up writing jobs to do things like joining data from different    tables/collections, something that an RDBMS would do for you automatically.

Your query capabilities with NoSQL are drastically crippled. MongoDb may be the closest thing to SQL but it is still extremely far behind. Trust me. SQL queries are super intuitive, flexible and powerful. NoSql queries are not.

MongoDb queries can retrieve data from only one collection and take    advantage of only one index. And MongoDb is probably one of the most flexible NoSQL databases. In many scenarios, this means more round-trips to the server to find related records. And then you start  de-normalizing data - which means background jobs.

The fact that it is not a relational database means that you won't    have (thought by some to be bad performing) foreign key constrains to  ensure that your data is consistent. I assure you this is eventually is going to create data inconsistencies in your database. Be prepared. Most likely you will start writing processes or checks to keep your database consistent, which will probably not perform better than letting the RDBMS do it for you.

Forget about mature frameworks like hibernate.

Beside deciding to use or not to use NoSql, a helpful article on NOSQL DBMS Comparison and the intention of them could be found here as some of them are focused on high reads, low writes, map-reduce, HA ...

Having a look at the ranking and popularity of them, by category may be usefull.

Title: Nested Entities and calculation on leaf entity property - SQL or NoSQL approach

Body:
I am working on a hobby project called Menu/Recipe Management.

This is how my entities and their relations look like.

A Nutrient has properties Code and Value

An Ingredient has a collection of Nutrients

A Recipe has a Collection of Ingredients and occasionally can have a collection of other recipes

A Meal has a Collection of Recipes and Ingredients

A Menu has a Collection of Meals

The relations can be depicted as

In one of the pages, for a selected menu I need to display the effective nutrients information calculated based on its constituents (Meals, Recipes, Ingredients and the corresponding nutrients).

As of now am using SQL Server to store the data and I am navigating the chain from my C# code, starting from each meal of the menu and then aggregating the nutrient values.

I think this is not an efficient way as this calculation is being done every time the page is requested and the constituents change occasionally.

I was thinking about a having a background service that maintains a table called MenuNutrients ({MenuId, NutrientId, Value}) and will populate/update this table with the effective nutrients when any of the component (Meal, Recipe, Ingredient) changes.

I feel that a GraphDB would be a good fit for this requirement, but my exposure to NoSQL is limited.

I want to know what are the alternative solutions/approaches to this requirement of displaying the nutrients of a given menu.

Hope my description of the scenario is clear.

OwnerDisplayName: Mohsen Heydari


答: It seems like for the experiment or knowledge purpose you want to try Graph-DB but your example is clearly an example of hierarchical data where we can Drill-Down/Up through a node. I am not expert on Graph/Neo DB yet I can see there are not much complexity in the way user/you can request data from this schema. I see the choice of database/schema design is very depends on how and what type of data will be queried against it. As you using SQLSERVER "HierarchyI"D is the best option from my point of view to put this nodes as part of Tree.</p>

OwnerDisplayName: Anup Shah


答:
I fact you do not need to use a graph db, just store required values in one upper level. It is just like storing an Order and OrderItems. you do not have to calculate total each time an order is about to be displayed. Instead you just calculate sum, vat and other stuff and store them with your Order.

```<code>order.Subtotal = order.Items.Sum(item => item.Price);
order.Tax = order.Subtotal * 0.25m; // just a value
order.Total = order.Subtotal + order.Tax;

// fast forward time
var subTotal = order.Items.Sum(item => item.Price);
var tax = subTotal * 0.25m;
var total = subTotal + tax;

if (toal == order.Total) {
   Console.Log("Why the hell I've just re-calculated total?");
}
</code>```

Body:
I fact you do not need to use a graph db, just store required values in one upper level. It is just like storing an Order and OrderItems. you do not have to calculate total each time an order is about to be displayed. Instead you just calculate sum, vat and other stuff and store them with your Order.

order.Subtotal = order.Items.Sum(item => item.Price);
order.Tax = order.Subtotal * 0.25m; // just a value
order.Total = order.Subtotal + order.Tax;

// fast forward time
var subTotal = order.Items.Sum(item => item.Price);
var tax = subTotal * 0.25m;
var total = subTotal + tax;

if (toal == order.Total) {
   Console.Log("Why the hell I've just re-calculated total?");
}

OwnerDisplayName: edokan


答:
It looks like you've spent some time thinking about how best to model the data so that it can be easily updated and queried.  However, now you are at the point where you need to provide access to the data.  Those two things are separate concerns.

You mention reloading the page is causing a new query to the database.  You also mention that the database will occasionally be updated and when it is you want those updates to be displayed on the page in a timely manner.  Your best method to reduce the overhead of queries is not to do them.  If you're running the same queries over and over and getting the same results, why not cache them for a while?  You should be able to implement some caching upstream without modifying the rest of the project.  I would recommend reading about rest.  Regardless if you implement the project in an rdbms or nosql problems with performance of this type are best handled by reducing the number of times you have to go to the database.  Say you have 100 requests for the same recipe in 60 seconds.  If you cache for 60 seconds then you only hit the database once so that's a 100x improvement in performance.  To see that same level of improvement by switching to nosql is going to require a lot more work.

Nosql type systems can be a great solution when you have huge amounts of data or extreme read or write speed requirements.  However that extra performance comes at a cost of throwing out things like referential integrity.

OwnerDisplayName: kzarns


答: My suggestion is to think like a machine and not like a human. It may seems repetitive, but that what machines are good at. One thing that you have to ask yourself is "do I have to retrieve every object, anyway, to display on my page?" If yes, continue what you are doing, compared to data retrieval, cpu cycles are negligible when doing simple math. </p>

OwnerDisplayName: Robert Co


答:
I suggest to look at the Command Query Responsibility Segregation pattern.

Basically instead of create a single model to read and write you can create 2 different models. One optimized for updating and the other optimized for queries (read, reporting, ...). The 2 models are synchronized (usually with eventual consistency) using domain events (see DDD).

I started to study this pattern some months ago and it really changed my way of modelling software. It is not easy because It is a big shift, especially when used with other techniques like DDD and Event Sourcing. But for worth it.

There are many resource available on the net, search for CQRS and DDD (and eventually Event Sourcing).

This pattern can be used on both SQL and noSql.

In your case you can fire an event each time the nutrients are changed to update the read model that is optmized for reading. The read model can be for example a denormalized view of the menu's nutrients (why not using a nosql db for efficient read). You can have multiple read models based on the queries that you need to perform.

There are some implications using this approach but it is very scalable and extensible.

OwnerDisplayName: Davide Icardi


问:
Will JVisualVM degrade application performance?
I have doubts in JVisual VM profiler tool related to performance. I have requirement to implement a JVM Monitoring tool  for my enterpise java application. I have gone through some profiling tools in market but all them are having some kind of agent file which we need include in server startup.

I have a fear that these client agent will degrade my application performance will more. So I have decided to JVisual VM because this profiler tool comes with JDK itself but before implementing JVisualVM, does anybody faces any issues with JVisualVM profiler tool?

As well as, is this safe if I implement in application?

答:
JVisualVM can cause performance problem issues for your application. It all depends on what you're doing with it. For example, if you're monitoring some GC via the JVM's MXBeans it has a fairly low impact (well actually, not that low if you're constantly monitoring). Another example - if you're profiling and recording thread dumps or stack trace dumps then yes you're going to heavily impact the running application as you're asking it to halt at safepoints all of the time whilst you collect information. Generally speaking you only want to do this when you know you have a performance issue happening at that time.

Massive disclaimer - I work for jClarity, we do have a unique approach which doesn't involve an Agent and due to that (and a bunch of other reasons) we are genuinely low impact (we're dead silent most of the time actually) Java/JVM performance monitoring tool. OK, I've said way too much on that.


答:
Two problems with your data encoding scheme that I can see right off the bat are:

How do you represent a Black or Brown one now that Blue is used?

What if you now need to make a 4HBU12 that's designed to fit in a Honda and one for every other make of vehicle?

I typically try to not work special meanings into identifiers for these and other reasons.

However it does somewhat depend on what you intend to do with the number. In my experience it can be useful for users to be able to 'predict' what a product number would be without needing access to a computer.  Also if you have these products floating around with model number labels on them, if the model number is the only real visible indicator of what's in the box, this may again support the exception.

So, while I avoid allowing identifiers to have special hidden meanings, I understand that as with most things, there are exceptions.


答:
Just to ensure we're on the same page, method "hiding" is when a derived class defines a member of the same name as one in the base class (which, if it is a method/property, is not marked virtual/overridable), and when invoked from an instance of the derived class in "derived context", the derived member is used, while if invoked by the same instance in the context of its base class, the base class member is used. This is different from member abstraction/overriding where the base class member expects the derived class to define a replacement, and from scope/visibility modifiers that "hide" a member from consumers outside the desired scope.

The short answer to why it's allowed is that not to do so would force developers to violate several key tenets of object-oriented design.

Here's the longer answer; first, consider the following class structure in an alternate universe where C# doesn't allow member hiding:

```<code>public interface IFoo
{
   string MyFooString {get;}
   int FooMethod();
}

public class Foo:IFoo
{
   public string MyFooString {get{return "Foo";}}
   public int FooMethod() {//incredibly useful code here};
}

public class Bar:Foo
{
   //public new string MyFooString {get{return "Bar";}}
}
</code>```

We want to uncomment the member in Bar, and by so doing, allow Bar to provide a different MyFooString. However, we cannot do so because it would violate out alternate-reality prohibition on member hiding. This particular example would be rife for bugs and is a prime example of why you might want to ban it; for instance, what console output would you get if you did the following?

```<code>Bar myBar = new Bar();
Foo myFoo = myBar;
IFoo myIFoo = myFoo;

Console.WriteLine(myFoo.MyFooString);
Console.WriteLine(myBar.MyFooString);
Console.WriteLine(myIFoo.MyFooString);
</code>```

Off the top of my head, I'm actually not sure whether you'd get "Foo" or "Bar" on that last line. You'd definitely get "Foo" for the first line and "Bar" for the second, even though all three variables reference exactly the same instance with exactly the same state.

So, the language's designers, in our alternate universe, discourage this obviously bad code by preventing property hiding. Now, you as the coder have a genuine need to do exactly this. How do you get around the limitation? Well, one way is to name Bar's property differently:

```<code>public class Bar:Foo
{
   public string MyBarString {get{return "Bar";}}
}
</code>```

Perfectly legal, but it's not the behavior we want. An instance of Bar will always produce "Foo" for the property MyFooString, when we wanted it to produce "Bar". Not only do we have to know that our IFoo is specifically a Bar, we also have to know to use the different accessor.

We could also, quite plausibly, forget the parent-child relationship and implement the interface directly:

```<code>public class Bar:IFoo
{
   public string MyFooString {get{return "Bar";}}
   public int FooMethod() {...}
}
</code>```

For this simple example it's a perfect answer, as long as you only care that Foo and Bar are both IFoos. The usage code a couple examples up would fail to compile because a Bar isn't a Foo and can't be assigned as such. However, if Foo had some useful method "FooMethod" that Bar needed, now you can't inherit that method; you'd either have to clone its code in Bar, or get creative:

```<code>public class Bar:IFoo
{
   public string MyFooString {get{return "Bar";}}
   private readonly theFoo = new Foo();

   public int FooMethod(){return theFoo.FooMethod();}
}
</code>```

This is an obvious hack, and while some implementations of O-O language specs amount to little more than this, conceptually it's wrong; if consumers of Bar need to expose Foo's functionality, Bar should be a Foo, not have a Foo.

Obviously, if we controlled Foo, we can make it virtual, then override it. This is the conceptual best practice in our current universe when a member is expected to be overridden, and would hold in any alternate universe that didn't allow hiding:

```<code>public class Foo:IFoo
{
   public virtual string MyFooString {get{return "Foo";}}
   //...
}

public class Bar:Foo
{
   public override string MyFooString {get{return "Bar";}}
}
</code>```

The problem with this is that virtual member access is, under the hood, relatively more expensive to perform, and so you typically only want to do it when you need to. The lack of hiding, however, forces you to be pessimistic about the members which another coder that doesn't control your source code might want to reimplement; the "best practice" for any non-sealed class would be to make everything virtual unless you specifically didn't want it to be. It also still doesn't give you the exact behavior of hiding; the string will always be "Bar" if the instance is a Bar. Sometimes it is genuinely useful to leverage the layers of hidden state data, based on the level of inheritance at which you're working.

In summary, allowing member hiding is the lesser of these evils. Not having it would generally lead to worse atrocities committed against object-oriented principles than allowing it does.

Body:
Just to ensure we're on the same page, method "hiding" is when a derived class defines a member of the same name as one in the base class (which, if it is a method/property, is not marked virtual/overridable), and when invoked from an instance of the derived class in "derived context", the derived member is used, while if invoked by the same instance in the context of its base class, the base class member is used. This is different from member abstraction/overriding where the base class member expects the derived class to define a replacement, and from scope/visibility modifiers that "hide" a member from consumers outside the desired scope.

The short answer to why it's allowed is that not to do so would force developers to violate several key tenets of object-oriented design.

Here's the longer answer; first, consider the following class structure in an alternate universe where C# doesn't allow member hiding:

public interface IFoo
{
   string MyFooString {get;}
   int FooMethod();
}

public class Foo:IFoo
{
   public string MyFooString {get{return "Foo";}}
   public int FooMethod() {//incredibly useful code here};
}

public class Bar:Foo
{
   //public new string MyFooString {get{return "Bar";}}
}

We want to uncomment the member in Bar, and by so doing, allow Bar to provide a different MyFooString. However, we cannot do so because it would violate out alternate-reality prohibition on member hiding. This particular example would be rife for bugs and is a prime example of why you might want to ban it; for instance, what console output would you get if you did the following?

Bar myBar = new Bar();
Foo myFoo = myBar;
IFoo myIFoo = myFoo;

Console.WriteLine(myFoo.MyFooString);
Console.WriteLine(myBar.MyFooString);
Console.WriteLine(myIFoo.MyFooString);

Off the top of my head, I'm actually not sure whether you'd get "Foo" or "Bar" on that last line. You'd definitely get "Foo" for the first line and "Bar" for the second, even though all three variables reference exactly the same instance with exactly the same state.

So, the language's designers, in our alternate universe, discourage this obviously bad code by preventing property hiding. Now, you as the coder have a genuine need to do exactly this. How do you get around the limitation? Well, one way is to name Bar's property differently:

public class Bar:Foo
{
   public string MyBarString {get{return "Bar";}}
}

Perfectly legal, but it's not the behavior we want. An instance of Bar will always produce "Foo" for the property MyFooString, when we wanted it to produce "Bar". Not only do we have to know that our IFoo is specifically a Bar, we also have to know to use the different accessor.

We could also, quite plausibly, forget the parent-child relationship and implement the interface directly:

public class Bar:IFoo
{
   public string MyFooString {get{return "Bar";}}
   public int FooMethod() {...}
}

For this simple example it's a perfect answer, as long as you only care that Foo and Bar are both IFoos. The usage code a couple examples up would fail to compile because a Bar isn't a Foo and can't be assigned as such. However, if Foo had some useful method "FooMethod" that Bar needed, now you can't inherit that method; you'd either have to clone its code in Bar, or get creative:

public class Bar:IFoo
{
   public string MyFooString {get{return "Bar";}}
   private readonly theFoo = new Foo();

   public int FooMethod(){return theFoo.FooMethod();}
}

This is an obvious hack, and while some implementations of O-O language specs amount to little more than this, conceptually it's wrong; if consumers of Bar need to expose Foo's functionality, Bar should be a Foo, not have a Foo.

Obviously, if we controlled Foo, we can make it virtual, then override it. This is the conceptual best practice in our current universe when a member is expected to be overridden, and would hold in any alternate universe that didn't allow hiding:

public class Foo:IFoo
{
   public virtual string MyFooString {get{return "Foo";}}
   //...
}

public class Bar:Foo
{
   public override string MyFooString {get{return "Bar";}}
}

The problem with this is that virtual member access is, under the hood, relatively more expensive to perform, and so you typically only want to do it when you need to. The lack of hiding, however, forces you to be pessimistic about the members which another coder that doesn't control your source code might want to reimplement; the "best practice" for any non-sealed class would be to make everything virtual unless you specifically didn't want it to be. It also still doesn't give you the exact behavior of hiding; the string will always be "Bar" if the instance is a Bar. Sometimes it is genuinely useful to leverage the layers of hidden state data, based on the level of inheritance at which you're working.

In summary, allowing member hiding is the lesser of these evils. Not having it would generally lead to worse atrocities committed against object-oriented principles than allowing it does.


问:
How can I defend Ruby on Rails against customers' not technical opinion?
My customer, a translations business owner, just told me that he has been reading about Ruby on Rails and told me that "there are more PHP guys around there" and "it seems the community prefers it".
What would you, as software engineer and freelancer, say to the customer to achieve these goals:

Sell

Make him see that the technology is my expert decision and Rails
is as good or better than PHP (+ whatever framework) for this
particular project.

UPDATE:
Thank you all for the suggestions! Tomorrow I've got another meeting with him, let's see how it goes, I will update again :)

UPDATE 2:
Finally I told him to read this thread and the result has been fantastic: He gave me the project and we are going to start right now. Thank you all for the help, you have free beer in my charge if we see someday :)

BTW: I learned the lesson: be as transparent as possible, because if you believe in yourself and your work, there is no question compromising enough to beat you.

regards

答:
Ultimately, PHP programmers are half the cost of Rails programmers, and what you if you find a better job tomorrow? Your boss would be totally screwed and scrambling to find a Rails developer, and that takes time and money since Rails developers are in short supply.

The only reason your boss would agree to it is if it feels like it would make YOU happier, and that by allowing to make the decisions that you want you would be happier working for him, and thus be more productive.

OwnerDisplayName: okeen


问:
When should I increment version number?
I didn't learn programming at school and I do not work as a (professional) developer, hence a lot of basics are not quite clear to me. This question tries to clarify one of them.

Now let's suppose that I have issues #1, #2 and #3 in my Issues Tracker that are set to be corrected/enhanced for version 1.0.0 and that the last (stable) version is 0.9.0.

When should I increment to version 1.0.0 ? When a) just one of the listed above issues is closed or b) when all the issues related to version 1.0 are closed ?

Which one is the right way to do it ? And by the right way, I mean what is currently used in the industry.

答: Version numbers are only relevant for releases, since they are a way for external users to identify a specific build of your software. If you're just busy doing development and not releasing each fix individually, then don't worry about incrementing the release number for every fix. It's not relevant to external users and wastes your own time with extra version bookkeeping.

Title: When should I increment version number?


问:
REST partial bad request
I'm implementing a REST method that allows you to post a list of items. If all data is correct I obviously return a 201 and if all data is incorrect a 400.

What would be an appropriate response code if some items are correct and others are not?

答: Send a 400.  Because the request is bad, even if part of it is good.  It is bad because you can't act on what you've received.</p>

Title: REST partial bad request


问:
Throwing exception from a property when my object state is invalid
I am aware that for the general case, the answer to "should I throw an exception from a property" is "generally don't, but in some special circumstances it is OK to do so". There is a Microsoft guideline which gives this general answer, and also a question on this site.

Now I am faced with a situation which I think may be one of those "special ones" where it is OK. My question: is this really one of those exceptional situations where throwing the exception is superior to the alternatives? Or is it better to use a getter/setter just like in the general case?

My application uses Linq2SQL, and there is the case where my object can be in invalid state because somebody or something wrote nonsense into the database. Consider this toy example:

```<code>[Table(Name="Rectangle")]
public class Rectangle {

[Column(Name="ID", IsPrimaryKey = true, IsDbGenerated = true)]
public int ID {get; set;}

[Column(Name="firstSide")]
public double firstSide {get; set;}

[Column(Name="secondSide")]
public double secondSide {get; set;}

public double sideRatio
{
    get
    {
            return firstSide/secondSide;
    }
}
}
</code>```

Here, I could write code which ensures that my application never writes a Rectangle with a zero-length side into the database. But no matter how bulletproof I make my own code, somebody could open the database with a different application and create an invalid Rectangle, especially one with a 0 for secondSide. (For this example, please forget that it is possible to design the database in a way such that writing a side length of zero into the rectangle table is impossible; my domain model is very complex and there are constraints on model state which cannot be expressed in a relational database).

So, the solution I am gravitating to is to change the getter to:

```<code>get
{
     if(firstSide > 0 && secondSide > 0) return firstSide/secondSide;
     else throw new System.InvalidOperationException("All rectangle sides should have a positive length");
}
</code>```

The reasoning behind not throwing exceptions from properties is that programmers should be able to use them without having to make precautions about catching and handling them them. But in this case, I think that it is OK to continue to use this property without such precautions:

if the exception is thrown because my application wrote a non-zero rectangle side into the database, then this is a serious bug. It cannot and shouldn't be handled in the application, but there should be code which prevents it. It is good that the exception is visibly thrown, because that way the bug is caught.

if the exception is thrown because a different application changed the data in the database, then handling it is outside of the scope of my application. So I can't do anything about it if I catch it.

Is this a good enough reasoning to get over the "avoid" part of the guideline and throw the exception? Or should I turn it into a method after all? Note that in the real code, the properties which can have an invalid state feel less like the result of a calculation, so they are "natural" properties, not methods.

答:
From my point of view this is totally valid. Making sure that valid values are set is important, however if you are still unsure you maybe could move the logic to the constructor of the object (assuming that applies to your environment)

Also check this other post

Is throwing an exception from a property bad form?


答:
I think what you have in this example is a method not a property. When you code it as a method, you could define a range of valid return values (as the case in many .NET methods such as finding string within another, you get -1 if not found), this way the invoking code could determine the result of the operation rather easily.

If your presented example is just for simplification, then the general case would be to validate data before you create the object - That is partially what constructors are for: Where to put validation in domain models.

Anyway, I guess you can't make your object so gentle in such a way that the caller can use them quite safely without anticipating the possibility of an error. Your doco should advice the user that certain objects are to be created with care.

Title: Throwing exception from a property when my object state is invalid

Body:
I am aware that for the general case, the answer to "should I throw an exception from a property" is "generally don't, but in some special circumstances it is OK to do so". There is a Microsoft guideline which gives this general answer, and also a question on this site.

Now I am faced with a situation which I think may be one of those "special ones" where it is OK. My question: is this really one of those exceptional situations where throwing the exception is superior to the alternatives? Or is it better to use a getter/setter just like in the general case?

My application uses Linq2SQL, and there is the case where my object can be in invalid state because somebody or something wrote nonsense into the database. Consider this toy example:

```<code>[Table(Name="Rectangle")]
public class Rectangle {

[Column(Name="ID", IsPrimaryKey = true, IsDbGenerated = true)]
public int ID {get; set;}

[Column(Name="firstSide")]
public double firstSide {get; set;}

[Column(Name="secondSide")]
public double secondSide {get; set;}

public double sideRatio
{
    get
    {
            return firstSide/secondSide;
    }
}
}
</code>```

Here, I could write code which ensures that my application never writes a Rectangle with a zero-length side into the database. But no matter how bulletproof I make my own code, somebody could open the database with a different application and create an invalid Rectangle, especially one with a 0 for secondSide. (For this example, please forget that it is possible to design the database in a way such that writing a side length of zero into the rectangle table is impossible; my domain model is very complex and there are constraints on model state which cannot be expressed in a relational database).

So, the solution I am gravitating to is to change the getter to:

```<code>get
{
     if(firstSide > 0 && secondSide > 0) return firstSide/secondSide;
     else throw new System.InvalidOperationException("All rectangle sides should have a positive length");
}
</code>```

The reasoning behind not throwing exceptions from properties is that programmers should be able to use them without having to make precautions about catching and handling them them. But in this case, I think that it is OK to continue to use this property without such precautions:

if the exception is thrown because my application wrote a non-zero rectangle side into the database, then this is a serious bug. It cannot and shouldn't be handled in the application, but there should be code which prevents it. It is good that the exception is visibly thrown, because that way the bug is caught.

if the exception is thrown because a different application changed the data in the database, then handling it is outside of the scope of my application. So I can't do anything about it if I catch it.

Is this a good enough reasoning to get over the "avoid" part of the guideline and throw the exception? Or should I turn it into a method after all? Note that in the real code, the properties which can have an invalid state feel less like the result of a calculation, so they are "natural" properties, not methods.