答:
It may be helpful to recognize different kinds of "why"--most notably:

Reasons that code which seems overly complex would not work if simplified (e.g. a seemingly-superfluous typecast may be necessary to ensure that code works in some corner cases).

Reasons that some particular simple operation which looks dangerous is actually safe (e.g. "Our fetch-data routine will report a dummy item item past the last as being less than anything else, and the item after that as being greater; any item which should sort before another, in a consistent ascending or descending sequence, will have at least one more (possibly dummy) item following it").

In many cases, a comment of the second type in one part of the code may "match up" with a comment of the first type in another (e.g. "While it would appear this sequence of operations could be simplified, the Fitz routine relies upon the Wongle not being Woozled until after the Bandersnatch has been Blarped.")

Body:
First of all, in this question I'd like to stay away from the polemic on whether source code commenting is good or bad. I'm just trying to understand more clearly what people mean when they talk about comments that tell you WHY, WHAT or HOW.

We often see guidelines like "Comments should tell you WHY; code itself should tell you HOW". It is easy to agree with the statement on an abstract level. However, people usually drop this like a dogma, and leave the room without further explanation. I've seen this used in so many different places and contexts, that it looks like people can agree on the catchphrase, but they seem to be talking about different things entirely.

So, back to the question: if comments should tell you WHY, what is this WHY we are talking about? Is this the reason why that piece of code exists in the first place? Is this what that piece code should be doing? I would really appreciate if someone could give a clear explanation, and then add some good examples (bad examples are not really needed, but fell free to add them for contrast).

There are many questions on whether comments are good or bad, but no one that addresses the specific question of what are good examples of comments that tell you WHY.


问:
Do I need IDs in my database if the records could be identified by the date?
I am writing my first application for Android and will use the SQLite database so will be trying to limit the size as much as possible, but I think the question applies in general to database design.

I am planning to store records that will have text and the date of creation. The app is a stand-alone app, i.e. it will not link to the internet and only one user will be updating it, so there is no chance that there will be more than one entry with a given date.

Does my table still need an ID column? If so, what are the advantages of using the ID as a record identifier as opposed to the Date?

答:
No, you don't strictly need an ID column defined in your schema if you can guarantee that there will never be a duplicate date.

BUT...

...that said, you might as well use it anyways.  The little secret here is that SQLite already has a unique, auto-incrementing ID for every table called ROWID.  If you declare an auto-incrementing integer column in your table as a PK, SQLite will not create a new column - it will simply alias that pre-existing ROWID column.

In SQLite, every row of every table has an 64-bit signed integer
  ROWID. The ROWID for each row is unique among all rows in the same
  table.

You can access the ROWID of an SQLite table using one the
  special column names ROWID, ROWID, or OID. Except if you declare an
  ordinary table column to use one of those special names, then the use
  of that name will refer to the declared column not to the internal
  ROWID.

If a table contains a column of type INTEGER PRIMARY KEY,
  then that column becomes an alias for the ROWID. You can then access
  the ROWID using any of four different names, the original three names
  described above or the name given to the INTEGER PRIMARY KEY column.
  All these names are aliases for one another and work equally well in
  any context.

http://www.sqlite.org/autoinc.html

So, you wont be saving any space by not using an ID column since you are getting one per table whether you want it or not!

ContentLicense: CC BY-SA 3.0


问:
Law of Demeter issues with complex class design
I've posted questions pertaining to this issue before, but they've all tackled different aspects of the problem (Just so you know that I'm not reposting the same question to get more answers).

So, in a nutshell, here is my problem: I have a Timeline class, which has-a Content interface member variable. The Timeline manages WHEN the content gets activated. There is also a Trigger class, which gets a reference to the Timeline class and call the Timeline's play() methods at certain times (like when the user hits spacebar). To organize the Triggers and the Timeline together, they're bound together in a class called Cue (which is the only class the rest of the program cares about).

This leads me to a design problem, since this Cue class is used so often throughout my code, it would be a pain to change it later.

Because of the Law of Demeter, should I not make getters and setters for the timeline and triggers member variables, and instead copy many of their functions into Cue (and just call the functions of the member variables in turn). That way, other classes won't know the inner workings of it?

答:
Because of the LoD, should I not make getters and setters for the timeline and triggers member variables, and instead copy many of their functions into Cue (and just call the functions of the member variables in turn). That way, other classes won't know the inner workings of it?

I would resolve this in one of three ways, depending on the Timeline / Trigger operations that must be performed in the application code.

If the application code needs to be able to call most methods of Timeline and Trigger, then adding delegations to Cue is pointless.  Every addition to Timeline or Trigger will require a corresponding change in Cue, and you will have made the code worse, not better.

If the application code needs to call many methods, but some methods must not be called on objects encapsulated in a Cue, then I might create new interfaces for Timeline and Trigger that expose only those methods, and have Cue publish those interfaces instead of the full interfaces.

If the application code needs perform only a few operations on Timeline and Trigger, or only a few special sequences of operations, then I would add methods do Cue and hide the contained Timeline and Trigger.


问:
Haskell memory efficiency - which is the better approach?
We are implementing a matrix compression library based on a modified two dimensional grammar syntax. Now we have two approaches for our data types -which one will be better in case of memory usage? (we want to compress something ;)).

The grammars contain NonTerminals with exactly 4 Productions or a Terminal on the righthand side. We will need the names of Productions for equality checks and grammar minimization.

The First:

```<code>-- | Type synonym for non-terminal symbols
type NonTerminal = String

-- | Data type for the right hand side of a production
data RightHandSide = DownStep NonTerminal NonTerminal NonTerminal NonTerminal | Terminal Int

-- | Data type for a set of productions
type ProductionMap = Map NonTerminal RightHandSide

data MatrixGrammar = MatrixGrammar {
    -- the start symbol
    startSymbol :: NonTerminal,
    -- productions
    productions :: ProductionMap
    }
</code>```

Here our RightHandSide data saves only String names to determine the next productions, and what we do not know here is how Haskell saves these strings. For example the [[0, 0], [0, 0]] matrix has 2 productions:

```<code>a = Terminal 0
aString = "A"
b = DownStep aString aString aString aString
bString = "B"
productions = Map.FromList [(aString, a), (bString, b)]
</code>```

So the question here is how often is the String "A" really saved? Once in aString, 4 times in b and once in productions or just once in aString and the others just hold "cheaper" references?

The Second:

```<code>data Production = NonTerminal String Production Production Production Production
                | Terminal String Int

type ProductionMap = Map String Production
</code>```

here the term "Terminal" is a bit misleading because its actually the production that has a terminal as right hand side.
The same Matrix:

```<code>a = Terminal "A" 0
b = NonTerminal "B" a a a a
productions = Map.fromList [("A", a), ("B", b)]
</code>```

and the similar question: how often is the production a saved internally by Haskell? Possibly we will drop the names inside the productions if we don't need them, but we are not sure right now about this.

So lets say we have a grammar with about 1000 productions. Which approach will consume less memory?

Finally a question about integers in Haskell: Currently we are planning on having name as Strings. But we could easily switch to integer names because with 1000 productions we will have names with more then 4 chars (which i assume is 32 bit?). How does Haskell handle this. Is an Int always 32 Bit and Integer allocates memory that it really needs?

I also read through this: Devising test of Haskell's value/reference semantics - but I can't figure out what that exactly means for us - I'm more of a imperative java child then good functional programmer :P

答:
You can expand your matrix grammar into an ADT with perfect sharing with a little bit of trickery:

```<code>{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-}

import Data.Map
import Data.Foldable
import Data.Functor
import Data.Traversable

-- | Type synonym for non-terminal symbols
type NonTerminal = String

-- | Data type for the right hand side of a production
data RHS a = DownStep NonTerminal NonTerminal NonTerminal NonTerminal | Terminal a
  deriving (Eq,Ord,Show,Read,Functor, Foldable, Traversable)

data G a = G NonTerminal (Map NonTerminal (RHS a))
  deriving (Eq,Ord,Show,Read,Functor)

data M a = Q (M a) (M a) (M a) (M a) | T a
  deriving (Functor, Foldable, Traversable)

tabulate :: G a -> M a
tabulate (G s pm) = loeb (expand <$> pm) ! s where
  expand (DownStep a11 a12 a21 a22) m = Q (m!a11) (m!a12) (m!a21) (m!a22)
  expand (Terminal a)               _ = T a

loeb :: Functor f => f (f b -> b) -> f b
loeb x = xs where xs = fmap ($xs) x
</code>```

Here I generalized your grammars to allow for any data type, not just Int, and tabulate will take the grammar and expand it by folding it in upon itself using loeb.

loeb is described in an article by Dan Piponi

The resulting expansion as an ADT physically takes no more memory than the original grammar -- in fact it takes a fair bit less, because it doesn't need the extra log-factor for the Map spine, and it doesn't need to store the strings at all.

Unlike the naive expansion, using loeb lets me 'tie the knot' and share the thunks for all occurrences of the same non-terminal.

If you want to dip more into the theory of all of this, we can see that RHS could be turned into a base functor:

```<code>data RHS t nt = Q nt nt nt nt | L t
</code>```

and then my M type is just the fixed point of that Functor.

```<code>M a ~ Mu (RHS a)
</code>```

