问:
SOA, Java EE and data organization
At the company I work for, we're currently splitting up our monolith solution into a number of small services (SOA).

The purpose of this is to make the developers working on each chunk of code (service) more independent, and on the whole to make the code base more manageable. When a change in code is introduced, only one part (i.e. a whole service) needs to be deployed, instead of having to deploy everything. This also helps with testing, there's less of a need to test everything when something is deployed.

Many of the services are small, so we'd like to deploy a number of these services on the same application server, JBoss 7.1 in this case.

As per the SOA philosophy, the independence of each service and the teams working on them is very important. What would be the best way to organize the data?

Use one schema per service

Would you use one datasource per schema in the application server?

Or use one datasource, prefixing all DB object names with the schema name in some transparent manner?

Use a shared schema, but evading any naming collisions by requiring each service to use a distinct prefix for all DB objects

Other options?

Am I maybe thinking this completely wrong here? :)

Edit: Explained why the code base is being split up from a monolith to smaller services.

答:
If you want that this services be really independent different schemas or different databases is a better approach in my opinion. In the future you can move this services to different applications services or split the dtabase into different servers.

But i'm not sure if a partition at the service level (REST or SOAP i suppose) its convenient for ease/independent development. You can make the partition at library level (different .jar for each team), each team can work in one of this .jar that expose some clases (an interface) for others. You have the same independence of development without the complexity of deployment you have with different services.

With the services partition, if a change don't change the service contract with others services or applications you can deploy/test only this service, but if the service change this contract you need to change/deploy/test all the clients of this services, this sounds easy but can easily turn into a nightmare or dependencies.

In my opinion a partition at the service level its ok when is done for deployment needs, you divide you system into small independent deployable pieces because this way you can have dedicated server to some pieces (a subsystem with heavy load for example) or perhaps replicate the same piece in a lot of servers, usually this is necessary for scalability reasons. But for development reasons in my opinion a partition at the library level its easier (i you are looking for ease of development)

Title: SOA, Java EE and data organization


问:
Why do programmers still use "SAFE_DELETE"?
If I had a dime for every time I've seen this macro in use, today I would be coding just for fun:

```<code>#define SAFE_DELETE(p) if ((p) != NULL) { delete (p); (p) = NULL; }
</code>```

Why do programmers insist in keep using this macro when delete checks for null? Is is because it sets the pointer to null at the end? Then why not at least rewrite it and remove the redundant check:

```<code>#define SAFE_DELETE(p) { delete (p); (p) = NULL; }
</code>```

Still, it doesn't seem like a good practice.

答: Let me put it this way.  Does it seem like something C++ would do?  C++ is replete with gotchas and undefined behavior, but in this one instance, it helpfully validates a parameter for you?  Every other "safer" language you know throws an exception if you try to do anything with a null pointer, but the unsafest language you use just handles it cleanly? It's not self-consistent.  People take the safe approach because in nearly every other case, C++ forces the programmer to take the safe approach.  In other words, in C++ code, "Bring Your Own Validation" is idiomatic and habitual.  It doesn't look right when it's missing.

ContentLicense: CC BY-SA 3.0


问:
How does the "Fourth Dimension" work with arrays?
Abstract:

So, as I understand it (although I have a very limited understanding), there are three dimensions that we (usually) work with physically:

The 1st would be represented by a line.

The 2nd would be represented by a square.

The 3rd would be represented by a cube.

Simple enough until we get to the 4th -- It is kinda hard to draw in a 3D space, if you know what I mean...  Some people say that it has something to do with time.

The Question:

Now, though that doesn't all make much sense, that is all great with me.  My question isn't about this, or I'd be asking it on MathSO or PhysicsSO.  My question is: How does the computer handle this with arrays?

I know that you can create 4D, 5D, 6D, etc... arrays in many different programming languages, but I want to know how that works.

答:
...or I'd be asking it on MathSO...

Well, as a matter of fact mathematicians would never (or at least not usually) associate a fourth dimension with anything like time. Nor would they associate the first three ones with anything space like: mathematicians simply define dimension as an abstract property of, typically, a vector space (often this will be generalised to manifolds or even metric spaces). And this abstract definition doesn't care about how many dimensions the physical space we happen to move in has. The concept of dimensions applies to spaces that don't even resemble the physical space. In fact mathematicians (and indeed physicists) very often use infinite-dimensional spaces, such as the Hilbert spaces of quantum mechanics.

With that clarified, let's talk arrays – you don't need to understand vector spaces, since the abstract definition is actually much simpler here.

An (ℓ0 × ℓ1 × ℓ2 × ... × ℓn−1)-sized array (i.e. of dimension n) is simply a collection of ℓ0 ⋅ ℓ1 ⋅ ... ⋅ ℓn−1 numbers (or whatever type of object populates the array). The only difference to a one-dimensional array of that length is that you have a particular useful way of indexing the dimensions seperately, namely

ilin = in−1 + ℓn−1 ⋅ (in−2 + ℓn−1 ⋅ ( ... ℓ2 ⋅ (i1 + ℓ1 ⋅ i0)...))


答:
You don't need to imagine in high spatial dimensions, just think of it as a fern leaf.

The main stalk is your first array, with each branch being an item that it is storing. If we look at a branch this is your second dimension. It has a similar structure of smaller branches coming of it representing its data. These in turn have their own small branches which continues until we get to the tiny leaves representing the data of the inner most or highest dimension array.

You can see this building up if you declare each level with its own name. Here I am reusing each level varible to minimise the code:

```<code>leaf = 2;
tinyBranch = [leaf, leaf, leaf];
middleBranch = [tinyBranch, tinyBranch, tinyBranch];
bigBranch = [middleBranch, middleBranch, middleBranch];
mainBranch = [bigBranch, bigBranch, bigBranch];
</code>```

Title: How does the "Fourth Dimension" work with arrays?

Body:
Abstract:

So, as I understand it (although I have a very limited understanding), there are three dimensions that we (usually) work with physically:

The 1st would be represented by a line.

The 2nd would be represented by a square.

The 3rd would be represented by a cube.

Simple enough until we get to the 4th -- It is kinda hard to draw in a 3D space, if you know what I mean...  Some people say that it has something to do with time.

The Question:

Now, though that doesn't all make much sense, that is all great with me.  My question isn't about this, or I'd be asking it on MathSO or PhysicsSO.  My question is: How does the computer handle this with arrays?

I know that you can create 4D, 5D, 6D, etc... arrays in many different programming languages, but I want to know how that works.

Body:
You don't need to imagine in high spatial dimensions, just think of it as a fern leaf.

The main stalk is your first array, with each branch being an item that it is storing. If we look at a branch this is your second dimension. It has a similar structure of smaller branches coming of it representing its data. These in turn have their own small branches which continues until we get to the tiny leaves representing the data of the inner most or highest dimension array.

You can see this building up if you declare each level with its own name. Here I am reusing each level varible to minimise the code:

leaf = 2;
tinyBranch = [leaf, leaf, leaf];
middleBranch = [tinyBranch, tinyBranch, tinyBranch];
bigBranch = [middleBranch, middleBranch, middleBranch];
mainBranch = [bigBranch, bigBranch, bigBranch];


答:
Imagine doing R&D on some new medical device, a series of sensors that you put along a patient's arms.   You have seven volunteers lined up for testing.   Each sensor reports low-frequency, mid-frequency, and high-frequency readings, which you take once every 100ms for about a minute.