while G a would consist of a chosen string and a map from strings to (RHS String a).

We can then expand G into M by lookup up the entry in a map of expanded strings lazily.

This is sort of the dual of what is done in the data-reify package, which can take such a base functor, and something like M and recover the moral equivalent of your G from it. They use a different type for the non-terminal names, which is basically just an Int.

```<code>data Graph e = Graph [(Unique, e Unique)] Unique
</code>```

and provide a combinator

```<code>reifyGraph :: MuRef s => s -> IO (Graph (DeRef s))
</code>```

which can be used with an appropriate instance on the above data types to get a graph (MatrixGrammar) out of an arbitrary matrix. It won't do deduplication of identical but separately stored quadrants, but it'll recover all of the sharing that is present in the original graph.

Body:
You can expand your matrix grammar into an ADT with perfect sharing with a little bit of trickery:

{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-}

import Data.Map
import Data.Foldable
import Data.Functor
import Data.Traversable

-- | Type synonym for non-terminal symbols
type NonTerminal = String

-- | Data type for the right hand side of a production
data RHS a = DownStep NonTerminal NonTerminal NonTerminal NonTerminal | Terminal a
  deriving (Eq,Ord,Show,Read,Functor, Foldable, Traversable)

data G a = G NonTerminal (Map NonTerminal (RHS a))
  deriving (Eq,Ord,Show,Read,Functor)

data M a = Q (M a) (M a) (M a) (M a) | T a
  deriving (Functor, Foldable, Traversable)

tabulate :: G a -> M a
tabulate (G s pm) = loeb (expand <$> pm) ! s where
  expand (DownStep a11 a12 a21 a22) m = Q (m!a11) (m!a12) (m!a21) (m!a22)
  expand (Terminal a)               _ = T a

loeb :: Functor f => f (f b -> b) -> f b
loeb x = xs where xs = fmap ($xs) x

Here I generalized your grammars to allow for any data type, not just Int, and tabulate will take the grammar and expand it by folding it in upon itself using loeb.

loeb is described in an article by Dan Piponi

The resulting expansion as an ADT physically takes no more memory than the original grammar -- in fact it takes a fair bit less, because it doesn't need the extra log-factor for the Map spine, and it doesn't need to store the strings at all.

Unlike the naive expansion, using loeb lets me 'tie the knot' and share the thunks for all occurrences of the same non-terminal.

If you want to dip more into the theory of all of this, we can see that RHS could be turned into a base functor:

data RHS t nt = Q nt nt nt nt | L t

and then my M type is just the fixed point of that Functor.

M a ~ Mu (RHS a)

while G a would consist of a chosen string and a map from strings to (RHS String a).

We can then expand G into M by lookup up the entry in a map of expanded strings lazily.

This is sort of the dual of what is done in the data-reify package, which can take such a base functor, and something like M and recover the moral equivalent of your G from it. They use a different type for the non-terminal names, which is basically just an Int.

data Graph e = Graph [(Unique, e Unique)] Unique

and provide a combinator

reifyGraph :: MuRef s => s -> IO (Graph (DeRef s))

which can be used with an appropriate instance on the above data types to get a graph (MatrixGrammar) out of an arbitrary matrix. It won't do deduplication of identical but separately stored quadrants, but it'll recover all of the sharing that is present in the original graph.


问:
Quickly prune and create valid data combinations
I am really struggling with a problem where I need to "prune" down available scenarios to those that a user has defined as valid. Below is a small example of the problem I am trying to solve in .Net (C#). Given the levels / values shown below, the user could pick that there are only a few valid combinations, but if you imagine the levels below being 30-40 levels of data instead of the 5 I have shown, you could see my dilemma. I could need to go through millions to billions of NOT VALID combinations to get to the Valid combinations. There will be cases where all values in the level are applicable and some where only those combinations that the user has specified are.

Current Levels / Values of data:

Users have said that the valid combinations are:

```<code>*Notice all from level 4 are valid
Receiver -> Sony -> 500 -999 -> Retail
Receiver -> Sony -> 1000 - Up -> Retail
</code>```

Results expected from the given 5 levels of information:

```<code>Receiver -> Sony -> 500-999 -> Open -Box -> Retail
Receiver -> Sony -> 500-999 -> New -> Retail
Receiver -> Sony -> 1000-Up -> Open -Box -> Retail
Receiver -> Sony -> 1000-Up -> New -> Retail
</code>```

The things I have tried are performant with small sets, but if I was to have a lot of levels and big gaps in the combinations which wouldn't allow me to prune the valid combinations until I was deep into the levels, I am running into major performance problems. I am obviously not tackling the problem incorrectly.

Any other views or suggestions on tackling the problem would be greatly appreciated.

答:
I assume you have some sort of algorithmic way of determining what valid combinations are (otherwise, you'll have edge cases galore)?

Assuming that's the case, this sounds like a job for a tree. The root node is some arbitrary, empty node that represents the store. Child nodes of the root are each item in your first column. Child nodes of those will be valid nodes from column 2, etc.

I would expect that the tree values would be indexed into the actual db rows (ie. each node in the tree merely contains the primary key of the db element it represents).

That describes something in-memory, but because you mention that there is a size constraint, you will likely have to encode this structure in the DB. A join table that represents the parent/child relationship between items should be sufficient (though, if your "levels" are split across multiple tables, then this would become more difficult).


问:
Should I make a variable readonly when I modify it, but I don't actually set it outside of the constructor?

Background:

I was writing some code. It looked something like this:

```<code>class X
{
    private List<int> _myList = new List<int>();
    public void MyMethod(int x)
    {
        _myList.Add(x);
    }
}
</code>```

R# suggested that I make _myList readonly. I wasn't so sure, as though I technically could make it readonly, I think it would be slightly confusing to do so, as I'm still modifying the list, just not reassigning it. So while I could make it readonly, I'm not sure if I should.

Question:

Should I make variables like this readonly? Why? If not, why does R# suggest this?

答:
You are getting the suggestion because you aren't changing the list itself, just the contents.  If you reassigned the list entirely somewhere it would not be readonly, but because you are simply updating the contents the list itself doesn't change.

This is similar to how you can have a readonly object, but still change values on that object.  The member variable does not change, but the object itself is still mutable.


问:
Convert Algebraic Expression directly into Binary Tree Structure (sans prefix / postfix)
I am looking all over internet to find a logic to convert an Algebraic Expression into a Binary Tree.

I could only find ones where you first convert the algebra expression to postfix or prefix and then convert it to Binary Tree.

I am just curious to know , if its possible.

Any pointers to external links or logical answers to put me in the right direction ?

yes A Syntax Tree

So this expression

```<code>A+(B-C)*D+E*F
</code>```

should be translated into

```<code>              |-(+)-|
              |     |
    |---(*)---|     |---(*)---|
    |         |     |         |
|---(+)---|   D     E         F
|         |
|         |
A   |--( - )--|
    |         |
    B          C
</code>```

答: You are overlooking the forest for the trees. The great majority of parsing algorithms have parse trees as their output, and virtually every treatise on parsing starts with arithmetic expressions as an example. Get any textbook, and chances are you can simply lift an algorithm from their examples, whether it's a recursive-descent parser, an LR parser or something else.</p>


问:
How to implement interactive programs (like games/simulations) using logic programming?
I've heard that logic programming can serve as a general-purpose alternative to other programming paradigms such as OO or functional programming. (Since Prolog is  Turing-complete, this must be so!)

However, I'm having trouble seeing how one would implement an interactive program, like a simple, graphical console game in Prolog or a similar language. You have facts, rules which can derive more facts, and queries which retrieve facts. It's easy to see how you can use those basic elements to create something like a sudoku solver. But how about Pac-man, or more simply, Pong?

PLEASE NOTE: I'm not looking for low-level details, but a conceptual overview. (For example: in high-level terms, how would you handle I/O? How would you store the game state? How would you implement something like a "main loop"? How would you measure and respond to the passing of time?)

答:
Tracking game state is no different than tracking state in any other Prolog program. You define facts and then use them to make decisions. It's pretty old, but the article Exploring Prolog : Adventures, Objects, Animals, and Taxes does a good job of explaining how this might work in a game. Summarized from the article:

```<code>% Set up - you start in a house
location(you, house).

% Move to a new location.
goto(X) :-
    location(you, L), % Read your current location into L
    connect(L, X), % Check if you can reach the new location X from L
    retract( location(you, L) ), % Remove the old location fact
    assert( location(you, X) ). % Add a new location fact. You are in X now.
    write($ You are in the $), write(X), nl.
</code>```

Beyond that, you need a graphics and IO library. There may be commercial Prolog distributions that include them. I'm most familiar with SWI Prolog, so I'll suggest plOpenGL as a starting point. Not only does it give you access to OpenGL's rendering capabilities, it also includes bindings for mouse and keyboard events. For example, to handle a press of the Escape key, you define a keyboard rule like so:

```<code>% 27 is ASCII Code for Escape
keyboard(27,_,_) :-
    write('Escape key was pressed...'),nl.
</code>```

Take a look at plOpenGL's moving light example for a few more details and an example of handling mouse movement.

If you use a graphics library, it will likely handle the game loop for you. Basically, you invert control to the library and provide rules to be executed when appropriate: set up, repainting, IO events, etc. If you want to limit FPS or run code conditionally based on time, you can track elapsed time using time/date predicates and make decisions accordingly.

There are many Prolog flavors, so this is certainly not the only way to build a game. Different distributions and related languages will use different libraries/bindings that may encourage different approaches. In addition, polyglot programmers might encourage you to use a more "graphics friendly" host language/runtime to manage rendering and IO while using Prolog to model game entity behaviors and decision making.

Body:
Tracking game state is no different than tracking state in any other Prolog program. You define facts and then use them to make decisions. It's pretty old, but the article Exploring Prolog : Adventures, Objects, Animals, and Taxes does a good job of explaining how this might work in a game. Summarized from the article:

% Set up - you start in a house
location(you, house).

% Move to a new location.
goto(X) :-
    location(you, L), % Read your current location into L
    connect(L, X), % Check if you can reach the new location X from L
    retract( location(you, L) ), % Remove the old location fact
    assert( location(you, X) ). % Add a new location fact. You are in X now.
    write($ You are in the $), write(X), nl.

Beyond that, you need a graphics and IO library. There may be commercial Prolog distributions that include them. I'm most familiar with SWI Prolog, so I'll suggest plOpenGL as a starting point. Not only does it give you access to OpenGL's rendering capabilities, it also includes bindings for mouse and keyboard events. For example, to handle a press of the Escape key, you define a keyboard rule like so:

% 27 is ASCII Code for Escape
keyboard(27,_,_) :-
    write('Escape key was pressed...'),nl.

Take a look at plOpenGL's moving light example for a few more details and an example of handling mouse movement.

If you use a graphics library, it will likely handle the game loop for you. Basically, you invert control to the library and provide rules to be executed when appropriate: set up, repainting, IO events, etc. If you want to limit FPS or run code conditionally based on time, you can track elapsed time using time/date predicates and make decisions accordingly.

There are many Prolog flavors, so this is certainly not the only way to build a game. Different distributions and related languages will use different libraries/bindings that may encourage different approaches. In addition, polyglot programmers might encourage you to use a more "graphics friendly" host language/runtime to manage rendering and IO while using Prolog to model game entity behaviors and decision making.


答:
If you think it's confusing, as you've said, then don't do it.  If other members of your team that are likely going to need to work with this code don't have the difference between references and objects sufficiently ingrained in their brains then don't do it to avoid confusing them.  If you all understand the concepts so effectively that this isn't confusing at all, and you think it might benefit you to convey that the reference to the list isn't changed, then mark it as read only.

Keep in mind that your team doesn't always need to do the same thing as everyone else on the planet.  Do what works best for the people who will actually need to touch this code (with some basic considerations for people who will need to touch the code that aren't yet on the team.)

Title: Should I make a variable readonly when I modify it, but I don't actually set it outside of the constructor?

Body:
Background:

I was writing some code. It looked something like this:

```<code>class X
{
    private List<int> _myList = new List<int>();
    public void MyMethod(int x)
    {
        _myList.Add(x);
    }
}
</code>```

R# suggested that I make _myList readonly. I wasn't so sure, as though I technically could make it readonly, I think it would be slightly confusing to do so, as I'm still modifying the list, just not reassigning it. So while I could make it readonly, I'm not sure if I should.

Question:

Should I make variables like this readonly? Why? If not, why does R# suggest this?


答:
I say yes, add the readonly. For two reasons:

if you (or a teammate in the future) try to reassign to that variable in a later method, it will give you a compile-time error. R# will note the error even earlier. So, it's best thought of as an indicator and enforcer of intent. Even if you intend to reassign it later, it forces you to think about the design a little more and will not hurt much to remove it.

the compiler and/or JITter can use the single-assignment knowledge conveyed to potentially provide optimizations. Not guaranteed, but I do it for the first reason - this is a possible bonus.


问:
I feel lost among the various web technologies and I'm looking for pointers
In the last 3-5 months I was thinking about which web programming language I should use. PHP? Ruby? C#? Python? Perl? And you know what? Every time I keep changing my mind like crazy! I learn some things about each one of them and then move to another.  Now I'm totally lost, totally lost guys. :)

What I want form you is to help me to decide, not to decide for me, and give me some recommendations. It would be more than helpful if you can tell me a short story about yourself, how you got started, where you are now and what web programming technologies you are using.

答:
Personally, I decided to use Silverlight because I've already done a fair bit of desktop development using C#/WinForms so I have more carry-over knowledge from my current/previous domain.

That, and there's other options after the project is finished:

Web: ASP.NET MVC/2, Silverlight

Games: XNA

Phone (Win Phone 7): Silverlight, XNA

Desktop: .NET/WPF/WinForms

Server: Console, windows services, wcf services

As much as I complain that there's too much to know/learn, it also means options to move from a consistent base knowledge.

ContentLicense: CC BY-SA 2.5


问:
Does IE have more strict Javascript parsing than Chrome?
This is not meant to start a religio-technical browser war - I still prefer Chrome, at least for now, but:

Because of a perhaps Chrome-related problem with my web page (see also), I temporarily switched to IE (10) to see if it would also view the time value as invalid.

However, I didn't even get to that point - IE stopped me in my tracks before I could get there; but I found that IE was right - it is more particular/precise in validating my code. For example, I got this from IE:

```<code>SCRIPT5007: The value of the property '$' is null or undefined, not a Function object
</code>```

...which was referring to this:

答:
before you call $, which is the variable for jquery, you need to let the page load first, then call any jquery object:

$(document).ready(function () {
    $("body").css("background-color", "#405DA7");
});
```

<p>"Javascript statements are executed by the browser immediately and not when the DOM is ready." - See Pro jquery by Adam Freeman [http://www.apress.com/9781430240952] page 107 </p>

<p>If you run the following In Firefox, Chrome and IE, it works. The background changes</p>

<pre class="lang-html prettyprint-override"><code><html>
<head>
    <title>Test</title>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("body").css("background-color", "#405DA7");
        });
    </script>
</head>
<body>

    <p>Test</p>
</body>
</html>
</code>```

If you remove the line:

        $(document).ready(function () {..}
```

<p>and only have:</p>

<pre class="lang-js prettyprint-override"><code>        $("body").css("background-color", "#405DA7");
</code>```

It will not work.

ContentLicense: CC BY-SA 4.0

Body:
before you call $, which is the variable for jquery, you need to let the page load first, then call any jquery object:

$(document).ready(function () {
    $("body").css("background-color", "#405DA7");
});

"Javascript statements are executed by the browser immediately and not when the DOM is ready." - See Pro jquery by Adam Freeman [http://www.apress.com/9781430240952] page 107

If you run the following In Firefox, Chrome and IE, it works. The background changes

<html>
<head>
    <title>Test</title>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("body").css("background-color", "#405DA7");
        });
    </script>
</head>
<body>

    <p>Test</p>
</body>
</html>

If you remove the line:

        $(document).ready(function () {..}

and only have:

        $("body").css("background-color", "#405DA7");

It will not work.


问:
What are examples of comments that tell you why instead of how or what?
First of all, in this question I'd like to stay away from the polemic on whether source code commenting is good or bad. I'm just trying to understand more clearly what people mean when they talk about comments that tell you WHY, WHAT or HOW.

We often see guidelines like "Comments should tell you WHY; code itself should tell you HOW". It is easy to agree with the statement on an abstract level. However, people usually drop this like a dogma, and leave the room without further explanation. I've seen this used in so many different places and contexts, that it looks like people can agree on the catchphrase, but they seem to be talking about different things entirely.

So, back to the question: if comments should tell you WHY, what is this WHY we are talking about? Is this the reason why that piece of code exists in the first place? Is this what that piece code should be doing? I would really appreciate if someone could give a clear explanation, and then add some good examples (bad examples are not really needed, but fell free to add them for contrast).

There are many questions on whether comments are good or bad, but no one that addresses the specific question of what are good examples of comments that tell you WHY.

答:
Having this issue right now wading through stored procedures and views against a complex and somewhat convoluted data model.

We have (numerous) made up selects like "Case when x.account is not null and x.address in (select address from fedex) then x.account else y.account end" throughout and productivity is expected though there is not time at all to read all the source code. And this example kindof sort of makes sense sort of, but it's still inscrutable.

The comments explaining why if in fedex then x and if not then y -- sheds light on the entire system and when we read enough of them we start to get it. And this is over simplified and there are hundreds or thousands of similar statements.My heart glows warmly towards whoever the kind dev from 2007 was who put in those why's.

So yeah, complex convoluted data models and hairy veiws and stored procedure with multiple validly named paths, please for the love of G-d tell us why.


答:
On top of Corbin's answer: In general state can be stored/retrieved in Prolog using the assert/retract predicates. But there are many non-standard options like saving into RDF, XML, relational databases, etc. If you want GUI one example is XPCE offered by SWI-Prolog.

Note that although implementing a complete game in Logic Programming is a good exercise, in practice its performance would be inadequate and that's why vendors like SWI-Prolog offer bindings to lower-level languages (eg. Java, C++, etc.). Even implementing a simple Sudoku solver requires using CLP libraries.

Title: How to implement interactive programs (like games/simulations) using logic programming?

Body:
I've heard that logic programming can serve as a general-purpose alternative to other programming paradigms such as OO or functional programming. (Since Prolog is  Turing-complete, this must be so!)

However, I'm having trouble seeing how one would implement an interactive program, like a simple, graphical console game in Prolog or a similar language. You have facts, rules which can derive more facts, and queries which retrieve facts. It's easy to see how you can use those basic elements to create something like a sudoku solver. But how about Pac-man, or more simply, Pong?

PLEASE NOTE: I'm not looking for low-level details, but a conceptual overview. (For example: in high-level terms, how would you handle I/O? How would you store the game state? How would you implement something like a "main loop"? How would you measure and respond to the passing of time?)


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

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

答:
One major feature of an application our company developed was the ability to search large amounts of documents by the full-text of the document. A competitor made the following claim in a marketing presentation to one of our clients,

Our search technology is superior because it doesn't just search the text of the documents,
  it also searches the 'bits and bytes' of the actual file in binary form.

They gave a ridiculous example of how the decimal ascii repersentations of the words "boot" and "boat" were much less similar than the same words in binary form, when you compared the actual numeric digits in the representation. So searching based on the 1's and 0's more accurately reflected how similar those two words appeared visually, and thus improved recall.

Naturally I was tasked with researching this technique, which I assume was the result of a marketing guy completely misunderstanding a programmer somewhere, and drafting a response that we could include in our proposal.


问:
In what order are rows fetched absent ORDER BY clause?
One programmer is testing and comparing the same application which uses the same database structure, and the same data, only in two separate databases, one with Oracle 8 and one with Oracle 9.

The app runs a query with no ORDER BY clause.

He claims that the ORDER-BY-less query should return the rows in the same order in both databases.

I tell him there's no warranty of the same row order unless you explicity provide an ORDER BY clause.

The database has the same indexes and keys. But the explain plan shows that in one of the databases the engine is using the key of one of the joined tables whereas in the other database it's using another's.

He insinuates that the two DB environtments are not equal, which is so because they have different statistics, different rdbms engines, etc., but not because I failed to replicate every index the original database has.

I tell him he must explicity provide an ORDER BY clause if the order is really that important.

The question

So I can explain him better:

In what order does a query fetch rows when you don't explicity provide an ORDER BY clause, and why doesn't that query return the rows in the same order ?

答:
From Wikipedia:

The ORDER BY clause identifies which columns are used to sort the
  resulting data, and in which direction they should be sorted (options
  are ascending or descending). Without an ORDER BY clause, the order of
  rows returned by an SQL query is undefined.

So it's undefined.

The SQL specification doesn't state the specific order that records are to be returned, so it's going to be implementation dependent.

With no indexes on the table, the sensible order would be the order in which the records were inserted.  With a Primary Key defined, the sensible order would be the order of the Primary Key.  But since the ANSI spec doesn't require a specific order, it's up to the vendor, and their sensibilities may differ from yours or mine.

Since the order is not stated in the specification, it is unwise to rely on the behavior of a particular vendor's implementation, since it can vary from one vendor to another, and the vendor may change the order any time they wish, without warning.

As you said, just include the ORDER BY clause, if order is important.


问:
What does IE mean by saying "'console' is undefined"?
I like IE's persnicketiness (the debugging tools that take you right to your code is even more user-friendly than what I've found in F12 Chrome Dev Tools), but why does it say, "'console' is undefined" re: this line of jQjuery:

```<code>console.log("entered submit button click");
</code>```

How could console be undefined? Neither Chrome nor Firefox complain about it...

And ironically, IE shows me this error message where? In the "Console" tab! Shirley it couldn't be case-sensitive, and it expects "Console.log"?

BTW and anyway, I'm impressed with IE's F12 tools; I wonder if it's "The Avis Effect" at work - they were #5 (among Browsers) and have thus begun fighting like a rabid wolverine to claw and scratch their way upwards?

答:
As mentioned the console object is not guaranteed to exist in IE.  It only gets "created" when the debug tools are opened.

I wrote a small lib that handles this and other cross browser console issues such as console.time support in IE and console.profile inconsistencies.

https://github.com/pllee/counsell

For example counsell.time will never throw an error in IE, with or without the debug tools open.


问:
changing value of a private member of a class in c++ without using member or friend function
Using pointer, I am able to modify the private value of the class in the code below.

Does it violate the C++ concept that private member can only be modified by member or friend functions?

```<code>#include<iostream>
using namespace std;

class demo
{
        private: int info;

        public:
                 demo()
                 {
                         info=10;
                 }

                 void print_info()
                 {
                       cout<<info;
                 }
};

int main()
{

     demo ob;
     int* ptr=(int*)&ob;

     *ptr=20;

     ob.print_info();

     return 0;
}
</code>```

答:
The exact posted code has has defined behavior under c++11, since demo is a standard-layout class and info (the data member) is accessed as a compatible type, but it is bad style.

Standard-layout class must:

Have the same access control for all data members

Have no virtual functions

Only inherit from standard-layout classes

At most one class in its class hierarchy has data members

Has no data members with the same type as any in the class hierarchy

This text is simplified from 9.7 of the draft standard. In my terminology, class hierarchy includes the class itself, and data members only covers non-static data members.

Accessing the data member with an incompatible type would cause undefined behavior, as always. For instance short is undefined, but char and int is defined.

In short, such access is defined if the class is standard-layout . So be VERY careful. You can check if a type is standard-layout with std::is_standard_layout


问:
Compiler design decision for dynamic method invocation
I asked about Compiler interpretation of overriding vs overloading on StackOverflow, and got good answers, but this led me to another question that I'm not sure is appropriate for SO, but I think is for here.

One should read the original question and accepted answer, but perhaps it's understandable just by looking at the code below:

```<code>public static void whatIs(Circle s)
{
    System.out.println("Circle");
}
public static void whatIs(Square s)
{
    System.out.println("Square");
}
</code>```

and we attempt to call,

```<code>whatIs(shapes[0]); //array of Shape objects (interface implemented by Circle,Square)
whatIs(shapes[1]);
</code>```

we will get two errors (one for Square and one for Circle) indicating that:

method Driver.whatIs(Square) is not applicable

actual argument Shape cannot be converted to Square by method invocation conversion

As is suggested in my question, using instanceof can give the desired results, and as the answered suggested:

The compiler could auto generate code like

```<code>if (shapes[0] instanceof Circle)
{
    whatIs((Circle) shapes[0]); //prints "Circle"
}
</code>```

but, it does not.  Just to be clear, I know one can use an abstract class instead of an interface to achieve similar functionality, nonetheless, does anyone know why the Java compiler won't automatically do this for you?  I'm not a compilers guy, but I have a feeling that this is not an opinion based question.  I assume that there is a good reason for this decision.

答:
Remember: Java does not do "dynamic method invocation", there is nothing dynamic about the invocation of an overload or override, these are invocations decided at compile-time.

The issue you're seeing is due to the fact that a base class lacks details of sub classes, thus the compiler cannot automatically convert a base class at compile time to any given sub class (without an explicit forced cast to ensure it's converted with the possibility of error if you use the forced cast on the wrong object).