How to store all that data in memory for analysis and plotting?

An array, obviously.   It would look like this (using made-up generic pseudocode):

```<code>npatients = 7
nsensors = 4     // number of sensors on an arm
nchannels = 3
nsamples = 60.0 / 0.1
sensordata = Array[ npatients, nsensors, 2, nchannels, nsamples ]
</code>```

That's a five dimensional array, and there's nothing tricky, mysterious or baffling about it.  There is no reason to try to associate it with 5-dimensional Euclidean space.   To obtain any one data value, we use an expression like

```<code>x = sensordata[6, 5, 1, 2, 338)
</code>```

It just like querying a relational database where you have a record for each data value, with five columns holding patient id, sensor id and so on, and a column with the value.  To get one data point you use five terms in the WHERE:   SELECT value FROM SensorData WHERE (patientid=6) and (sensorid=5) and (arm="left") and (channel="midfreq") and (sampleindex=338).

There is nothing mystical about a database table with five or more columns, is there?

(I'm using 1-based indexing though in real life, 0-based is much more common.)

Note that I'm a bad boy due to hard-coding the number of arms.  If I'm ever given funding to investigate these sensors on an octopus, I'm in trouble!

Body:
Imagine doing R&D on some new medical device, a series of sensors that you put along a patient's arms.   You have seven volunteers lined up for testing.   Each sensor reports low-frequency, mid-frequency, and high-frequency readings, which you take once every 100ms for about a minute.

How to store all that data in memory for analysis and plotting?

An array, obviously.   It would look like this (using made-up generic pseudocode):

npatients = 7
nsensors = 4     // number of sensors on an arm
nchannels = 3
nsamples = 60.0 / 0.1
sensordata = Array[ npatients, nsensors, 2, nchannels, nsamples ]

That's a five dimensional array, and there's nothing tricky, mysterious or baffling about it.  There is no reason to try to associate it with 5-dimensional Euclidean space.   To obtain any one data value, we use an expression like

x = sensordata[6, 5, 1, 2, 338)

It just like querying a relational database where you have a record for each data value, with five columns holding patient id, sensor id and so on, and a column with the value.  To get one data point you use five terms in the WHERE:   SELECT value FROM SensorData WHERE (patientid=6) and (sensorid=5) and (arm="left") and (channel="midfreq") and (sampleindex=338).

There is nothing mystical about a database table with five or more columns, is there?

(I'm using 1-based indexing though in real life, 0-based is much more common.)

Note that I'm a bad boy due to hard-coding the number of arms.  If I'm ever given funding to investigate these sensors on an octopus, I'm in trouble!


问:
Best datatype to store a ternary, or three-state variable
Disclaimer: I know that datatypes are a little bit subjective to which scripting/programming language you are using, I like to write in Python as a matter of preference; though I am happy to hear about any lanugage/implementation.

What is the best datatype to store a three-state variable? Something capable or representing Positive, Neutral, and Negative.

Example: Integers -1, 0, 1.

Pro: Very concise.

Pro: Potentially efficient, Could be stored as a single 2-bit signed integer.

Pro: could be used as a scale, such as a floating point multiplier.

Example 2: 0, null, 1 (or any permutation)

Pro: Non-neutral use case can be binary.

Con: Requires dynamic datatype

Con: Potentially not concise.

Example 3: +,  (empty string), -

Pro: Very concise.

Con: May utilize string logic to determine state.

Pro?: Intuitive graphical representation.

Perhaps there is some clever binary logic that can do something clever that I can't even imagine, perhaps there relies too much considerations of the use case.

Also, are there any considerations when adapting a ternary state to store in a database engine? Like Innodb for reference.

答:
In Microsoft.NET, there is a type "Tuple" which can be used for your requirement.
Visit http://msdn.microsoft.com/en-us/library/system.tuple%28v=vs.110%29.aspx</p>


答:
In programming, arrays are quite easy to implement, but maybe not to understand.

Generally, each level of arrays means to have the content n-fold. That means

int x[4] are 4 blocks, each of them containing an int.

int x[5][4] are 5 blocks, each of them containing an int[4].

int x[3][5][4] are 3 blocks, each of them containing an int[5][4].

int x[2][3][5][4] are 2 blocks, each of them containing an int[3][5][4].

How you are referring to them is up to you, but for better understanding, you have something like

COLUMN for the last one

ROW for the second-last one

PAGE for the third-last one

Till here, I read it somewhere. In order to stay here, we can as well define

BOOK for the fourth-last one

and maybe SHELF for the fifth-last one. (Or, if you prefer, SHELFROW so that we can continue.)

That said, I never saw array with more than 4 or maybe 5 dimensions in "wild life".

This way, you can define and imagine int x[6][2][3][5][4] as a collection of 6 "shelves", each having 2 books, each having 3 pages, each having 5 rows, each having 4 columns.


答:
Apart from an enum which is the obvious and clearest way of expressing this, the system used for interoperable system where a language-specific enum cannot be expressed is the -1/0/1 option.

You may like to try a bitmask though, where 0 means 0, 1 means 'bit 2 set' and 2 means 'bit 3 set' (ie you have 3 bits that can be on or off. As long as you don't define 3, or bits 1 and 2 set, then you're good. This option is best if you think you might need 4 or more flags in the future as 4, 8, 16 etc sets subsequent bits).

All these fit into a single 8-bit datatype so it won't be wasteful of memory or require conversion (as a character based system would, sometimes 16-bit chars are used, sometimes 8-bit depending on your platform).

I wouldn't consider null in any case. Maybe in a database, but only where I could guarantee the system had distinct support for NULLs, and even then it could be error prone if someone didn't explicitly make the distinction and ended up with 0 when it was really null.

Title: Best datatype to store a ternary, or three-state variable

Body:
Disclaimer: I know that datatypes are a little bit subjective to which scripting/programming language you are using, I like to write in Python as a matter of preference; though I am happy to hear about any lanugage/implementation.

What is the best datatype to store a three-state variable? Something capable or representing Positive, Neutral, and Negative.

Example: Integers -1, 0, 1.

Pro: Very concise.

Pro: Potentially efficient, Could be stored as a single 2-bit signed integer.

Pro: could be used as a scale, such as a floating point multiplier.

Example 2: 0, null, 1 (or any permutation)

Pro: Non-neutral use case can be binary.

Con: Requires dynamic datatype

Con: Potentially not concise.

Example 3: +,  (empty string), -

Pro: Very concise.

Con: May utilize string logic to determine state.

Pro?: Intuitive graphical representation.

Perhaps there is some clever binary logic that can do something clever that I can't even imagine, perhaps there relies too much considerations of the use case.

Also, are there any considerations when adapting a ternary state to store in a database engine? Like Innodb for reference.


答:
What is the best datatype to store a three-state variable? Something capable or representing Positive, Neutral, and Negative.

This depends greatly on the language, what you are doing, abstraction level (which also depends on the language and so on).

I mainly use C++ and there are a lot of choices here. The simplest is an enum tribool_state { false_val, true_val, undetermined_val }. This would be sufficient if your usage scenario is a single function returning this type of value.

I would probably use boost::optional<bool> if I wanted to express a boolean result that may be impossible to get (e.g. check if received network data is complete, then process boolean value if that is the case).

I would use boost::tribool if I wanted to express a fuzzy boolean result that supported full tri-state boolean logic (e.g. true || indetermined -> true, false && indetermined -> false, true && indetermined -> indetermined and so on).

Similarly, in python, I would use a set of constants, or a class (again, depending on what kind of semantics/operations I would need in client code):

For example, I would use:

```<code>POSITIVE, INDETERMINED, NEGATIVE = 1, 0, -1
</code>```

if I had a simple case of a function returning one of three results.

If I had instead a full library requiring tri-state boolean logic, I would implement the value type as a class.

Body:
What is the best datatype to store a three-state variable? Something capable or representing Positive, Neutral, and Negative.

This depends greatly on the language, what you are doing, abstraction level (which also depends on the language and so on).

I mainly use C++ and there are a lot of choices here. The simplest is an enum tribool_state { false_val, true_val, undetermined_val }. This would be sufficient if your usage scenario is a single function returning this type of value.

I would probably use boost::optional<bool> if I wanted to express a boolean result that may be impossible to get (e.g. check if received network data is complete, then process boolean value if that is the case).

I would use boost::tribool if I wanted to express a fuzzy boolean result that supported full tri-state boolean logic (e.g. true || indetermined -> true, false && indetermined -> false, true && indetermined -> indetermined and so on).

Similarly, in python, I would use a set of constants, or a class (again, depending on what kind of semantics/operations I would need in client code):

For example, I would use:

POSITIVE, INDETERMINED, NEGATIVE = 1, 0, -1

if I had a simple case of a function returning one of three results.

If I had instead a full library requiring tri-state boolean logic, I would implement the value type as a class.


答:
I do not intend write a clear answer to this question directly; as I commended above, this question is highly dependent on the use-case. In general, all of the listed implementation choices seem appropriate for some different purposes, at different times.

However, I would like to draw your attention to these underlying principles and background knowledge, so that you can make your own informed decision.

http://en.wikipedia.org/wiki/Three-valued_logic

Database "Coalesce" behavior, as discussed in http://en.wikipedia.org/wiki/Null_(SQL)#COALESCE

Fold, or Reduce, the higher-order function, for which "coalesce" is an example:

http://en.wikipedia.org/wiki/Fold_(higher-order_function)

http://en.wikipedia.org/wiki/Short-circuit_evaluation , yet another example

Weighted average, http://en.wikipedia.org/wiki/Weighted_arithmetic_mean , which approaches the problem from an arithmetic way as opposed to the logic-value way.

On a lighter note, also read this joke: "A businessman asks an accountant; what is two plus two?"

Apologies to all accountants and non-accountants. My mentioning of this joke is intended to highlight the liberty of something we're going to define very soon, and the responsibility and consequences (both in a logical sense) that follows.

Question: what is the truth table of a three-valued logic?

Answer:

... got up from his chair, went over to the door, closed it, came back and sat down. Leaning across the desk,

... And pulls out a hand-drawn chart on a piece of paper.

Operation: Logical And - Confidential - Draft for Q3 2014

   FalseTrue Third

FalseFalseFalse?????

True FalseTrue ?????

Third???????????????

... he said in a low voice, "how much what would you like those magic values to be?"

A graphics designer asks a programmer, "Can you give an example of three-valued logic?"

Programmer replies, "Can you give me two colors, which is as black and white as they could be?"

Graphic designer: "so ... black, and white?"

Programmer: "exactly. Now I am going to give a third color - but I'll have to specify it as an ARGB number. I hope you don't mind."

Graphic designer: "well I work with ARGB everyday ..."

Black#FF000000

White#FFFFFFFF

Nothing#00000000

Remark. In the above, Black and White are fully opaque colors. The third color, Nothing, is fully transparent. When mixed together in various ratios, Black and White mixes to become various grays, but mixing in Nothing doesn't change anything.


问:
Is there a real advantage to dynamic languages?
First I want to say Java is the only language I ever used, so please excuse my ignorance on this subject.

Dynamically typed languages allow you to put any value in any variable. So for example you could write the following function (psuedocode):

```<code>void makeItBark(dog){
    dog.bark();
}
</code>```

And you can pass inside it whatever value. As long as the value has a bark() method, the code will run. Otherwise, a runtime exception or something similar is thrown. (Please correct me if I'm wrong about this).

Seemingly, this gives you flexibility.

However, I did some reading on dynamic languages, and what people say is that when designing or writing code in a dynamic language, you think about types and take them into account, just as much as you would in a statically typed language.

So for example when writing the makeItBark() function, you intent for it to only accept 'things that can bark', and you still need to make sure you only pass these kinds of things into it. The only difference is that now the compiler won't tell you when you made a mistake.

Sure, there is one advantage to this approach which is that in static languages, to achieve the 'this function accepts anything that can bark', you'd need to implement an explicit Barker interface. Still, this seems like a minor advantage.

Am I missing something? What am I actually gaining by using a dynamically typed language?

答:
This is a difficult, and quite subjective issue. (And your question may get closed as opinion-based, but that doesn't mean it's a bad question - on the contrary, even thinking about such meta-language questions is a good sign - it's just not well-suited to the Q&A format of this forum.)

Here's my view of it: The point of high-level languages is to restrict what a programmer can do with the computer. This is surprising to many people, since they believe the purpose is to give users more power and achieve more. But since everything you write in Prolog, C++ or List is eventually executed as machine code, it is actually impossible to give the programmer more power than assembly language already provides.

The point of a high-level language is to help the programmer to understand the code they themselves have created better, and to make them more efficient at doing the same thing. A subroutine name is easier to remember than a hexadecimal address. An automatic argument counter is easier to use than a call sequence here you have to get the number of arguments exactly right on your own, with no help. A type system goes further and restricts the kind of arguments you can provide in a given place.

Here is where people's perception differs. Some people (I'm among them) think that as long as your password checking routine is going to expect exactly two arguments anyway, and always a string followed by a numeric id, it's useful to declare this in the code and be automatically reminded if you later forget to follow that rule. Outsourcing such small-scale book-keeping to the compiler helps free your mind for higher-level concerns and makes you better at designing and architecting your system. Therefore, type systems are a net win: they let the computer do what it's good at, and humans do what they're good at.

Others see to quite differently. They dislike being told by a compiler what to do. They dislike the extra up-front effort to decide on the type declaration and to type it. They prefer an exploratory programming style where you write actual business code without having a plan that would tell you exactly which types and arguments to use where. And for the style of programming they use, that may be quite true.

I'm oversimplifying dreadfully here, of course. Type checking is not strictly tied to explicit type declarations; there is also type inference. Programming with routines that actually do take arguments of varying types does allow quite different and very powerful things that would otherwise be impossible, it's just that a lot of people aren't attentive and consistent enough to use such leeway successfully.

In the end, the fact that such different languages are both very popular and show no signs of dying off shows you that people go about programming very differently. I think that programming language features are largely about human factors - what supports the human decision-making process better - and as long as people work very differently, the market will provide very different solutions simultaneously.


问:
Why does C# have much more features than Java?
Please note that this isn't meant to be a Java vs. C# argument. I'm a Java programmer with no C# experience, asking just out of curiosity.

I did some reading on C#, and it seems it has much more features than Java. A number of examples:

Type inference.

dynamic keyword.

Delegates.

Optional parameters.

Lambda and LINQ (I actually have no idea what these are).

Properties.

However Java doesn't really feature anything that C# doesn't have.

My question is: why does C# have much more native features than Java? And why didn't Java add some of these throughout the years, for example Properties or type inference? Do the Java language designers take a more simplistic approach? What is the reason for this?

答:
Several reasons:

C# came later than Java; version 1 was a blatant rip-off of Java 1.4, so it pretty much had everything Java had at that point.

But then C# developed much faster than Java, because it was an exciting new platform (and had an utterly brilliant driver in Anders Hejlsberg, the father of Turbo Pascal). That allowed them to avoid all the mistakes in Java that had become obvious, while adding everything that Java practitioners wished they had.

Meanwhile, Java was hampered by very strict backward compatibility goals and by a somewhat slower pace of development, partly because it tried desperately to gain a reputation for being the standard, enterprisey, reliable, non-surprising solution for the 95% of non-genius programmers. At this they succeeded, perhaps a bit too well.

The result is that Java now has a bit of a feature gap. It does have huge plans for the future, but as usual with this sort of thing everything takes a bit longer than planned.


问:
Which algorithms do I need to look into?
First things first: I need to apologize in advance about the bad choice of title for this question, but I really couldn't come up with something meaningful. I'm actually looking for suggestions as to what this kind of problem in called, so that I can do some research on my own. I will gladly change the title once the suggestions will start to come in.

It's not even a real problem, it's just an exercise I made up in order to explore algorithms I have never had the chance to deal with.

Let's say we want to write a program that will help us to optimize the logistics of an arbitrary number of music bands that have to perform one after the other on the same stage during the same night.

Here's the problem: the bands share players, meaning that any given player can play in more than one band. Were the bands all made of different players, we wouldn't need a program at all, but since all the musicians know each other, they will form many bands with different combinations of them.

What we want to do is to arrange all the bands in such a way that groups that share the greatest number of members will "cluster" together and play one after the other, so that we can minimize the number of musicians involved with each change of band. In other words, the largest number possible of musicians should be already on stage each time a band finishes its set and the next one comes on stage.

Is this just another form of the famous staff rostering / scheduling problem?

Or is it simpler?

I admittedly haven't yet though hard about how one might solve it, it's just a problem that I thought of today.

If I had to take a stab at it, it looks like the problem boils down to figuring out which bands have the most members in common, and sort them accordingly.

But how is this called in CS parlance?

And, is that all there is to it?

Arranging bands by the number of musicians is the only requirement we have. I sense that, if we had to take into account other kinds of constraints like, say, one particular band would really prefer playing at the beginning and another right in the middle, this might turn into a full-fledged scheduling problem.

In its simplest form, though, this appears to be a simple problem but, like I said, I don't know the name of the family of algorithms that would enable me determine which bands have the most musicians in common.

答:
This problem can be interpreted as a variant of the travelling salesman problem, as @randomA has noted in a comment. The bands form the nodes of a graph to be visited, the "distance" between two bands is the number of musicians they don't have in common (the number of musicians which has to change for a band change). The goal is to minimize the total cost of a tour through this graph.

Finding the number of uncommon members is easy: find the number of common members by using standard set intersection (see here) and substract the number 2 times from the sum of the number of members of the 2 bands.

To the question for the class of algorithms: TSP has been attacked by several dozen kinds of algorithms, see the Wikipedia article for some pointers. Some of them deliver an exact solution (but since the general problem is NP-hard, there are no "efficient" algorithms known working for all cases). Others deliver a "good" solution, which is not necessarily the optimium; such heuristics can be much faster.


答:
Dynamically-typed languages are uni-typed

Comparing type systems, there's no advantage in dynamic typing. Dynamic typing is a special case of static typing - it's a statically-typed language where every variable has the same type. You could achieve the same thing in Java (minus conciseness) by making every variable be of type Object, and having "object" values be of type Map<String, Object>:

```<code>void makeItBark(Object dog) {
    Map<String, Object> dogMap = (Map<String, Object>) dog;
    Runnable bark = (Runnable) dogMap.get("bark");
    bark.run();
}
</code>```

So, even without reflection, you can achieve the same effect in just about any statically-typed language, syntactic convenience aside. You're not getting any additional expressive power; on the contrary, you have less expressive power because in a dynamically typed language, you're denied the ability to restrict variables to certain types.

Making a duck bark in a statically-typed language

Moreover, a good statically-typed language will allow you to write code that works with any type that has a bark operation. In Haskell, this is a type class:

```<code>class Barkable a where
    bark :: a -> unit
</code>```

This expresses the constraint that for some type a to be considered Barkable, there must exist a bark function that takes a value of that type and returns nothing.

You can then write generic functions in terms of the Barkable constraint:

```<code>makeItBark :: Barkable a => a -> unit
makeItBark barker = bark (barker)
</code>```

This says that makeItBark will work for any type satisfying Barkable's requirements. This might seem similar to an interface in Java or C# but it has one big advantage - types don't have to specify up front which type classes they satisfy. I can say that type Duck is Barkable at any time, even if Duck is a third party type I didn't write. In fact, it doesn't matter that the writer of Duck didn't write a bark function - I can provide it after-the-fact when I tell the language that Duck satisfies Barkable:

```<code>instance Barkable Duck where
    bark d = quack (punch (d))

makeItBark (aDuck)
</code>```

This says that Ducks can bark, and their bark function is implemented by punching the duck before making it quack. With that out of the way, we can call makeItBark on ducks.

Standard ML and OCaml are even more flexible in that you can satisfy the same type class in more than one way. In these languages I can say that integers can be ordered using the conventional ordering and then turn around and say they're also orderable by divisibility (e.g. 10 > 5 because 10 is divisible by 5). In Haskell you can only instantiate a type class once. (This allows Haskell to automatically know that it's ok to call bark on a duck; in SML or OCaml you have to be explicit about which bark function you want, because there might be more than one.)

Conciseness

Of course, there's syntactical differences. The Python code you presented is far more concise than the Java equivalent I wrote. In practice, that conciseness is a big part of the allure of dynamically-typed languages. But type inference allows you to write code that's just as concise in statically-typed languages, by relieving you of having to explicitly write the types of every variable. A statically-typed language can also provide native support for dynamic typing, removing the verbosity of all the casting and map manipulations (e.g. C#'s dynamic).

Correct but ill-typed programs

To be fair, static typing necessarily rules out some programs that are technically correct even though the type checker can't verify it. For example:

```<code>if this_variable_is_always_true:
    return "some string"
else:
    return 6
</code>```

Most statically-typed languages would reject this if statement, even though the else branch will never occur. In practice it seems no one makes use of this type of code - anything too clever for the type checker will probably make future maintainers of your code curse you and your next of kin. Case in point, someone successfully translated 4 open source Python projects into Haskell which means they weren't doing anything that a good statically-typed language couldn't compile. What's more, the compiler found a couple of type-related bugs that the unit tests weren't catching.

The strongest argument I've seen for dynamic typing is Lisp's macros, since they allow you to arbitrarily extend the language's syntax. However, Typed Racket is a statically-typed dialect of Lisp that has macros, so it seems static typing and macros are not mutually exclusive, though perhaps harder to implement simultaneously.

Apples and Oranges

Finally, don't forget that there's bigger differences in languages than just their type system. Prior to Java 8, doing any kind of functional programming in Java was practically impossible; a simple lambda would require 4 lines of boilerplate anonymous class code. Java also has no support for collection literals (e.g. [1, 2, 3]). There can also be differences in the quality and availability of tooling (IDEs, debuggers), libraries, and community support. When someone claimed to be more productive in Python or Ruby than Java, that feature disparity needs to be taken into account. There's a difference between comparing languages with all batteries included, language cores and type systems.

Title: Is there a real advantage to dynamic languages?

Body:
First I want to say Java is the only language I ever used, so please excuse my ignorance on this subject.

Dynamically typed languages allow you to put any value in any variable. So for example you could write the following function (psuedocode):

```<code>void makeItBark(dog){
    dog.bark();
}
</code>```

And you can pass inside it whatever value. As long as the value has a bark() method, the code will run. Otherwise, a runtime exception or something similar is thrown. (Please correct me if I'm wrong about this).

Seemingly, this gives you flexibility.

However, I did some reading on dynamic languages, and what people say is that when designing or writing code in a dynamic language, you think about types and take them into account, just as much as you would in a statically typed language.

So for example when writing the makeItBark() function, you intent for it to only accept 'things that can bark', and you still need to make sure you only pass these kinds of things into it. The only difference is that now the compiler won't tell you when you made a mistake.

Sure, there is one advantage to this approach which is that in static languages, to achieve the 'this function accepts anything that can bark', you'd need to implement an explicit Barker interface. Still, this seems like a minor advantage.

Am I missing something? What am I actually gaining by using a dynamically typed language?

Body:
Dynamically-typed languages are uni-typed

Comparing type systems, there's no advantage in dynamic typing. Dynamic typing is a special case of static typing - it's a statically-typed language where every variable has the same type. You could achieve the same thing in Java (minus conciseness) by making every variable be of type Object, and having "object" values be of type Map<String, Object>:

void makeItBark(Object dog) {
    Map<String, Object> dogMap = (Map<String, Object>) dog;
    Runnable bark = (Runnable) dogMap.get("bark");
    bark.run();
}

So, even without reflection, you can achieve the same effect in just about any statically-typed language, syntactic convenience aside. You're not getting any additional expressive power; on the contrary, you have less expressive power because in a dynamically typed language, you're denied the ability to restrict variables to certain types.

Making a duck bark in a statically-typed language

Moreover, a good statically-typed language will allow you to write code that works with any type that has a bark operation. In Haskell, this is a type class:

class Barkable a where
    bark :: a -> unit

This expresses the constraint that for some type a to be considered Barkable, there must exist a bark function that takes a value of that type and returns nothing.

You can then write generic functions in terms of the Barkable constraint:

makeItBark :: Barkable a => a -> unit
makeItBark barker = bark (barker)

This says that makeItBark will work for any type satisfying Barkable's requirements. This might seem similar to an interface in Java or C# but it has one big advantage - types don't have to specify up front which type classes they satisfy. I can say that type Duck is Barkable at any time, even if Duck is a third party type I didn't write. In fact, it doesn't matter that the writer of Duck didn't write a bark function - I can provide it after-the-fact when I tell the language that Duck satisfies Barkable:

instance Barkable Duck where
    bark d = quack (punch (d))

makeItBark (aDuck)

This says that Ducks can bark, and their bark function is implemented by punching the duck before making it quack. With that out of the way, we can call makeItBark on ducks.

Standard ML and OCaml are even more flexible in that you can satisfy the same type class in more than one way. In these languages I can say that integers can be ordered using the conventional ordering and then turn around and say they're also orderable by divisibility (e.g. 10 > 5 because 10 is divisible by 5). In Haskell you can only instantiate a type class once. (This allows Haskell to automatically know that it's ok to call bark on a duck; in SML or OCaml you have to be explicit about which bark function you want, because there might be more than one.)

Conciseness

Of course, there's syntactical differences. The Python code you presented is far more concise than the Java equivalent I wrote. In practice, that conciseness is a big part of the allure of dynamically-typed languages. But type inference allows you to write code that's just as concise in statically-typed languages, by relieving you of having to explicitly write the types of every variable. A statically-typed language can also provide native support for dynamic typing, removing the verbosity of all the casting and map manipulations (e.g. C#'s dynamic).

Correct but ill-typed programs

To be fair, static typing necessarily rules out some programs that are technically correct even though the type checker can't verify it. For example:

if this_variable_is_always_true:
    return "some string"
else:
    return 6

Most statically-typed languages would reject this if statement, even though the else branch will never occur. In practice it seems no one makes use of this type of code - anything too clever for the type checker will probably make future maintainers of your code curse you and your next of kin. Case in point, someone successfully translated 4 open source Python projects into Haskell which means they weren't doing anything that a good statically-typed language couldn't compile. What's more, the compiler found a couple of type-related bugs that the unit tests weren't catching.

The strongest argument I've seen for dynamic typing is Lisp's macros, since they allow you to arbitrarily extend the language's syntax. However, Typed Racket is a statically-typed dialect of Lisp that has macros, so it seems static typing and macros are not mutually exclusive, though perhaps harder to implement simultaneously.

Apples and Oranges

Finally, don't forget that there's bigger differences in languages than just their type system. Prior to Java 8, doing any kind of functional programming in Java was practically impossible; a simple lambda would require 4 lines of boilerplate anonymous class code. Java also has no support for collection literals (e.g. [1, 2, 3]). There can also be differences in the quality and availability of tooling (IDEs, debuggers), libraries, and community support. When someone claimed to be more productive in Python or Ruby than Java, that feature disparity needs to be taken into account. There's a difference between comparing languages with all batteries included, language cores and type systems.


问:
Cross Platform Compilation of C++ .exe
I have been asked to re-write an old C/C++ project in C++11. The old project is multi-platform, however, in order to deploy the system on other architectures the current process is to log into a remote service which has all the available target platforms (Red Hat Linux, Umbuntu, Sco Unix et al.) and build the .exe on each platform for distribution.

Is there a way that I can send the user a package that will self-compile on their architecture and build the correct .exe without giving the source code?

I am also open to cross-compilation to get around having to log into separate servers and compile for each platform. How easy or not is it to compile a code for different architectures using a cross compiler?

答:
No. You cannot compile source code without source code.

But you can probably compile or even cross-compile the code locally and send the different compiled files

```<code>my_exe_rhel8
my_exe_ubuntu_x64
</code>```

and the user can then start the correct one.

Ideally, you would package the binaries for those systems already, so for ubuntu, you would prepare a .deb, for red hat, an rpm. That way you can make it much easier for your clients to make sure they get the right versions, have dependencies installed and so on...

As Btrfl noted, you can use VMs to easily create a setup where you can locally compile all binaries on their respective platforms.

Title: Cross Platform Compilation of C++ .exe

Body:
No. You cannot compile source code without source code.

But you can probably compile or even cross-compile the code locally and send the different compiled files

my_exe_rhel8
my_exe_ubuntu_x64

and the user can then start the correct one.

Ideally, you would package the binaries for those systems already, so for ubuntu, you would prepare a .deb, for red hat, an rpm. That way you can make it much easier for your clients to make sure they get the right versions, have dependencies installed and so on...

As Btrfl noted, you can use VMs to easily create a setup where you can locally compile all binaries on their respective platforms.


答: If the executables are not too large, could you package them all together and then distribute an installer that chooses and installs the correct executable? The customer would end up getting a version of the compiled code for each platform, but if you just zip them up into a single file they'd never know the difference. Of course, this might not work if you have space constraints.</p>

Title: Cross Platform Compilation of C++ .exe

Body:
I have been asked to re-write an old C/C++ project in C++11. The old project is multi-platform, however, in order to deploy the system on other architectures the current process is to log into a remote service which has all the available target platforms (Red Hat Linux, Umbuntu, Sco Unix et al.) and build the .exe on each platform for distribution.

Is there a way that I can send the user a package that will self-compile on their architecture and build the correct .exe without giving the source code?

I am also open to cross-compilation to get around having to log into separate servers and compile for each platform. How easy or not is it to compile a code for different architectures using a cross compiler?


答:
Code written using dynamic languages is not coupled to a static type system.  Therefore, this lack of coupling is an advantage compared to poor/inadequate static type systems (although it may be a wash or a disadvantage compared to a great static type system).

Furthermore, for a dynamic language, a static type system doesn't have to be designed, implemented, tested, and maintained.  This could make the implementation simpler compared to a language with a static type system.


答: I suppose you could compile the source to bytecode using LLVM and then produce binaries using that but... its a lot of unknown hassle for something that is easily fixed by changing your position so slightly.</p>

Title: Cross Platform Compilation of C++ .exe


问:
Can XCode work with TFS?
We have been using Team Foundation Server (TFS) for source code management of our solution which contains components for a number of platforms - asp.net, windows & android so far. We now wish to develop iOS apps for the solution but is there any integration possible between XCode and TFS?

What's the best way to use TFS version control with Xcode now that I find out we need to write some iOS apps?

We will also eventually want to have automated builds for a Continuous Integration process

答:
You don't have to use TFS inside Visual Studio, though Microsoft seems to prefer this "buy one, get one for full price plus SQLServer and CALs" solution :)

You can access TFS from an external source control. They have a Windows Explorer plugin that works much like TortoiseXXX products, allowing you to commit and update directly from the filesystem icons.

They also have a command line source control interface for Linux, called "Team Explorer Everywhere", and one that plugs into Eclipse.

It is available to use with Mac OS 10.8+, but on Intel only.

Title: Can XCode work with TFS?


问:
How do programming languages integrate with OS runtimes
For example, Objective-C, Swift and Ruby (i.e. RubyMotion) integrate with the Cocoa framework.

Is this done via linked libraries? I assume they call functions in existing binaries instead of simply recreating some common interface.

答:
By many different methods, not easily reduced to just a few paras. Here are some, in roughly ascending order of abstraction.

The OS implements one or more privileged instructions (trap, syscall, etc). The compiler emits code to translate certain language constructs into those instructions. [ASM]

The OS provides an API in a form compatible with the external interfaces of a specific target language (one that ordinarily provides a mechanism for calling separately compiled translation units). Calls to the OS are indistinguishable from calls to user code. [C]

The OS provides binding layers in a form intended to be compatible with the external interfaces of a specific various target languages. Calls to the OS are similar to calls to user code. [C++, many]

The OS implements an API in a form designed to be callable from various languages but native to none, along with binding layers. This mechanism may also be used for calls to user code. [VB, COM]

The OS provides a 'framework' with an extensive range of capabilities, in lieu of direct access to its services. The compiler usually provides privileged access to the framework, as well as allowing calls that are indistinguishable from user code. [C#, Java, Objective-C*]

These mechanisms are often layered. The calls at a higher layer are translated into calls at a lower layer behind the scenes. Objective-C is an odd one, in providing two different API mechanisms.

At a physical deployment level, the services can be provided by:

Generated code 'traps' directly into the OS, often provided as macros.

OS library code is statically linked (LIB), often provided as 'header' files.

OS library code is dynamically linked using low level mechanisms similar to those used by the OS itself, often via headers and an intervening static lib (DLL, SO).

OS library code is dynamically linked using a mechanism that is part of the API specification, using mechanisms specific to the spec (COM, .NET)

Wherever two disparate technologies (such as Ruby and Cocoa) are able to interact, there is usually a binding layer created by a tool, or manually. Eventually it will use one of the mechanisms above (unless I've missed something).


答:
Yes.

The newer Team Foundation Server versions support Git, so if you set up your TFS repository to use git, you can easily use TFStogether with the build-in git version control tools in Xcode.

Title: Can XCode work with TFS?

Body:
We have been using Team Foundation Server (TFS) for source code management of our solution which contains components for a number of platforms - asp.net, windows & android so far. We now wish to develop iOS apps for the solution but is there any integration possible between XCode and TFS?

What's the best way to use TFS version control with Xcode now that I find out we need to write some iOS apps?

We will also eventually want to have automated builds for a Continuous Integration process


问:
Pros and cons of custom exceptions
This may be an pointless question based on opinion, style, and context but I've been racking my brain trying to decide whether or not to make use of custom exceptions and would love to hear some pros and cons from anyone with experience from both approaches.

For example I'm trying to decide between a custom ObjectNotFoundException vs IllegalArgumentException/IllegalStateException.

(Please note that I am not intending to throw an exception whenever a service cannot find an object with a given identifier. We simply return a null in that case. I'm speaking of when an action is to be performed on an object with a given identifier. In this case, the object in question is expected to exist, so if it does not, we want to throw an exception.)

On one hand, a "GiraffeNotFoundException" is explicit and could be handled differently than a generic IllegalStateException, but then again I suppose that would only matter if such a differentiation is actually required. Another pro is that a custom message for such an exception can be set as the default message for this exception (reducing a bit of redundancy).

On the other hand, it might not be a good idea to clutter the source code with custom exceptions. Also with standard exceptions, the Assert class from spring can be used quite efficiently. There are no intentions of publishing our code as a third party library so there are no pressures for using standard exceptions from that end.

Any other thoughts?

答:
In my experience that depends on how much you need to do once you caught the exception.

If you need to just propagate it further after closing some resources - there is no need to make your own exceptions.

If you need to do some complex work depending on what failed and how - custom exceptions are your friend. If you just use a single IllegalArgumentException - how do you know if it's your DB that failed or network or disk? When looking through logs you will certainly see your very useful debug message, but the code needs that info there and then, and exception type is the perfect tool for it.

Another feature that you haven't mentioned is an exception hierarchy. Different implementations of a method can throw more specific exceptions. It is also easier to catch a group of exceptions by catching their superclass (up to a point of course, catch(Throwable e) is an antipattern).

Lastly: If you make your own hierarchy, you don't have clashes. In the simplest example where you need to provide a meaningful message when an object is not found, it would be pretty embarrassing to give a message saying "Failed to find object: Object cannot be added to list" because it was actually thrown by a List.add(e) method, not your method...

Title: Pros and cons of custom exceptions


问:
In terms of Software, what constitutes a quality control plan for ISO 9001 compliance?
I am bidding on a government contract (my first) and there is a section requesting that I provide a high-level outline of a quality control plan that would ensure that the end product is ISO-9001 compliant.

I don't know much about ISO 9001 so I am certainly doing my own homework and research on this, but thought I would ask the question here in case there happens to be someone very knowledgeable in the area who could provide 5-10 broad bullet points on which I should focus.

答:
In doing my own research on the topic, I found this document published by ISO.  It covers eight quality management principles:

Customer Focus

Leadership

Involvement of people

Process approach

System approach to management

Continual improvement

Factual approach to decision making

Mutually beneficial supplier relationships

The document itself goes into detail about what each tenent means with regards to quality and it's not too hard to apply that to the process of producing a piece of software.


答:
I would add to Kilian's answer that one big difference between Java and C# is that C# designers control not only the language, but also the standard IDE.

Adding something like extension methods and partial classes could be a nightmare in development/control versioning if the IDEs would not properly support it.

Since you are expected to be able to compile Java with your platform of choice (Eclipse, Netbeans, vi + Ant), adding features that break the code (and using these to develop additional extensions like LINQ) is way more complicated than just saying "since IntelliSense will deal with these cases, we need not to worry".

Additionally, sometimes it is worth noting the value of the features instead of its number. For instance, automatic properties are nice and I certainly wish Java supported this, but in the end it only means that you have to write a few more lines of code in Java. Similarly, I find that calling "Events" a feature is somewhat of a misnomer, since they are little more than specially labelled delegates, and just a refined copy of the Observer pattern already used by Java (then again, in Java it needs more explicit coding)

Don't get me wrong, I think C# has introduced several noteworthy innovations, and I wish that someday Oracle big bosses will wake up and launch a true "Java 2" to include some of these, but the gap is not as obvious as your question points.

Title: Why does C# have much more features than Java?

Body:
Please note that this isn't meant to be a Java vs. C# argument. I'm a Java programmer with no C# experience, asking just out of curiosity.

I did some reading on C#, and it seems it has much more features than Java. A number of examples:

Type inference.

dynamic keyword.

Delegates.

Optional parameters.

Lambda and LINQ (I actually have no idea what these are).

Properties.

However Java doesn't really feature anything that C# doesn't have.

My question is: why does C# have much more native features than Java? And why didn't Java add some of these throughout the years, for example Properties or type inference? Do the Java language designers take a more simplistic approach? What is the reason for this?


问:
Pattern to use to relate multiple data sources to different user data widgets
I have an client x server intranet application the basically gets data from the server, format it and send that data to the client for display. At the server we are using  ASP.NET C# running on IIS and at the client we have Javascript widgets. The client x server requests are done through ajax calls.

I have lots (100+) of server objects, that can be shown into 10 different formats in the browser though different graphical widgets.

So, basically we have the following structure:

So, for every server object I need, at nnnWidgetDataGetter objects, to do some data transformation to widget data format to be sent to the client. Every widget can request data from all objects of the server.

Using a normal approach, I would have to write tons of methods, one for each server basic class times each datagetter class.

To avoid writing hundred of methods with similar behaviour, we decided to use a dynamic approach at the DataGetter classes (static classes), where the business object is evaluated at runtime,  data is gathered from this object, formatted and sent to the client.

The problem is that using dynamic object creation and invokation we loose the Intellisense, so the code is turning very big and difficult to understand and maintain.

After a while we found out that we´re not using the correct approach and started thinking about sw patters that would help us solve this.

So we are looking for the correct pattern to solve this issue that would keep a typed structure where Intellisense could work and that avoid us to write hundred of different methods.

We appreciate very much any kind of help.

答:
Patterns could give you a clean design for transforming your server objects into widget data. However they will not prevent you from having to define the strategy for each server object (at best you will remove duplicate code).

May be you could use reflection or attributes to examine your server objects and have a generic generator for populating the desired 'DataGetter'.

OwnerDisplayName: Mendez


问:
Is it a good idea to return a default value if a field in a query cannot be found?
At the place I work we are using a SafeReader class that wraps an IDataReader. One of the 'features' is that if the field you are trying to access wasn't in the query then it just returns a default value.

So I am working with some code that is already in place, but apparently never fully worked as it accesses fields that aren't returned from the stored proc it's calling but it didn't throw any exceptions since the SafeReader kindly returned default values.

I personally don't like this because it means that when there are mistakes in the code (someone forgets to include a field in the query, or perhaps a misspelling) then it's harder to catch.

My question is whether this violates any general 'best practices' of development or object oriented programming ideals? Or does this seem perfectly reasonable?

答:
No, it is not a good idea in general.  It is a very bad idea.

For SOME things, it will be OK to return a default value, but this has to be resolved on a case-by-case basis for that particular thing.  In order be able to do that case-by-case resolution, you have to provide for the case where it is NOT OK to return a default value.

Consider for example an employee badge system.  All employees are by default allowed entry into a particular facility, but only some had access to certain rooms in the facility.  The database is engineered to return the allowed access value when searched by employee number.  It would be tempting in this case to return a default value, and only store those badge numbers that had HIGHER levels of access.  This immediately fails, when Ivan Ivanovitch of the GRU (or whoever the current Russian external spook bureau is called) presents a counterfeit badge with the name "John Johnson" and a bogus employee number, and the badge reader opens the front door for him.  (Yes, I'm giving away my age here.)

My personal experience is that, if your language supports exceptions, you throw an exception in the "not found" case, and FORCE the next guy up to provide an exception handler.  Extensive experience in the industry demonstrates beyond reasonable doubt that the vast majority of C and C++ programmers never check function return codes.  (For that matter, too many of them fail to check pointers for non-null before dereferencing them, even when their employer has hard-and-fast written coding standards requiring such checks.  Yes, that sentence IS written in blood, thank you for asking.)


答:
Think of a one-dimensional array like a chest of drawers:

Each drawer is an index of the array. You can put whatever you want in each drawer, and for many purposes, each drawer will only contain a single item (that's a one-dimensional array).

This chest of drawers is magical though, so it's not limited by physical space. That means that you can put another chest of drawers inside each drawer of the first chest of drawers. The inner chests of drawers can then contain whatever you want. That's a two-dimensional array.

So you can say something like "open up the top drawer of the first chest of drawers, get the chest of drawers out of that drawer, then open up the bottom drawer of that second chest of drawers". That would be like accessing an index of a 2D array: myArray[0][3];

And of course, the chests of drawers inside the outer-most chest of drawers can themselves contain chests of drawers. That's a three-dimensional array.

So, your question is: what's a four-dimensional array? It's a chest of drawers of chests of drawers of chests of drawers of chests of drawers, of course!

It's drawers all the way down.


答:
My question is whether this violates any general 'best practices' of development or object oriented programming ideals?

Sometimes it does. Sometimes, accessing a column that doesn't exist is a clear disconnect between the implied contract that is implemented by the data reader between the calling code and the data source. If it is a clearly a problem, then returning default is violating the "fail early, fail obviously" best practice.

But sometimes it doesn't. In something like a web service, not including a column is done as an implied "not specified" or "use default" (see EmitDefaultValue on DataMember for example). This reduces the payload of web service calls. Having unincluded columns provide a default is much cleaner here since it allows you to obey DRY (don't repeat yourself) rather than checking every single data access call.

Personally, I would avoid having your stuff working with a DataReader or its kin directly where possible. This entire problem exists because you're using a glorified dictionary rather than a real object. That is the real violation of OO ideals. Everything else is a trade off based on your particular situation.

Title: Is it a good idea to return a default value if a field in a query cannot be found?

Body:
At the place I work we are using a SafeReader class that wraps an IDataReader. One of the 'features' is that if the field you are trying to access wasn't in the query then it just returns a default value.

So I am working with some code that is already in place, but apparently never fully worked as it accesses fields that aren't returned from the stored proc it's calling but it didn't throw any exceptions since the SafeReader kindly returned default values.

I personally don't like this because it means that when there are mistakes in the code (someone forgets to include a field in the query, or perhaps a misspelling) then it's harder to catch.

My question is whether this violates any general 'best practices' of development or object oriented programming ideals? Or does this seem perfectly reasonable?


答:
I'm going to preface my answer with the fact that my expertise is in AS9100 and AS9115. AS9100 is the aerospace industry standard that incorporates additional aerospace industry requirements with ISO 9001. The revision of AS9100 that I'm familiar with is AS9100C, which corresponds to ISO9001:2008. There may be minor differences between the two.

The first thing to realize is that a document like ISO9001 or AS9100 is designed for an organization to ensure that their process accounts for things that are important to their customers. It, by itself, is not a process. It's up to an organization to determine exactly how to meet the requirements, based on the organizational environment, objectives, the product, the size of the organization, and more. The emphasis is on considering the value added to customers by process steps, obtaining an effective process and continually improving processes using objective measures, and ultimately understanding customer requirements and meeting them throughout the product life cycle.

At the highest level, the goal is to define organizational processes, how those processes interact, ensure that the processes have the resources and information needed to function, how to measure and control each process, and how to implement actions to correct or prevent problems in the process.

In AS9100, the actual requirements are found in sections 4 through 8. Looking at the outline of ISO9001 on Wikipedia, it looks like the section headers are the same - Quality Management System, Management Responsibility, Resource Management, Product Realization, and Measurement, Analysis and Improvement.

Each section and subsection is a collection of statements, usually "shall" statements. In essence, this document is a requirements specification for an organization to follow.

For example, section 7.3.4 Design and Development Review:

At suitable stages, systematic reviews of design and development shall be performed in accordance with planned arrangements (see 7.3.1)

a) to evaluate the ability of the results of design and development to meet requirements

b) to identify any problems and propose necessary actions

Participants in such reviews shall include representatives of functions concerned with the design and development stage(s) being reviewed. Records of the results of the reviews and any necessary actions shall be maintained (see 4.2.4).

What this says is that you have planned and well-defined reviews during product development. Often, this takes the form of System Requirements Review, Preliminary Design Review, Critical Design Review, and Test Readiness Review, in addition to various peer reviews that are planned and executed during development. These reviews are to ensure that the current work products (derived requirements specifications, models, design documents, source code, test code, etc) are meeting requirements.

This ties to Section 7.3.1 Design and Development Planning, which says that you plan the stages of design and development, ensure that reviews and V&V activities occur at every stage of development and are appropriate given the inputs and outputs, and that you identify who is responsible and has authority over design and development activities. It also ties to 4.2.4 Control of Records which  says that you have documented procedures for identifying, storing, protecting, retrieving, retaining, and dispositioning records and maintain objective evidence of this happening.

Depending on your organization, there may be one or more documents that define the organizational process. In larger organizations, there are often several documents controlled by different people who are knowledgeable in that area. For example, the documents that define the processes for configuration management are controlled by the configuration management team, while the documents for record management are controlled by Document Control, and the engineering documents are controlled by various engineers (often engineering management). However, in a smaller organization, you may only have one or a small handful of documents.

In order to fully understand and implement ISO9001, you'll need to have a copy of the standard to read and follow. Reading it pretty much tells you everything that you'll need to achieve with your process documentation. Once your documentation is in place and you've been executing to it for long enough to begin to produce objective evidence, you can seek an audit and your organization will become compliant to ISO9001.

Title: In terms of Software, what constitutes a quality control plan for ISO 9001 compliance?

Body:
I am bidding on a government contract (my first) and there is a section requesting that I provide a high-level outline of a quality control plan that would ensure that the end product is ISO-9001 compliant.

I don't know much about ISO 9001 so I am certainly doing my own homework and research on this, but thought I would ask the question here in case there happens to be someone very knowledgeable in the area who could provide 5-10 broad bullet points on which I should focus.


问:
Why isn't testing a language a supported feature at the syntax level?
You can find an endless list of blogs, articles and websites promoting the benefits of unit testing your source code. It's almost guaranteed that the developers who programmed the compilers for Java, C++, C# and other typed languages used unit testing to verify their work.

So why then, despite its popularity, is testing absent from the syntax of these languages?

Microsoft introduced LINQ to C#, so why couldn't they also add testing?

I'm not looking to predict what those language changes would be, but to clarify why they are absent to begin with.

As an example: We know that you can write a for loop without the syntax of the for statement. You could use while or if/goto statements. Someone decided a for statement was more efficient and introduced it into a language.

Why hasn't testing followed the same evolution of programming languages?

答:
As with many things, unit testing is best supported at the library level, not the language level.  In particular, C# has numerous Unit Testing libraries available, as well as things that are native to the .NET Framework like  Microsoft.VisualStudio.TestTools.UnitTesting.

Each Unit Testing library has a somewhat different testing philosophy and syntax.  All things being equal, more choices are better than less.  If unit testing were baked into the language, you'd either be locked into the language designer's choices, or you'd be using... a library, and avoiding the language testing features altogether.

Examples

Nunit - General purpose, idiomatically-designed unit testing framework that takes full advantage of C#'s language features.

Moq - Mocking framework that takes full advantage of lambda expressions and expression trees, without a record/playback metaphor.

There are many other choices.  Libraries like Microsoft Fakes can create "shims..." mocks that don't require you to write your classes using interfaces or virtual methods.

Linq isn't a language feature (despite it's name)

Linq is a library feature.  We got a lot of new features in the C# language itself for free, like lambda expressions and extension methods, but the actual implementation of Linq is in the .NET Framework.

There's some syntactic sugar that was added to C# to make linq statements cleaner, but that sugar is not required to use linq.


答:
The only other thing I think you could do is to compile the source to object files, send them the object files, and then have them link the code on their end.  But that just creates more issues than it's worth.

If their compiler can see the source code, they can see the source code.  You could, as some suggested, go from source down to some intermediate representation used by the compiler, but that varies compiler to compiler.

Okay, I see, you're talking about renting machine time for each build.  Cross compilers might help, but I've only seen that done well for the same O/S but on a different architecture (cross compiling a Linux program for PPC on an x86).

Otherwise, in a similar position, I bought a cheap after-market Sun Sparc server to run Sparc builds for Ruby for my clients.  It didn't have to be fast.

Title: Cross Platform Compilation of C++ .exe


答:
It depends if the default value is the right value or not.  I see that pattern way too often when it just happens to be the fastest way to make a particular use case work.  It just makes it harder to debug other use cases down the road.

What do I mean by the default value being the right value?  Well, take an integer field for example.  What should it default to?  If you said you don't know, give yourself a cookie.  If you said zero, that's the right answer for, say, "number of upvotes," but not "seconds until self destruct."

In other words, a correct default value is specific to the field and can be used in all use cases without checking for it.  If I have to pepper my code with if IntegerField == -1, the default not only isn't buying me anything I couldn't get with null, or even better an option or exception, it's actually hurting me because the check is easier to forget and serious errors are easier to ignore.  Why would you forego using the tools which are specifically designed to help programmers in this situation?

However, if I can just write Upvotes += 1 without worrying about if that field has been used before, and know that it will produce the correct result due to a zero default, then the default is buying me something worthwhile.

The problem with the SafeReader class you describe is it is making assumptions about fields it knows nothing about.  I can think of use cases where it might be handy to include defaults for fields not in a query, but they all involve some other form of validating field names, such as against a schema.

I personally consider anything named SafeWhatever a code smell.  The name strikes me as somewhat Orwellian, because the safety is almost always an illusion.  It's like taking down guard rails so a cliff road won't look so dangerous.