I know that doesn't seem like the answer, but you have to recognize what the compiler's actually doing. When you say:

```<code>Shape someShape = functionThatReturnsACircle();
whatIs(someShape);
</code>```

The compiler reads that you have an object of type Shape named someShape, and therefore it writes out IL to call the generic whatIs(Shape shape). It can't know until runtime that someShape will be a Circle. Even if you use new Circle() the variable could be reassigned to a Square before the whatIs call, it really can't know the subclass that will live in someShape. So at compile time it compiles it to call the only one it knows has a matching signature, which is the whatIs that takes a base class.

Granted at runtime it will know that the in-memory object is in fact a Circle, but the compiler already wrote out IL/ByteCode/MachineCode/what-have-you that instructs to call the base class form of whatIs, so what's done is already done there.

As for:

actual argument Shape cannot be converted to Square by method invocation conversion

Now that speaks to what I said at the top of this answer. The compiler simply cannot write out instructions to convert someShape to a Circle because as stipulated earlier, it does not have any certainty that it is a Circle. Further more, you cannot just naturally up convert a base class to a more specific class because for instance, a Shape only has getArea() and does not have Radius so there's no way to construct the Radius property's value automatically based on the available information in the base class.

Body:
Remember: Java does not do "dynamic method invocation", there is nothing dynamic about the invocation of an overload or override, these are invocations decided at compile-time.

The issue you're seeing is due to the fact that a base class lacks details of sub classes, thus the compiler cannot automatically convert a base class at compile time to any given sub class (without an explicit forced cast to ensure it's converted with the possibility of error if you use the forced cast on the wrong object).

I know that doesn't seem like the answer, but you have to recognize what the compiler's actually doing. When you say:

Shape someShape = functionThatReturnsACircle();
whatIs(someShape);

The compiler reads that you have an object of type Shape named someShape, and therefore it writes out IL to call the generic whatIs(Shape shape). It can't know until runtime that someShape will be a Circle. Even if you use new Circle() the variable could be reassigned to a Square before the whatIs call, it really can't know the subclass that will live in someShape. So at compile time it compiles it to call the only one it knows has a matching signature, which is the whatIs that takes a base class.

Granted at runtime it will know that the in-memory object is in fact a Circle, but the compiler already wrote out IL/ByteCode/MachineCode/what-have-you that instructs to call the base class form of whatIs, so what's done is already done there.

As for:

actual argument Shape cannot be converted to Square by method invocation conversion

Now that speaks to what I said at the top of this answer. The compiler simply cannot write out instructions to convert someShape to a Circle because as stipulated earlier, it does not have any certainty that it is a Circle. Further more, you cannot just naturally up convert a base class to a more specific class because for instance, a Shape only has getArea() and does not have Radius so there's no way to construct the Radius property's value automatically based on the available information in the base class.


问:
Why use protocol, not call the method directly?
I was asked this question in an interview. For eg: UITableviewDelegate protocol has CellForRowAtIndexpath. Why make it a delegate method in a protocol not a method in the UITableView class and call it directly?

答:
By not putting the -[tableView:cellForRowAtIndexPath:] in the UITableViewController class, one can write another class to use as datasource (cellForRow is in the datasource). This can be useful for code organization or code-reuse.

By putting it in a protocol, the class can have any superclass: useful when subclassing your own datasources or delegates. It also gives to ability to add in the datasource anywhere you want, even in the app delegate or a view subclass (don't do this).


答:
Here's what Apple have to say about it:

Delegation

Delegation is a mechanism by which a host object embeds a weak reference (weak in the sense that it’s a simple pointer reference, unretained) to another object—its delegate—and periodically sends messages to the delegate when it requires its input for a task. The host object is generally an “off-the-shelf” framework object (such as an NSWindow or NSXMLParser object) that is seeking to accomplish something, but can only do so in a generic fashion. The delegate, which is almost always an instance of a custom class, acts in coordination with the host object, supplying program-specific behavior at certain points in the task. Thus delegation makes it possible to modify or extend the behavior of another object without the need for subclassing.

So, in this case, you want to supply a custom-built cell, but you don't want to subclass the UITableView to do so.  Any class that conforms to the protocol can supply the custom cell.

Title: Why use protocol, not call the method directly?

Body: I was asked this question in an interview. For eg: UITableviewDelegate protocol has CellForRowAtIndexpath. Why make it a delegate method in a protocol not a method in the UITableView class and call it directly?


问:
How to see what parts of your code are run most often?
I would like to be able to see what code in thousands of lines of source code is run most often and takes the longest. The purpose of this would be for optimization.

Being able to see what parts of the code are run most often is important for optimization, because those parts are where I should focus to speed up. At the same time of course, some code is run very often but takes virtually no time, so its also important to be able to see what code takes the longest.

I guess the best of both worlds would be a program that adds up the amount of time a piece of code takes, including ALL of the times it was run (therefor figuring out what slows down your code most overall). Is there a kind of tools for this?

答:
What you are looking for is profiling:

In software engineering, profiling ("program profiling", "software profiling") is a form of dynamic program analysis that measures, for example, the space (memory) or time complexity of a program, the usage of particular instructions, or frequency and duration of function calls. The most common use of profiling information is to aid program optimization.

There are several such applications.  Sometimes, these are built into the IDE itself.  The netbeans ide is one such tool that has a profiler built in.

Another such tool is visual vm.

Profilers can work in different ways - and one should be aware of the differences.  One approach is every second to take a snapshot of the threads running and see what methods are currently being invoked for each thread.  This uses a sampling of what is out there.

The other approach is to instrument the java bytecode to report back the start and stop time to another application.

Writing a profiler is not terribly difficult for one skilled java.  IBM has an article on writing your own profiler (with source code!).  This one is based on the Java Interactive Profiler.

There are a multitude of profilers out there - both free and commercial (how about a profiler hooked up to running JVM instances that can report back to you (email or some other notification) when particular methods exceed the expected runtime? or hooked up to a program that reports back when web requests took too long - have the historical profile for that request saved off for later inspection?).  You just have to know what you are looking for to start finding them and go from there.

Once you've got the profiler, you're on to interpreting the profiling results.


问:
What is the proper way to store an object with many attributes in Objective-C?
I have an object that I am downloading over HTTP, that has approximately 50 attributes. What is the proper way to store this information in Objective-C? Should I have an NSObject with a property for each attribute (if so, what would be a good way to initialize this object?)? Should I use an NSDictionary with 50 key-value pairs?</p>

答: I'd probably use a NSDictionary. The code will probably be cleaner & easier to maintain. If you get an unexpected attribute, you'll crash if you didn't define a property for it.</p>

OwnerDisplayName: Lenny K

OwnerDisplayName: Mike C.


问:
Does a programming language increase/decrease value?
Let's say you develop a software program for Windows in C#, then Joe Blow develops the same software program for Windows but instead codes it using C++.

If Joe Blow were to sell that software program, what would determine who would get more money for it given the different languages?

Assuming, both used the same licensing system and the only difference between the programs was the source code.

答:
There are two things ordinary users care about:

User experience¹,

Features².

They don't care about:

The language used by an app,

If it uses design patterns or not,

Whether the code is readable,

etc.

But...

... but a programming language can have a minor effect on user experience. An application which uses Java will require Java to be installed on the machine. This is not always an easy task for users with no technical background. The same applies for C# if it uses newer versions of .NET Framework on the versions of Windows which have older versions.

... but some users, such as:

Geeks,

Developers who want to create software products which are interoperable with your app³,

System administrators who need to deploy your app in the shortest amount of time, in an automated way, on thousands of machines,

will all be concerned by the technology you use, and a choice of a language will become a feature.

Examples

OkCupid, a dating website, uses C++. Since it is a website, it really doesn't matter which language is used behind for the end users. It would have been Ruby on Rails or JSP, nobody would see the difference, as soon as the user experience and the features stay the same.

Google Closure compiler requires to have both Java and Python installed. This impacts the user experience for a person like me who would like to install Google Closure compiler on a server and then create a service to use it from other machines on the local network, given that installing components like Java on the server is out of question in my case.

Side note: why do we care about languages?

If languages don't matter from user's point of view, the choice of a language is still important. Choosing the right language in a given context and given skills of your team means having less bugs, to be able to fix bugs faster, to improve creativity, to use a bunch of tools to enhance the quality of the application, etc.

One of the challenges of a project manager is to pick the right tools and languages to ensure that the product can be delivered on schedule within a given budget.

¹ Performance is not mentioned in the list, since it is already inside user experience. An application which responds fast enough provides a good user experience. An application which feels slow and unresponsive provides bad user experience. The choice of a language has small to no impact on the perceived performance. Any good interaction designer would tell that there are plenty of ways to enhance perceived performance without doing code profiling and optimization.

² Given that user experience counts much more than features, since there is no benefit from putting hundreds of features if no ordinary user can use or even find them. This also explains the actual trend to over-concentrate the efforts on user experience, while reducing the number of originally projected features.

³ Unless it's a web app or an application which provides an API which can be used from nearly any language.


答:
I doubt that it makes any difference either way.

If the program is a self-contained application that is targeted at end users, then they won't care one way or the other what language it is coded in.  It is not relevant to them ... provided the application does what it is supposed to do, reliably, quickly enough, etcetera.  The price they are willing to pay depends on the application's utility and the market sector it is being sold into.  The implementation language is not a consideration.

If the program is designed to be extended, tailored or embedded by the customer, then the programming language could be significant.  The choice of language might affect the saleability and size of the target market, but I don't see why it would affect the price.

@MainMa mentions that selling to geeks is different.  I agree that technologically aware people are more likely to care about the implementation technology than the average customer.  However, I think that language choice more is likely to affect the geek's decision to buy or not buy rather than the amount of money they are prepared to pay.

Title: Does a programming language increase/decrease value?

Body:
Let's say you develop a software program for Windows in C#, then Joe Blow develops the same software program for Windows but instead codes it using C++.

If Joe Blow were to sell that software program, what would determine who would get more money for it given the different languages?

Assuming, both used the same licensing system and the only difference between the programs was the source code.


问:
Why don't we have a non-turing complete general purpose language yet?
Non-turing complete languages can solve every practical problem that a turing-complete language can. Also, they are much more analyzable than turing complete languages. The compiler can comprehend the program as a whole, predict/compute/cache every possible computation in advance, optimize it the most mathematically possible and even prove it has done so. It is like a super fusion between static typing and lazy evaluation in roids.

Yet nobody is trying to design a non-turing complete language like COQ that is practical and usable. Why?

答:
Non-turing complete languages can solve every practical problem that a turing-complete language can.

Wrong.  You cannot, for example, even do something as simple as implement the game of Life in a non-Turing complete language.  Why?  Because the game of Life is Turing complete.

Once that hypothesis is seen to be false, the answer to the question is obvious.


答:
All else being equal, the language used to write the program shouldn't affect the value or selling price.

The chances of all else being equal, however, are nearly nonexistent, so the question is almost completely theoretical, and the answer almost completely meaningless. In reality, language choice affects things like availability of libraries, documentation, tutorials, etc.

For example, consider just one small facet of development. A team writing a GUI in Java is much more likely to emphasize similar look and feel across platforms -- you can move from Windows to MacOS to Linux, and hardly notice the difference. A similar program written using C++ and Qt would show much greater differences in look/feel between one platform and another.

Now, it's certainly possible to use Qt from languages other than C++, so that particular point doesn't affect ever possible pair of languages you could compare. Nonetheless, the pair of languages you choose to compare will only affect what differences you see, not the fact that there will be differences.


问:
Is it OK to return HTML from a JSON API?
On my current project I am responsible for the implementation of a service which involves the consumption of newly created RESTful APIs, documented as solely supporting JSON.

The client consistently makes requests with the accept header of 'application/json' and content-type of 'application/json'. However some endpoints send a response with a content-type of HTML, even a HTML body. To me this is clearly the wrong approach and can never be justified.

Throughout the project this same practice has been applied across two different vendors and two different services. I found myself having to justify why the services needed to be changed. The vendors stated that the client should cope with this and even my REST library of choice has been questioned (RestEasy) because it doesn't cope with this by default 'out the box'.

This has been a major point of frustration. I can't find many references to back up my argument, I assume this is because the point is moot as it's so obvious.

The question is, am I missing something? am I being pedantic about this? Is it OK to have a JSON API that doesn't have a content-type of application/json in this scenario? References would be appreciated. How do you resolve this situation from a commercial point of view?

答:
What do you mean by "RESTful JSON API" - I think the first issue here is that you are mixing up concepts (or possibly someone between you and your technical counterparts at your "suppliers").

A RESTful API (whether you're talking not at all rest really at level 1 or something at level 3 or above c.f. http://martinfowler.com/articles/richardsonMaturityModel.html ) is about the way you interact with the API not about the format of the content sent to or received from. Its not even about protocols or transport mechanisms...

Similarly a JSON API is an API that supports use of JSON as a data format - it may or may not be restful, it may or may not be implemented using HTTP and (and this is the key point) it may  or may not support JSON exclusively.

A good API running over HTTP (its reasonable to assume that in context you're talking about an api exposed over HTTP) should allow you to request content in a variety of formats and those formats can (and possibly should) include HTML as well as JSON and XML. Why? Well it would make learning the API a lot easier, conceptually it provides an instant browser based UX for whatever purpose and so on...

The interesting question then becomes if my API, which supports a variety of content formats, is called without being told what format the client expects then what format should it return...? This tends towards a religious argument - but HTML gives the provider the option of including helpful information (like "remember to set the content accept header").

To answer the question an API, one that's restful and one that supports json should absolutely be able to return HTML if that's the requested content.


答:
When you are sending an accept header requesting a specific media type, the server should not send back something else, and most certainly not with a 200 OK status code

From Restpatterns.org:

If no Accept header field is present, then it is assumed that the
  client accepts all media types. If an Accept header field is present,
  and if the server cannot send a response which is acceptable according
  to the combined Accept field value, then the server SHOULD send a 406
  (not acceptable) response.

(Emphasis mine)

Restpatterns.org takes this from the actual HTTP standard: Header field definitions - Accept

In short: you are not being pedantic. The services are not following the HTTP standard if they are returning HTML when the accept header specifically tells them to return application/json and nothing else.

Title: Is it OK to return HTML from a JSON API?

Body:
On my current project I am responsible for the implementation of a service which involves the consumption of newly created RESTful APIs, documented as solely supporting JSON.

The client consistently makes requests with the accept header of 'application/json' and content-type of 'application/json'. However some endpoints send a response with a content-type of HTML, even a HTML body. To me this is clearly the wrong approach and can never be justified.

Throughout the project this same practice has been applied across two different vendors and two different services. I found myself having to justify why the services needed to be changed. The vendors stated that the client should cope with this and even my REST library of choice has been questioned (RestEasy) because it doesn't cope with this by default 'out the box'.

This has been a major point of frustration. I can't find many references to back up my argument, I assume this is because the point is moot as it's so obvious.

The question is, am I missing something? am I being pedantic about this? Is it OK to have a JSON API that doesn't have a content-type of application/json in this scenario? References would be appreciated. How do you resolve this situation from a commercial point of view?


答:
The client consistently makes requests with the accept header of 'application/json' and content-type of 'application/json'

Yes, this is the correct thing to do, but doesn't mean the vendor cares. While I totally understand your frustration, because I also think a JSON service should always give a JSON response but there are many examples where that's the not the case.

Throughout the project this same practice has been applied across two different vendors and two different services. I found myself having to justify why the services needed to be changed. The vendors stated that the client should cope with this and even my REST library of choice has been questioned (RestEasy) because it doesn't cope with this by default 'out the box'.

Well, I have to agree with the vendor. It's their service and as long as they document clearly the special cases for using it, then you can't really impose that they change it. It's a disadvantage for them as developers will be slow to adopt their API, and if they listened to what the developers need then they would change it, but sadly there is no rule that they must follow standards.

The question is am I missing something?

Request headers mean nothing unless they are interrupted correctly on the other end. I know that if I develop a web API using PHP, then to hell with the request headers. I can respond with whatever I want. Whereas, a service configured in IIS with C# offers much easier handling of request headers, their type and handling the response type. It has a lot to do with the tools the vendor used to build the API.

I'm I being pedantic about this?

Yes and No. I have developer friends who would be unable to move past this. They would become so fixated by the problem and unable to proceed with other tasks until the API works the way they expect it to work. Now that's being pedantic.

It's a problem because the vendor has created "more work" to complete your tasks. Anyone would be frustrated by that. I know I would be.

Is it OK to have a JSON API that doesn't have a content-type of application/json in this scenario?

Absolutely, but it's not a good practice.

A client can only tell the server what the context-type of a request is. It has no ability to enforce a content-type for the response. The client can only inform the server that it will accept a collection of possible content-types.

Header Field Definitions

The Accept request-header field can be used to specify certain media types which are acceptable for the response. Accept headers can be used to indicate that the request is specifically limited to a small set of desired types, as in the case of a request for an in-line image.

It's possible for a client to request an image of image/jpeg, but the server responses with text/html and a status code of 404 if the image was not found. Servers can also respond incorrectly. There are many Wordpress websites out there that respond with text/html and status code 200 for files not found pages.

Now that is all BAD practice on the part of the server. What I'm trying to tell you is that it's absolutely possible, and happens often. People don't know what they are doing when they configure these things.

References would be appreciated. How do you resolve this situation from a commercial point of view?

I've run into this problem on a few projects. You post JSON data to the server and it gives back either a JSON or HTML response.

It really isn't a big deal to know which type was in the response. If the first character is { or [ you can assume JSON. If it's < you can assume HTML. That's how I've handled it in the past. Sometimes the programmer who wrote the API knows jack all about HTTP headers. Everything comes back as text/html responses. If you are lucky they have Apache configured to default to text/plain which can sometimes help.

These problems exist and will continue to exist far into the future. Server to server communication is by far an unregulated activity. There is no governing body that will kick out a vendor from a union for a server that gives bad HTTP responses.


问:
When to fracture a web application design into multiple products
Have you had this problem?

You are building a complex web application for a target market, and after a while you reach a point in complexity where you can't decide if you are building more than one product.

A decision has to be made. Do you add features to turn it into a framework for multiple domains or do you resist the urge and focus just on the one product.

I'll give you a theoretical example;

You are building a web application for reviewing Movies and Television shows. Users can login and write their own reviews. After months of hard work you start to see how useful the application would be for reviewing Automobiles. All the terms/themes are for the Movie/TV industry. So you would have to refactor and take into account a multisite structure to run the web application for two different markets.

What do you call this type of problem, and how do you know when you should and should not split the project up into multiple domains.

答:
Tough one. I'd resist the urge, unless you have definite demand for an automobile review site.

If that is the case: prepare the codebase to allow for different terms and themes in specific instances of the site. Much like the tag system on the stackexchange network. The tag system is shared, but the content of that system - the tag values - differ per site in the network.

Do the same for other stuff where the concept/principle should be the same, but the table content should be different on a per site basis.

Every time you get the urge to code something like if automobiles then ... else ... step back and find a different approach where the code base can stay the same for both (all?) sites and the differences are in the site's data tables and or provided by callbacks and or other means of extending the core functionality.

Resist the urge to duplicate the code base: it may seem the quickest way, but it is going to give you major headaches in the future.

Btw, I did assume you already have proper separation of visual looks (css), visual structure (html/css), and information structure/data/logic. For example by using MVC or similar design pattern.

Oh and the name for this problem: I dunno, Seeing potential? Swiss army knife syndrome? Or when you have a hammer all you see is nails? In the end whether you do or don't split the project in multiple domains is a business decision, not a programming one.


问:
object oriented analysis, missing methodology
I've studied design pattern and oop principles, still feel that there is something missing in most design theories. Maybe the fact is that there is not a 'theory' as it is in database design.

Let me explain with an example.

Suppose that i want to model different ways to produce orange juice.

Let say that i start by a class Oranges, that models a lot of oranges that will be of a certain variety, of a certain ripeness, they may have been froozen etc., ant these will by my Oranges class properties.

Then i continue by providing Orange with a squeeze method.

This seems to be correct, because ties togheter the method to the data it applies to, that is the precondition to achieve encapsulation and other valuable oop principles.

But quickly it comes out that it has not been a good choiche because there is not just one way to squeeze an orange. It would be preferrable to have a Juicer class whose instances contains details of the juicing method: by hand, with an electric juicer, including the pulp, not to mention mixing different varieties of oranges. Where the latter opens an whole new cathegory of possibilities that were not available (or not achievable with ease) if each Oranges instance would have been processed using its squeeze method.

Say that we have performed a 'refactoring' of our oo architecture and move to another similar example that will get us to the point.

It is now a common practise to use an ORM to save class instances to database and get them back later.
In what is it similar to the Oranges class example? Well, here i have a class whose instances may be persisted to a database, that is 'allow a particular process'. But the class itself does not contain the logic for doing so, that actually is in the ORM classes. So it seems that the same process of 'externalization' of the Oranges example has taken place in this case too.

And here is the question

Given that it is desireable to reduce the number of attempts-and-refactorings to the minimum, what are the questions that a programmer should put in order to determine precociously if a method should be externalized to another class?
Are all the methods of a class exernalizable or is there a set of core methods that are inherently of the class itself and so not externalizable?

Ideas

As i said in the beginning, i'm not completely clueless, i feel more like that a 'comprehensive' theory is missing.

It's easy to put some examples:

if i have a class whose instances represent invoices, i will have a method 'calculateTotalAmount'. This is clearly an inthrinsic, core method of that class, as oppsed to the methods for saving that invoice to the database that will be 'external' of the class itself.
But this is not a 'final answer', but a starting point that serves to demonstrate that 'not all methods are equal', but methods may be divided into cathegories. How many (useful) cathegories can we make, and are there methodologies that put these questions?

答:
Given that it is desireable to reduce the number of
  attempts-and-refactorings to the minimum...

Desirable, yes. Practically possible in every case, no: because you don't know everything about the solution yet.

I don't see this as a lack of a formal methodology (you'll have the same issues with a relational model of your orange-juicer as you discover new ways of extracting juice), but as an intrinsic process of thinking about and evolving your design and application.

EDIT: I missed an assertion on first reading, added here for further illustration (not to hammer you or anything, you've asked a very good, fundamental question, just trying to be thorough) -

...if i have a class whose instances represent invoices, i will have a
  method 'calculateTotalAmount'. This is clearly an inthrinsic, core
  method of that class...

No, it isn't. The total may be maintained incrementally instead as invoice items are added, deleted, or edited. Or 'CalculateTotalAmount' might be convenient if the Invoice class has only a few simple InvoiceLineItem objects in a collection in memory, but even then the actual calculation may be ridiculously complex, time-dependent, require a boatload of supporting objects and be subject to multiple varying discount levels based on the purchaser, billing agent, line item codes, service provider, location, time of day, and so on (think 'insurance claim invoice').

The methods and properties of classes (and thus the protocols of the application) depend on what you are trying to do, which influences what structures will be more (or less) convenient to do so. And you only know all of that after you're done.

(Which is why refactoring is crucial for code longevity, but that's another discussion)


答:
I think you are looking for SOLID. More precisely, Single Responsibility Principle.

These are not methodologies, but more like way you should think about your solution and guidelines to validate this solution. In the end, you still need to use your experience and common sense to judge your final design.

The reason non existence of such rigid methodology, that would allow you to validate your solution, is simply because scope of such validation is huge. Correctness of OO design depends on requirements for not only the classes itself, but also on classes that depend and are depended on by this design. And also context of the whole application. If we take your Orange and Invoice examples, they might have radically different designs depending on application, yet they might be "correct" implementations in all those cases.

Title: object oriented analysis, missing methodology

Body:
I've studied design pattern and oop principles, still feel that there is something missing in most design theories. Maybe the fact is that there is not a 'theory' as it is in database design.

Let me explain with an example.

Suppose that i want to model different ways to produce orange juice.

Let say that i start by a class Oranges, that models a lot of oranges that will be of a certain variety, of a certain ripeness, they may have been froozen etc., ant these will by my Oranges class properties.

Then i continue by providing Orange with a squeeze method.

This seems to be correct, because ties togheter the method to the data it applies to, that is the precondition to achieve encapsulation and other valuable oop principles.

But quickly it comes out that it has not been a good choiche because there is not just one way to squeeze an orange. It would be preferrable to have a Juicer class whose instances contains details of the juicing method: by hand, with an electric juicer, including the pulp, not to mention mixing different varieties of oranges. Where the latter opens an whole new cathegory of possibilities that were not available (or not achievable with ease) if each Oranges instance would have been processed using its squeeze method.

Say that we have performed a 'refactoring' of our oo architecture and move to another similar example that will get us to the point.

It is now a common practise to use an ORM to save class instances to database and get them back later.
In what is it similar to the Oranges class example? Well, here i have a class whose instances may be persisted to a database, that is 'allow a particular process'. But the class itself does not contain the logic for doing so, that actually is in the ORM classes. So it seems that the same process of 'externalization' of the Oranges example has taken place in this case too.

And here is the question

Given that it is desireable to reduce the number of attempts-and-refactorings to the minimum, what are the questions that a programmer should put in order to determine precociously if a method should be externalized to another class?
Are all the methods of a class exernalizable or is there a set of core methods that are inherently of the class itself and so not externalizable?

Ideas

As i said in the beginning, i'm not completely clueless, i feel more like that a 'comprehensive' theory is missing.

It's easy to put some examples:

if i have a class whose instances represent invoices, i will have a method 'calculateTotalAmount'. This is clearly an inthrinsic, core method of that class, as oppsed to the methods for saving that invoice to the database that will be 'external' of the class itself.
But this is not a 'final answer', but a starting point that serves to demonstrate that 'not all methods are equal', but methods may be divided into cathegories. How many (useful) cathegories can we make, and are there methodologies that put these questions?


问:
Optimization of a hybrid pagination scheme
I'm working on a Web Application using node.js in which I'm building a partial copy of the database on the client-side to decrease the load on my server. Right now, I have a function like this (expressed as python-style pseudocode, but implemented in JavaScript):

```<code>get(table_name,primary_key):
    if primary_key in cache[table_name]:
        return cache[table_name][primary_key]
    else:
        x = get_data_from_server(table_name,primary_key) # socket.io
        return cache[table_name][primary_key] = x
</code>```

While this scheme works perfectly well for caching individual rows, I'd like to extend it to support the creation of paginated tables ordered according to the primary_key, and loading additional data using the above function for only the current and possibly the adjacent pages. Now, I don't want to keep the list of primary keys on the server to be retrieved every time I need to change the page (which, for reasons beyond the scope here, will be very frequent), and keeping it on the client side, subject to real-time create/delete events from the server, doesn't seem that good an idea, even after compression (using ranges, instead of individual values).

What is the best way to calculate which items are to be displayed on a random page, minimizing the space requirements & the need for communication with the server?

答:
Keep in mind that node is non blocking when waiting for io, not if you are processing items within your code. If you are using node to loop through or manipulate large datasets, consider offloading that work to the database or other processes.

It also sounds like you are trying to combine database logic (primary keys, rows) with application logic (user views, models) into a single caching function.  Consider a dual approach of optimizing at the database layer, and the application layer:

At the database level, Look into your database usage, use EXPLAIN, examine your use of indexes, remove N+1 and other repeated database calls.

At the application level, think of your pages (especially on the initial load) as entire views instead of tables and rows. then cache all of the data needed for the most common views, if the same data is presented to every user, consider caching the entire rendered output.  If using ajax calls, consider storing the initial set of cached data as json embedded within the html response.  Also look at where your cache is stored, redis and memcached are popular datastores for live site data.

Ref:
- NodeJS Event Loop: http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/
- MVVM architecture: http://addyosmani.com/blog/understanding-mvvm-a-guide-for-javascript-developers/
- Nodejs Page Caching: https://stackoverflow.com/questions/9715636/node-js-page-caching


问:
When to go Fluent in C#?
In many respects I really like the idea of Fluent interfaces, but with all of the modern features of C# (initializers, lambdas, named parameters) I find myself thinking, "is it worth it?", and "Is this the right pattern to use?". Could anyone give me, if not an accepted practice, at least their own experience or decision matrix for when to use the Fluent pattern?

Conclusion:

Some good rules of thumb from the answers so far:

Fluent interfaces help greatly when you have more actions than setters, since calls benefit more from the context pass-through.

Fluent interfaces should be thought of as a layer over top of an api, not the sole means of use.

The modern features such as lambdas, initializers, and named parameters, can work hand-in-hand to make a fluent interface even more friendly.

Here is an example of what I mean by the modern features making it feel less needed. Take for example a (perhaps poor example) Fluent interface that allows me to create an Employee like:

```<code>Employees.CreateNew().WithFirstName("Peter")
                     .WithLastName("Gibbons")
                     .WithManager()
                          .WithFirstName("Bill")
                          .WithLastName("Lumbergh")
                          .WithTitle("Manager")
                          .WithDepartment("Y2K");
</code>```

Could easily be written with initializers like:

```<code>Employees.Add(new Employee()
              {
                  FirstName = "Peter",
                  LastName = "Gibbons",
                  Manager = new Employee()
                            {
                                 FirstName = "Bill",
                                 LastName = "Lumbergh",
                                 Title = "Manager",
                                 Department = "Y2K"
                            }
              });
</code>```

I could also have used named parameters in the constructors in this example.

答:
Initial note: I'm taking issue with one assumption in the question, and draw my specific conclusions (at the end of this post) from that. Because this probably doesn't make for a complete, encompassing answer, I'm marking this as CW.

```<code>Employees.CreateNew().WithFirstName("Peter")…
</code>```

Could easily be written with initializers like:

```<code>Employees.Add(new Employee() { FirstName = "Peter", … });
</code>```

In my eyes, these two versions ought to mean and do different things.

Unlike the non-fluent version, the fluent version hides the fact that the new Employee is also Added to the collection Employees — it only suggests that a new object is Created.

The meaning of ….WithX(…) is ambiguous, especially for people coming from F#, which has a with keyword for object expressions: They might interpret obj.WithX(x) as a new object being derived from obj that is identical to obj except for its X property, whose value is x. On the other hand, with the second version, it's clear that no derived objects are created, and that all properties are specified for the original object.

```<code>….WithManager().With…
</code>```

This ….With… has yet another meaning: switching the "focus" of the property initialization to a different object. The fact that your fluent API has two different meanings for With is making it difficult to correctly interpret what is happening… which is perhaps why you used indentation in your example to demonstrate the intended meaning of that code. It would be clearer like this:

```<code>(employee).WithManager(Managers.CreateNew().WithFirstName("Bill").…)
//                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//                     value of the `Manager` property appears inside the parentheses,
//                     like with `WithName`, where the `Name` is also inside the parentheses
</code>```

Conclusions: "Hiding" a simple-enough language feature, new T { X = x }, with a fluent API (Ts.CreateNew().WithX(x)) can obviously be done, but:

Care must be taken that readers of the resulting fluent code still understand what exactly it does. That is, the fluent API should be transparent in meaning, and unambiguous. Designing such an API may be more work than is anticipated (it might have to be tested for ease-of-use and acceptance), and/or…

designing it might be more work than is necessary: In this example, the fluent API adds very little "user comfort" over the underlying API (a language feature). One could say that a fluent API should make the underlying API / language feature "easier to use"; that is, it should save the programmer a considerable amount of effort. If it's just another way of writing the same thing, it's probably not worth it, because it doesn't make the programmer's life easier, but only makes the designer's work harder (see conclusion #1 right above).

Both points above silently assume that the fluent API is a layer over an existing API or language feature. This assumption may be another good guideline: A fluent API can be an extra way of doing something, not the only way. That is, it might be a good idea to offer a fluent API as an "opt-in" choice.

OwnerDisplayName: ach

Title: When to go Fluent in C#?

Body:
Initial note: I'm taking issue with one assumption in the question, and draw my specific conclusions (at the end of this post) from that. Because this probably doesn't make for a complete, encompassing answer, I'm marking this as CW.

Employees.CreateNew().WithFirstName("Peter")…

Could easily be written with initializers like:

Employees.Add(new Employee() { FirstName = "Peter", … });

In my eyes, these two versions ought to mean and do different things.

Unlike the non-fluent version, the fluent version hides the fact that the new Employee is also Added to the collection Employees — it only suggests that a new object is Created.

The meaning of ….WithX(…) is ambiguous, especially for people coming from F#, which has a with keyword for object expressions: They might interpret obj.WithX(x) as a new object being derived from obj that is identical to obj except for its X property, whose value is x. On the other hand, with the second version, it's clear that no derived objects are created, and that all properties are specified for the original object.

….WithManager().With…

This ….With… has yet another meaning: switching the "focus" of the property initialization to a different object. The fact that your fluent API has two different meanings for With is making it difficult to correctly interpret what is happening… which is perhaps why you used indentation in your example to demonstrate the intended meaning of that code. It would be clearer like this:

(employee).WithManager(Managers.CreateNew().WithFirstName("Bill").…)
//                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//                     value of the `Manager` property appears inside the parentheses,
//                     like with `WithName`, where the `Name` is also inside the parentheses

Conclusions: "Hiding" a simple-enough language feature, new T { X = x }, with a fluent API (Ts.CreateNew().WithX(x)) can obviously be done, but:

Care must be taken that readers of the resulting fluent code still understand what exactly it does. That is, the fluent API should be transparent in meaning, and unambiguous. Designing such an API may be more work than is anticipated (it might have to be tested for ease-of-use and acceptance), and/or…

designing it might be more work than is necessary: In this example, the fluent API adds very little "user comfort" over the underlying API (a language feature). One could say that a fluent API should make the underlying API / language feature "easier to use"; that is, it should save the programmer a considerable amount of effort. If it's just another way of writing the same thing, it's probably not worth it, because it doesn't make the programmer's life easier, but only makes the designer's work harder (see conclusion #1 right above).

Both points above silently assume that the fluent API is a layer over an existing API or language feature. This assumption may be another good guideline: A fluent API can be an extra way of doing something, not the only way. That is, it might be a good idea to offer a fluent API as an "opt-in" choice.


答:
Obviously pointing out that the spec doesn't say what order the data comes in, hasn't worked.  Probably because he knows the data is on a disk or in memory somewhere and thus has that as an order.  Ask him what is the order of calculated data from several tables.  I.e. create an example where you join 4 tables, doing a calculation on 2 of them and returning just the calculated value.

The engine returns the data in the order it finds it (absent an order by), but how it finds it depends upon factors that can change - index's, stats, caches.  Generally the data will be in a consistent order -- but if you depend upon the order, you need to ask for it.

Title: In what order are rows fetched absent ORDER BY clause?

Body:
One programmer is testing and comparing the same application which uses the same database structure, and the same data, only in two separate databases, one with Oracle 8 and one with Oracle 9.

The app runs a query with no ORDER BY clause.

He claims that the ORDER-BY-less query should return the rows in the same order in both databases.

I tell him there's no warranty of the same row order unless you explicity provide an ORDER BY clause.

The database has the same indexes and keys. But the explain plan shows that in one of the databases the engine is using the key of one of the joined tables whereas in the other database it's using another's.

He insinuates that the two DB environtments are not equal, which is so because they have different statistics, different rdbms engines, etc., but not because I failed to replicate every index the original database has.

I tell him he must explicity provide an ORDER BY clause if the order is really that important.

The question

So I can explain him better:

In what order does a query fetch rows when you don't explicity provide an ORDER BY clause, and why doesn't that query return the rows in the same order ?


答:
As Mike suggested, an NSDictionary is an easy way to store a ton of key/value pairs quickly. The downside to this approach is you lose convenience of access after the fact. You have to remember what every key was in order to access any values. This may mean going back to the web service API or the JSON response to get the key you need. You also get no help from the compiler. </p>

<p>On the other hand, creating an NSObject subclass with properties for each key/value pair gives you all the convenience but it takes time to parse the values, especially with as many as you're talking about. I generally use the subclass approach because I like the convenience of having the compiler help with autocomplete and type checking. You can also determine which properties are read/write and which are read only. I add an initWithDictionary: method to create the subclass and parse the JSON response inside of that method. That kind of helps abstract away the data model from the application itself </p>

Title: What is the proper way to store an object with many attributes in Objective-C?

Body: I have an object that I am downloading over HTTP, that has approximately 50 attributes. What is the proper way to store this information in Objective-C? Should I have an NSObject with a property for each attribute (if so, what would be a good way to initialize this object?)? Should I use an NSDictionary with 50 key-value pairs?</p>

Body:
As Mike suggested, an NSDictionary is an easy way to store a ton of key/value pairs quickly. The downside to this approach is you lose convenience of access after the fact. You have to remember what every key was in order to access any values. This may mean going back to the web service API or the JSON response to get the key you need. You also get no help from the compiler.

On the other hand, creating an NSObject subclass with properties for each key/value pair gives you all the convenience but it takes time to parse the values, especially with as many as you're talking about. I generally use the subclass approach because I like the convenience of having the compiler help with autocomplete and type checking. You can also determine which properties are read/write and which are read only. I add an initWithDictionary: method to create the subclass and parse the JSON response inside of that method. That kind of helps abstract away the data model from the application itself


答:
Presumably there is some human being somewhere who wanted you to model the making of orange juice. Perhaps instead it is you, and you just wish to model it for the fun of it.

Start by writing out, in English (or the language of your choice)  how you would describe the process.  Keep track of the nouns, verbs, and other parts of speech.

You might end up with something like "I take an orange out of the bowl and roll it around on the table to "soften" the inside so that it will produce more juice when cut. Then I cut the orange in half, and use a handheld squeezer to squeeze the juice into a glass. Sometimes, if I'm lazy, I will use the mechanical juicer in my cupboard, but it usually makes too much pulp. Then I drink the glass of juice and go sit on the couch for an hour"

Now you have a description of what is going on, and what you need to model.

So you find the nouns, and make those the classes. You find the verbs, and make those the methods.  It is just a starting point, but it is important to note the following:

Software always models something, and the actual thing that you are modelling is what drives how you design the classes and their relationships. And now the most important part:  someone else might describe the same process differently. The order might be different, some parts might be different, and so they need a different model in software to describe what is going on.   BUT NO MODEL IS BETTER or MORE ACCURATE than other,  they simply are different models.

Some software systems may even need more than one model for the same process, even. So remember, your OOP design is about matching a model for a specific purpose in a particular domain. The "correct" OOP design is the one that best captures the model in the particular domain.