问:
Decrease probability of picking a list's item based on its index
I have a list of sounds that are to be played when the user presses a button.

For now I just generate a random number within the range of the list and just pick the sound with that index. (I also prevent that sound from being played the next time the button is clicked. Since that is easy, I would like to concentrate only on the selection algorithm and leave the exclusion behind.)

Since that makes it possible for a few sounds to be played repeatedly in a pattern, I would like to adjust my algorithm:

Once a file is played it gets moved to the end of the list. Sounds from the beginning have a greater chance of being played than those at the end - therefore minimizing repetition.

Instead of assigning a weight to each index, I want to have one factor determining the probability falloff. For example, I would set this factor to be 1.2 which means that each index is 1.2 times as probable to be played as the following one. This hopefully produces a nice falloff in probability.

The fastest solution seems to be a mathematical function that maps the random number to the range of indices. That way I do not have to set up intervals, but can directly calculate the result based on the random number.

I just cannot figure out the math and implementiation behind this idea, so I need you to lay it out for me. The algorithm will be used in an Android app, so the programming language I am using is Java.

答:
There are many ways to implement weighting, but you should start by thinking of this as a weighting function. In pseudo-code:

```<code>function weight(int max) returns integer;
</code>```

The integer is an index in the range of 0..max-1 which will select a sound.

You have available a random number generator which returns a uniform distribution [0..1).

```<code>function random() returns real;
</code>```

Now you need a formula to translate one distribution into another.

```<code>// linear
return integer(random() * max);
</code>```

To implement the 'factor' you propose requires a bit of maths, which perhaps someone else can help with. It could go something like this.

```<code>return integer(max*(1-x^1.2))
</code>```

I suggest the use of a graphing tool to visualise the distributions: http://rechneronline.de/function-graphs/.

Body:
There are many ways to implement weighting, but you should start by thinking of this as a weighting function. In pseudo-code:

function weight(int max) returns integer;

The integer is an index in the range of 0..max-1 which will select a sound.

You have available a random number generator which returns a uniform distribution [0..1).

function random() returns real;

Now you need a formula to translate one distribution into another.

// linear
return integer(random() * max);

To implement the 'factor' you propose requires a bit of maths, which perhaps someone else can help with. It could go something like this.

return integer(max*(1-x^1.2))

I suggest the use of a graphing tool to visualise the distributions: http://rechneronline.de/function-graphs/.


问:
Classic inheritance problem?
I keep seeing the following pattern when people learn about OOP:

Problem: How do I put objects of different but related types into a container?

Solution: Inherit from a common base class.

New problem: I have a bunch of base class objects, how do I get the real type?

Solution: ???

The classic inheritance example is to make a graphics program that deals with geometric objects. We have Circles, Ellipses and Triangles. All these objects have a common base Drawable.

In C++ this might look something like this:

```<code>struct Drawable{
    virtual ~Drawable(){}
    virtual void draw() const = 0;
};

struct Triangle : Drawable{
    Point p1, p2, p3;
    void draw() const override;
    void stretch(double xfactor, double yfactor);
    std::touple<double, double, double> getAngles() const;
    //...
};

struct Circle : Drawable{
    double radius;
    void draw() const override;
    //...
};

struct Ellipse : Drawable{
    double radius;
    void draw() const override;
    //...
};

std::vector<Drawable *> drawables = {new Circle, new Triangle, new Ellipse};
for (const auto &d : drawables)
    d->draw();
</code>```

So far so good. Now I want to increase the radius of my Circles and Ellipses. As far as I know there are 4 ways to do that:

1: Put everything into the base class. The base class gets the virtual functions getAngles, getRadius, stretch and getEccentricity. There is a default implementation for each so that for example getRadius returns some dummy value when you are dealing with a Triangle. After this is done you can easily iterate over the Drawables and increase their radius. This makes the base class ridiculously huge and working on a vector<Drawable *> becomes inefficient because the functions do nothing for most elements.

2: Use dynamic_cast hacks.

```<code>for (const auto &d : drawables){
    if (dynamic_cast<Circle *>(d))
        ((Circle *)d)->radius++;
    else if (dynamic_cast<Ellipse *>(d))
        ((Ellipse *)d)->radius++;
}
</code>```

Unfortunately you need to repeat this ugly syntax every time you need to do something like this. You cannot put it in a function or macro. Every time a new Drawable is added you have to go through the whole code base and add it where appropriate. Also the if/else-chain is fairly inefficient.

3: Add a Tag as the first member variable and cast accordingly.

```<code>for (const auto &d : drawables){
    switch(d->tag){
        case Tag::Circle:
            ((Circle *)d)->radius++;
            break;
        case Tag::Ellipse:
            ((Ellipse *)d)->radius++;
            break;
    }
}
</code>```

Slightly more efficient due to a switch instead of an if/else-chain, but there is already a kind of tag that shows the dynamic type, so the tag is redundant. Also it has the same problem as 2: since you need to change the whole code base whenever a new Drawable comes along.

4: Just keep the objects in separate containers.

```<code>vector<Circle> circles;
vector<Triangle> triangles;
vector<Ellipse> ellipses;
for (auto &c : circles)
    c.radius++;
for (auto &e : ellipses)
    e.radius++;
</code>```

This is very efficient memory layout wise and you only iterate over objects that matter. It is my favorite, but unfortunately it breaks the first solution in that you do not keep differently typed objects in a single container.

I tried to solve the problem by creating a variadic template that internally has a vector per type and forwards insertions to the right container. Ideally it would completely hide the fact that there are different containers under the hood. Usage would look something like this:

```<code>MultiVector<Triangle, Circle, Ellipse> mv;
mv.push_back(Triangle());
mv.push_back(Circle());
mv.push_back(Ellipse());
for (auto &d : mv.get<Circle, Ellipse>())
    d.radius++;
</code>```

The solution is not perfect, for example different types do not keep their order and implementing the iteration is tricky.

I presented this problem and solution attempt to my (university) research group and got the reactions "If you design your classes right this is not a problem" and "The proposed solution is a very specific tool to solve a very specific problem and it is questionable at best to add even more complexity to c++ for such a minor detail". In my opinion this is a very basic problem that needs fixing and the usual solution of better class design only tries to find the least evil of the 4 workarounds in the specific case without actually solving the problem. The problem comes up almost every time inheritance is used.

So finally here is the question: Did you run into this problem too / is this a real problem? Do you know of another workaround/solution? Do other languages deal better with the problem? I want to simulate a poll using 2 comments below so feel free to upvote either "I never had this problem / The problem is easily solved." or "I also had this problem and never solved it to my satisfaction."

Edit: To prevent a close due to primarily opinion based / discussion: I want a clear answer that solves the problem or some resource that says that there is none.

Edit: Related: Do I really have a car in my garage?

答:
I'm personally perfectly fine using downcasting. Simply because it is same as language-aided visitor pattern. It becomes even better if you create HasRadius interface/abstract class, that allows you to specify which classes do allow this change. This then allows you to add it to potentially new Drawable and eliminates the if chain. And some of the complains about this solution can be solved by implementing actual visitor, because changes to types will be ensured to be correct by the type system and compiler.

And one thing to note: you talk a lot about efficiency. Programming is about tradeofs and abstractions (especially those that add Open/Closed properties to design) always go directly against efficiency. I'm not saying efficiency is not necessary. Just that when you start using OOP, you have to be able to accept some performance hit. And lets not forget : You should leave performance optimizations after you profile your code. Thinking about performance in such example is going to skewer the results extremely.

ContentLicense: CC BY-SA 3.0

Title: Classic inheritance problem?


问:
Continuations, coroutines, and tail-call optimization
I am trying to learn continuations and use them to implement coroutines in Scheme.

I have two procedures (coroutines) a and b, and I switch between them in the following way:

```<code>;; c is a continuation.
(define (a c)
   ...
   ;; Switch to the other coroutine.
   (call/cc c)
   ...

(define (b c)
   ...
   ;; Switch to the other coroutine.
   (call/cc c)
   ...
</code>```

I  start the execution with

```<code>(a b)
</code>```

I have tested a small example and, indeed, the execution switches back and forth between the two procedures until one of the two terminates without calling the continuation it was given as an argument.

I have two questions:

Is my example an appropriate / idiomatic implementation of coroutines using continuations?

Is tail-call optimization mandatory for implementing coroutines with continuations? In my solution, switching too often between the two coroutines might cause a stack overflow if Scheme did not provide TCO. Are there other solutions that do not require TCO?

EDIT

Basile's comment seems to be sufficient to answer my question. The background of the question is that I would like this approach to implement coroutines in Python, where I do not have TCO.

答:
As I commented:

yes, your example is an appropriate implementation of coroutines using continuations.

yes, tail-call optimization is mandatory for implementing coroutines with continuations.


问:
Why are zero length VLAs allowed in C99, but not in C11 any more?
In the comments to this former question, there was a discussion if the C standard allows variable length arrays (VLAs) of length 0 or not. As it turns out, the C99 standard states:

In 6.7.5.2 Array declarators, Constraints:

"If the expression [for the array size] is a constant expression, it shall have a value greater than zero."

So since the standard explicitly mentions "constant expressions", it is clear that this constraint shall not hold for non-constant expressions, means zero length VLAs are allowed. This is indeed a useful behaviour, so for example GCC introduced it long before C99 as an extension and supports this AFAIK currently.

On the other hand, the C11 standard (draft) in 6.7.6.2 (Array declarators, Constraint 5) says:

If the size is an expression that is not an integer constant expression: if it occurs in a declaration at function prototype scope, it is treated as if it were replaced by *; otherwise, each time it is evaluated it shall have a value greater than zero.

So this explicitly forbids VLAs with zero length arrays. For example, according to this change, a function like

```<code>void MySpecialProcessing(int n, int *data)
{
    int sortBuffer[n];
    // ... do something with data, using sortBuffer ...
}
</code>```

maybe C99 compliant without any special treatment for n==0, but in C11, it must be

```<code>void MySpecialProcessing(int n, int *data)
{
    if(n==0)
        return;

    int sortBuffer[n];
    // ...
}
</code>```

Normally I would expect newer versions of the standard to introduce features which makes the life easier for the programmer, but in this case IMHO this seems a step back.

So any idea why this incompatible, breaking change was introduced? Is this intentional, or just a bug in the C11 standard?

答:
There has been no breaking change in this regard between C99 and C11.

The C99 standard states in section 6.7.5.2/5 (under Semantics):

If the size is an expression that is not an integer constant expression: [...]; otherwise, each time it is evaluated it shall have a value greater than zero. [...]

As this is not a constraint, violating the 'shall' results in undefined behavior.


问:
Differentiating Standalone and Client-Server architectures
I was wondering what is the exact difference between a client-server and a standalone application, particularly in following scenario.

For example lets say there is a win forms application running on a PC. So that the DBMS, SQL Server also installed on the same PC as it hosts the database too. Now this is clearly a standalone setup.

Now if we introduce another PC and connect it to the first PC through a local area network and we want to run the application on this new PC too but it will use the same database which is in the first PC.

Now is this application considered to be a standalone app or a thick client - server?

EDIT: The application communicates with SQL server to access data and processing will happen locally. SQL server hosts the data and there are few stored procedures and views too.

答:
Most client-server applications can be installed in a "standalone setup", where the client and server machine are the same, as you wrote, but that does not make them a "standalone application". Such a system is still a client/server application, and the interprocess communication between the client application process and the database process will typically happen through a network protocol like TCP/IP. Also, installation and administration typically require almost the same effort as on two separate machines.

Of course, applications specificially made for "standalone usage" are typically optimized for that scenario, for example, by accessing the database directly from the client application process, which eliminates the need for (typically slower) interprocess communication. Or they have still two processes for client app and database, but those communicate by using "shared memory", which (on most operating system, see here for execeptions) supports only non-distributed scenarios. This makes the applications more lightweight and easier to install or administer, but you cannot easily connect to that database from a second PC.

Of course, lots of DB systems (like SQL Server) are smart enough to use TCP/IP for a connection to a another machine, and switch to shared memory automatically when they detect client and server beeing on the same machine. I would still call such a system a client/server application.

As an example in the context of Microsoft Databases, there is SQL Server Compact Edition which is specifially made for such standalone applications, but not for client/server usage. A very popular example from the freeware world is SqLite. And if you are looking for a full-featured relational database system which can switch between a  "stand alone mode" (using shared memory, but easy to install without a background service) and "client server mode" (using TCP/IP) I would recommend SQL Anywhere.


问:
How to handle divide by zero in a language that doesn't support exceptions?
I'm in the middle of developing a new programming language to solve some business requirements, and this language is targeted at novice users. So there is no support for exception handling in the language, and I wouldn't expect them to use it even if I added it.

I've reached the point where I have to implement the divide operator, and I'm wondering how to best handle a divide by zero error?

I seem to have only three possible ways to handle this case.

Ignore the error and produce 0 as the result. Logging a warning if possible.

Add NaN as a possible value for numbers, but that raises questions about how to handle NaN values in other areas of the language.

Terminate the execution of the program and report to the user a severe error occurred.

Option #1 seems the only reasonable solution. Option #3 is not practical as this language will be used to run logic as a nightly cron.

What are my alternatives to handling a divide by zero error, and what are the risks with going with option #1.

答:
In my view your language should provide a generic mechanism for detecting and handling errors. Programming errors should be detected at compile time (or as early as possible) and should ordinarily lead to program termination. Errors that result from unexpected or erroneous data, or from unexpected external conditions, should be detected and made available for appropriate action, but allow the program to continue whenever possible.

Plausible actions include (a) terminate (b) prompt the user for an action (c) log the error (d) substitute a corrected value (e) set an indicator to be tested in code (f) invoke an error handling routine. Which of these you make available and by what means are choices you have to make.

From my experience, common data errors like faulty conversions, divide by zero, overflow and value out of range are benign and should by default be handled by substituting a different value and setting an error flag. The (non-programmer) using this language will see the faulty data and quickly understand the need to check for errors and handle them.

[For an example, consider an Excel spreadsheet. Excel does not terminate your spreadsheet because a number overflowed or whatever. The cell gets a strange value and you go find out why and fix it.]

So to answer your question: you should certainly not terminate. You might substitute NaN but you should not make that visible, just make sure the calculation completes and generates a strange high value. And set an error flag so that users who need it can determine that an error occurred.

Disclosure: I created just such a language implementation (Powerflex) and addressed exactly this problem (and many others) in the 1980s. There has been little or no progress on languages for non-programmers in the last 20 years or so, and you will attract heaps of criticism for trying, but I really hope you succeed.


问:
Is this a viable approach to resolving multiple matches in a lexer?
I'm writing a lexer in JavaScript. It's pretty typical - rules are specified with regular expressions and produce a token.

I am unsure of the best way to handle when multiple rules are matched. The existing lexers I've looked at handle this by picking the rule with the longest match.

It also seems like a viable strategy, however, to simply use the first rule that matches. This is my current strategy.

Here is an example:

Input:

:=

Rules:

```<code>: -> COLON
= -> EQUALS
:= -> ASSIGN
</code>```

The longest-match rule would return ASSIGN, where the first-match rule would return COLON and then EQUALS.

Obviously this is not desirable, so under my implementation I would just reorder the rules to put the ASSIGN rule first as follows:

```<code>:= -> ASSIGN
: -> COLON
= -> EQUALS
</code>```

Is this a viable approach to just use the first matching rule? What are the advantages and disadvantages of each approach?

答:
When I write a lexer I use a grammar, not regular expressions. The grammar has no ambiguities by design. The effect is exactly equivalent to your proposal of using regular expressions, ordering them by length descending, and accepting the first match. My way is more efficient (faster and less space) but a little harder to write.

The object raised regarding identifiers and reserved words does not apply. The tokens var and variant are parsed in exactly the same way. The lexer is tightly coupled to a symbol table, and the difference is that reserved words (and indeed every kind of token) are pre-loaded into the symbol table. The symbol table says what kind of token it is.

So your strategy (first match) is perfectly viable if you are prepared to look up tokens in a symbol table to find out what they are rather than building that knowledge into the lexer.


问:
Concurrency: How do you approach the design and debug the implementation?
I've been developing concurrent systems for several years now, and I have a pretty good grasp on the subject despite my lack of formal training (i.e. no degree).  There's a few new languages that have become popular to at least talk about lately that are designed to make concurrency easier such as Erlang and Go.  It appears that their approach to concurrency echoes my own experience as to how to make systems scalable and take advantage of multiple cores/processors/machines.

However, I find that there are very few tools to help visualize what you intend to do, and verify that you are at least close to your original vision.  Debugging concurrent code can be a nightmare with languages that are not designed for concurrency (like C/C++, C#, Java, etc.).  In particular, it can be near impossible to recreate conditions that happen readily on one system in your development environment.

So, what are your approaches to designing a system to deal with concurrency and parallel processing?  Examples:

How do you figure out what can be made concurrent vs. what has to be sequential?

How do you reproduce error conditions and view what is happening as the application executes?

How do you visualize the interactions between the different concurrent parts of the application?

I have my own answers for some of these, but I'd also like to learn a bit more.

Edit

So far we have a lot of good input.  Many of the articles linked to are very good, and I've already read some of them.

My personal experience with concurrent programming leads me to believe you need a different mindset than you do with sequential programming.  The mental divide is probably as wide as the difference between object oriented programming and procedural programming.  I'd like this set of questions to focus more on the thought processes necessary (i.e. theory) to systematically approach the answers.  When providing more concrete answers, it helps to provide an example--something you went through personally.

Goal for the Bounty

Don't tell me what I should do.  I already have that under control.  Tell me what you do.  Tell me how you solve these problems.

答:
How do you figure out what can be made concurrent vs. what has to be sequential?

Pretty much every thing you write can take advantage of concurrency especially the "devide an conquer" use case. A much better question is what should be concurrent?

Joseph Albahari's Threading in C# list five common uses.

Multithreading has many uses; here are
  the most common:

Maintaining a responsive user interface

By running time-consuming
  tasks on a parallel “worker” thread,
  the main UI thread is free to continue
  processing keyboard and mouse events.

Making efficient use of an otherwise blocked CPU

Multithreading is useful when a thread
  is awaiting a response from another
  computer or piece of hardware. While
  one thread is blocked while performing
  the task, other threads can take
  advantage of the otherwise unburdened
  computer.

Parallel programming

Code that performs intensive
  calculations can execute faster on
  multicore or multiprocessor computers
  if the workload is shared among
  multiple threads in a
  “divide-and-conquer” strategy (see
  Part 5).

Speculative execution

On multicore machines, you can
  sometimes improve performance by
  predicting something that might need
  to be done, and then doing it ahead of
  time. LINQPad uses this technique to
  speed up the creation of new queries.
  A variation is to run a number of
  different algorithms in parallel that
  all solve the same task. Whichever one
  finishes first “wins”—this is
  effective when you can’t know ahead of
  time which algorithm will execute
  fastest.

Allowing requests to be processed simultaneously

On a server, client requests can
  arrive concurrently and so need to be
  handled in parallel (the .NET
  Framework creates threads for this
  automatically if you use ASP.NET, WCF,
  Web Services, or Remoting). This can
  also be useful on a client (e.g.,
  handling peer-to-peer networking—or
  even multiple requests from the user).

If you're not trying to do one of the above you'd probably better think real hard about it.

How do you reproduce error conditions and view what is happening as the application executes?

If you're using .NET and you've written use cases you can use CHESS which can recreate specific thread interleaving conditions which enables you to test your fix.

How do you visualize the interactions between the different concurrent parts of the application?

It depends on the context. For worker scenarios I think of a manager-subordinate. Manger tells the subordinate to do something and waits for status updates.

For concurrent unrelated tasks I think of elevators or cars in separate lanes of traffic.

For synchronization I sometimes think of traffic lights or turn-styles.

Also if you're using C# 4.0 you might want to take a look at the Task Parallel Library

ContentLicense: CC BY-SA 2.5


问:
What is the "1620's multiplication operation"?
I was stumbling through Wikipedia when I came across the entry for FLOPS, specifically the table in this section.

The first entry is for a computer from 1961, the comment on the right reads

The 1620's multiplication operation takes 17.7 ms.[46]

What is this operation?

I assume it means it can do multiplication in 17.7ms?

答:
These stats are for the Model I, and is for two 10 digit numbers.  The Model I did in fact use table look ups for math, except for divide (add table was at locations 300-399, multiply at 100-299).  The Model II had circuitry for addition and subtraction, but still used table look up for multiply.

As odd as all of that sounds what you would find most odd was that the machine was not fixed word length.  That meant that you could add a 100 digit number to a 200 digit number. The other oddity was that each addressable memory location was actually 7 bits, one of them being a parity bit.

The 1620 was my first computer and those two oddities were initially hard to overcome as I moved forward in my career.


问:
How do sockets work over wireless connections?
I've only worked on client side(specifically, mobile) applications using Android, where all networking is handled at the HTTP layer using framework provided components like HttpUrlConnection.

But push messaging systems like Websockets/XMPP etc, all maintain a persistent connection to the server. Even Google's GCM, which is baked into Google Play supported devices, maintain a persistent connection to the servers.

My question is, how does this work without draining battery? If we make continuous HTTP requests sequentially, the battery drain is significant. How are these persistent connections maintained without encountering the same problem?

答:
An open TCP connection is a logical state. It does not imply that that data is always being sent back and forth. After the initial three-way handshake you've entered into the "connected" state. You're in that state until either a 3-way disconnect occurs or a keep-alive fails.

During the lifetime of the connection, resources from the underlying "physical" medium may be established to do transfers of data for that connection. In the case of a wired connection, this is a matter of transferring ethernet frames around. In the case of a 3G/4G wireless connection, this is done by establishing connections with the lower-level protocols as needed.

So for the life of the connection, there's no physical underlying data connection that exists. Instead it lies dormant waiting for either peer in the TCP connection to need to send data.

Another issue is that TCP is ack based. TCP peers can pretty efficiently keep each other apprised of what has been definitely recieved. Upon failure, TCP will retransmit. This works great for fairly reliable physical links, but tends to fall apart in very noisy/broken links, like your wireless connections. As you can imagine, acks/retransmissions would occur very frequently in these environments.

So typically, the underlying wireless protocol does everything it can to reduce the need for TCP retransmissions. For example, there's lots of error checking built into the wireless layer. Peers in the wireless realm (the base station/phone) also use a nak based protocol to tell the other side when they didn't receive something. Being nak based reduces the overhead in checking for errors (we assume everything fine unless the other side says its not). It also helps address errors before they bubble up to the TCP layer -- thus avoiding lots of TCP thrashing trying to retransmit. Moreover, it reduces the scope of any retransmissions to the wireless peers -- the phone doesn't need to ask the server somewhere on the Internet for the packet again, just the base station over the wireless link.


问:
Is SourceSafe really safe?
Having spent all morning trying to check something in - I now realise I've lost a couple of days worth of work.

Its happened before - and is apparently common occurrence with SourceSafe.  Can SourceSafe be used successfully, without problems, and if so, how?

答:
Even MS is deprecating it in favor of TFS.

For a solo or really small shop working in Visual Studio 6 or something older it is passable and better than nothing. I think there is a lot of exaggeration about how bad it was, but then it only takes one instance of losing valuable work to sour you on a product (for good reason). VSS had its place, and I credit it for at least encouraging a lot of developers who were using no SCM tool at all to get into the habit, but like many technologies it is now pretty much obsolete.

Title: Is SourceSafe really safe?


问:
Does jQuery basically use CSS3 for animation and effects?
I originally started out this question with "what is jQuery, and how does it work", in terms of all that fancy animation, effects, slideshow plugins, etc. I was uncertain as to how JQuery does all that fancy stuff. But after reading around on the internet, I am happy to acknowledge that jQuery is basically a "JavaScript library", and by that, I think it means that jQuery is pure text, of JavaScript code, consisting of public methods, functions, constants etc, with the idea that calling these simple methods or functions can replace loads of JavaScript code, and that its has a nice consistent feel to it.

So am I right in saying that all that fancy animation, effects etc  are not "actually" achieved by JavaScript/jQuery?  They are achieved by using CSS3? And CSS3 is a style sheet language which the browser can understand, and has the capabililites of carrying out those style sheet instructions?

Very fuzzy and ambiguous question, I know, but just trying to get my head round how you get those amazing jQuery animations etc.

答: For normal manipulation of styling change or adding new CSS class. Any JavaScript library can use the core DOM  elements navigation.   For animations and themes, jquery UI is used.   http://api.jqueryui.com/theming/css-framework/</p>


问:
Good way to handle the notification counter like Facebook does
I want to build a similar notification mechanism that Facebook handles.

I actually store the user's notification in an SQL table (actually it's a graph database but everybody master RDBMS terms).

I'm interested in the case where the user clicks on the icon:
The counter should get a value of 0 internally and visually disappears.

How the clearing of this counter should be made?

On clicking, call a Rest API that flags each notification as being read (table's column READ)?

Drawback would be that it would take some time if there was huge amount of notifications to flag in order to get the counter to 0 and making it disappear.

Having a kind of column for each user called HAS_NEW_NOTIFICATION that is valued as false each time the icon is clicked (through a REST API call), if the counter was present.

Thus, the counter would be present only if the flag value is true.

What would be a good practice?

答:
The best practice is to store a datetime stamp in the user's table that indicates the last pull by the browser for notifications. Any notifications created after this datetime stamp would be counted as new and unread.

The database can index notifications by their created datetime stamp efficiently, and adding a flag if read shouldn't impact performance. Since you are always searching for notifications after a give datetime the performance should be okay.

You just need to update the user's table of what the oldest unread datetime stamp is. That gives you a place to query the notifications for new and unread items.

If there are no unread items then the user's timestamp is updated to the last time the browser pulled for a check.


问:
Why shouldn't I make variables public, but should use public getters/setters?
I'm watching a C++ tutorial video. It is talking about variables inside classes and assert that variables should be marked private. It explains that if I want to use them publicly, I should do it indirectly through functions.

Why? What's the difference? It looks like the result is the same, except that instead of having one line of code, I now have like 9 or 10 more LOC to do the same thing.

Can someone explain why converting a private variable in a class to public within the class rather than just making it public right out the simple way is any different and more efficient?

答:
There are a few reasons to use setters and accessors as opposed to simply making variables public.

1. Separation of concerns - The consumers of a class shouldn't know, or even care, whether what they're accessing is a primitive variable, or something more complex. For example, let's say I had a Car class, and that car has a horsepower. You can get the horsepower by calling the getHorsepower() method, and you can set it with setHorsepower(int power).

Now, a consumer of this class really doesn't care what goes on under the hood, just that there is a horsepower method. But what if, on the backend, setting the horsepower meant changing the engine? When you call setHorsepower, it will find an engine that can provide that, and call the private method setEngine(Engine newEngine) to make sure that the car's behavior is consistent!

2. Code maintainability - When you set up the class, it may make sense to only have a public variable, but you quickly find that you need to do error checking on the variable, or you need to have a change in that variable update another object. If you provided the public variable, you would need to change all the classes that use that and then have them either A) Implement all the functionality you need them to like error checking, or B) Change them to use an accessor. By having them use the accessor, you can  modify all of that in one place instead of having to keep track of all the places that use that variable.


问:
Help with database design with a strict and structured subset of clinical data
I'm developing an application to keep some of the data in chronic patients, the data came from a very strict subset of data, vital signs, exams, ecc.

On a first glance I thought to create a Patient model with has_many encounters, and put every info in a different field like (age, height, weight, ecc), but it will result in a big model. So I wondered about embedding to make it easier to maintain and scale if in a couple of months I need to register a new exam, right now I have been thinking in something like this:

Patient

```<code>name: string,
address: string,
phone: integer,
diagnose: string,
etc...
</code>```

Encounters

```<code>patient_id: ObjectID,
age: Integer,
vital_signs: [ { height, weight, bmi, systolic_pressure, diastolic_pressure } ],
exams: [ { creatinine, total cholesterol... } ],
next_encounter: Date
</code>```

I'm going to still need to access to bmi for example if I want to get how many people in the community is obese (hint: an awful lot), so embedding maybe it's not a very good idea. In any case, all the "analysis" will only be done only monthly (or less).

I picked mongodb, because I'm afraid the requisites for this database will be changing from time to time, so flexibility it's important.

Maybe in this case since data is structured, every document will have the same types of fields, a relational database could be better? I don't think it makes sense using a nosql database in a sql way, right?

PS.- I read this article from mongodb blog, and I'm more confused about if this really it's the best approach.

答:
What is the use case of the data, reporting or just serve app functionality?

Relational databases are great for structuring data for reporting, but you can develop more rapidly with NoSQL because if it's lack of schema constraints.


答: Getters and setters are poor design as well.  They are better than public variables because they allow the class to enforce invariants.  To borrow Ampt's example setHorsepower is better than a public horsepower variable because the car class can ensure that horsepower is never negative with the setter, but can't guaranty anything about a public variable.  While that is better than nothing, a better design would have car instances in charge of their own horsepower.  Any code that is mucking about with the car's internal state should be apart of the car class.  It shouldn't have wondered off and gotten lost somewhere else.</p>

Title: Why shouldn't I make variables public, but should use public getters/setters?

Body:
I'm watching a C++ tutorial video. It is talking about variables inside classes and assert that variables should be marked private. It explains that if I want to use them publicly, I should do it indirectly through functions.

Why? What's the difference? It looks like the result is the same, except that instead of having one line of code, I now have like 9 or 10 more LOC to do the same thing.

Can someone explain why converting a private variable in a class to public within the class rather than just making it public right out the simple way is any different and more efficient?


问:
Design Pattern : Static Array/List in Class Object
I'm a CS alumni, but we didn't learn much by the way of OOP, or Design Patterns. I've heard the phrase C with iostreams and thought it fitting. Anyway that's besides the point. I am just curious about what I perceive would be a very simple design pattern.

Have any of you played the game Starcraft? You know how you can select/deselect units? Back to that in a second. Suppose I have a Unit class, and I wanted it to keep track of all the units that were selected. I had the idea that I could create a static list/arrray inside the Unit class, and the units themselves could add or remove themselves from the array as they were selected/deselected.

That's just one example, there could be other applications of this "pattern". Say you wanted to maintain a list of visible "tabs" in a web browser or w/e, you could have them add a reference to themselves in a a static array in the class.

The idea is that you could just call Unit.GetSelected() and get a pointer/reference to all of the "selected" or "opened" units/tabs. I am aware that there are other maybe better ways of solving these problems, but that is also besides the point. What would this pattern be called?

答:
This anti-pattern would be named whatever you like. I'm not sure I've seen it named before, though I would heartily recommend against getting cozy with it. I've seen this in games occasionally when someone thinks it's a good idea to have a global list of "all of the units in the game". Even if that's a good idea, that shouldn't be the responsibility of the unit - it's the responsibility of the game.

For your example, only the UI should know or care what's selected. Your game objects certainly should not.

In a more general sense, having a static that a type knows about tends to be tight coupling - making your code inflexible, hard to test, and hard to use concurrently.


问:
Php: Whats my next step?
So in college I started learning Php, mostly starting with the Larry Ullman books. I got a job at a company after, where I was able to learn some stuff from the higher up guys. Since then, I've done freelance stuff and sort of learned things as I needed to.

I'm trying to figure out where to go next. I definitely want to stick with the web programming arena, and I'm enjoying concentrating on Php.

I know MySQL as well, but VERY little Javascript / Ajax.

I've also been reading a lot of OOP theory, and have a descent grasp of how it works, but it doesn't feel natural yet.

Where should I go from here? Is it worth learning Java fort a while to really get the OOP stuff down? I took introductory Java in college, but it was only 1 semester. Or should I concentrate on some of the open source stuff (Wordpress, Drupal, JQuery, etc). How about E-commerce solutions? I have no experience with that.

In terms of my goals, I don't have much plans for big, enterprise types of projects.  I would mostly be interested in working freelance on websites of small, to medium size.  But, I would like my coding to be as sound, and well structured as can be

thanks for the help!

答: I don't think you should do just one thing, but several things.  Learn a good PHP framework.  I recommend Kohana, which will also teach you MVC.  (It was branched from CodeIgniter.  See this question for a comparison.)  Add some JavaScript, whether jQuery  or Prototype.  To that, add some CSS, perhaps YAML to start with.  Using libraries will help you get functional faster, but I'm not sure that is your goal.  For all of these, play with them, learn how they work, customize them, experiment, and enjoy.  Having fun is the single best thing for wanting to learn even more.</p>

OwnerDisplayName: David

Title: Php: Whats my next step?


答: SQL, easily the language most widely used by non-programmers, does #3, for whatever that's worth.  In my experience observing and assisting non-programmers writing SQL, this behavior is generally well understood and easily compensated for (with a case statement or the like).  It helps that the error message you get tends to be quite direct e.g. in Postgres 9 you get "ERROR:  division by zero".</p>

Title: How to handle divide by zero in a language that doesn't support exceptions?

Body:
I'm in the middle of developing a new programming language to solve some business requirements, and this language is targeted at novice users. So there is no support for exception handling in the language, and I wouldn't expect them to use it even if I added it.

I've reached the point where I have to implement the divide operator, and I'm wondering how to best handle a divide by zero error?

I seem to have only three possible ways to handle this case.

Ignore the error and produce 0 as the result. Logging a warning if possible.

Add NaN as a possible value for numbers, but that raises questions about how to handle NaN values in other areas of the language.

Terminate the execution of the program and report to the user a severe error occurred.

Option #1 seems the only reasonable solution. Option #3 is not practical as this language will be used to run logic as a nightly cron.

What are my alternatives to handling a divide by zero error, and what are the risks with going with option #1.


答:
I think the problem is " targeted at novice users. --> So there is no support for ..."

Why are you thinking that exception handling is problematic for novice users?

What is worse? Have a "difficult" feature or have no idea why something happened? What could confuse more? A crash with a core dump or "Fatal error: Divide by Zero"?

Instead, I think is FAR better to aim for GREAT message errors. So do instead: "Bad calculation, Divide 0 / 0" (ie: Always show the DATA that cause the problem, not just the kind of problem). Look at how PostgreSql do the message errors, that are great IMHO.

However, you can look at other ways to work with exceptions like:

http://dlang.org/exception-safe.html

I also have dream on build a language, and in this case I think that mix a Maybe/Optional with normal Exceptions could do be the best:

```<code>def openFile(fileName): File | Exception
    if not(File.Exist(fileName)):
        raise FileNotExist(fileName)
    else:
        return File.Open()

#This cause a exception:

theFile = openFile('not exist')

# But this, not:

theFile | err = openFile('not exist')
</code>```

Body:
I think the problem is " targeted at novice users. --> So there is no support for ..."

Why are you thinking that exception handling is problematic for novice users?

What is worse? Have a "difficult" feature or have no idea why something happened? What could confuse more? A crash with a core dump or "Fatal error: Divide by Zero"?

Instead, I think is FAR better to aim for GREAT message errors. So do instead: "Bad calculation, Divide 0 / 0" (ie: Always show the DATA that cause the problem, not just the kind of problem). Look at how PostgreSql do the message errors, that are great IMHO.

However, you can look at other ways to work with exceptions like:

http://dlang.org/exception-safe.html

I also have dream on build a language, and in this case I think that mix a Maybe/Optional with normal Exceptions could do be the best:

def openFile(fileName): File | Exception
    if not(File.Exist(fileName)):
        raise FileNotExist(fileName)
    else:
        return File.Open()

#This cause a exception:

theFile = openFile('not exist')

# But this, not:

theFile | err = openFile('not exist')


问:
How did separation of code and data become a practice?
Please read the question carefully: it asks how, not why.

I recently came across this answer, which suggests using a database to store immutable data:

It sounds like many of the magic numbers you describe - particularly if they are part dependent - are really data, not code. [...]  It may mean an SQL type database, or it may simply mean a formatted text file.

It would seem to me that if you have data that is part of what your program does, then the thing to do is to put it in the program. For example, if your program's function is to count vowels, what's wrong with having vowels = "aeiou" in it? After all, most languages have data structures designed for precisely this use. Why would you bother to separate data by putting it in a "formatted text file", as suggested above? Why not just make that text file formatted in your programming language of choice? Now is it a database? Or is it code?

I'm sure some will think this is a dumb question, but I ask it in all seriousness. I feel like "separate code and data" is emerging culturally as some sort of self-evident truth, along with other obvious things like "don't give your variables misleading names" and "don't avoid using whitespace just because your language considers it insignificant".

Take for example, this article: The Problem with Separating Data from Puppet Code. The Problem? What problem? If Puppet is a language for describing my infrastructure, why can't it also describe that the nameserver is 8.8.8.8? It seems to me that the problem isn't that code and data are mingled,1 but that Puppet lacks sufficiently rich data structures and ways to interface to other things.

I find this shift disturbing. Object oriented programming said "we want arbitrarily rich data structures", and so endowed data structures with powers of code. You get encapsulation and abstraction as a result. Even SQL databases have stored procedures. When you sequester data into YAML or text files or dumb databases as if you are removing a tumor from the code, you lose all of that.

Can anyone explain how this practice of separating data from code came to be, and where it's going? Can anyone cite publications by luminaries, or provide some relevant data that demonstrates "separate code from data" as an emerging commandment, and illustrates its origin?

1: if one can even make such distinctions. I'm looking at you, Lisp programmers.

答:
Ok, lets assume you want to write some kind of c++ program for your leisure. You know exactly what it has to do and what it will never need to do.
Now take any book on "modern software design". Heres the rule of the game: For every class in your project and every even so tiny case you have to implement each and every fancy pattern you find described in that book in order to make your code a "clean design" . Well, "dependency injection" will be enough for many ppl, I guess. (It's c++, not java!)
Programming is taught from a more and more theoretical point of view. It is not sufficient you get the job done, you have to write code that is maintanable, fool prove... all fine and right. The problem starts when ppl. stop thinking about the actual reason, design patterns were invented and become dogmatic.

Let me stop you writing your letter counting tool by (over)using a single simple designe principle:
When you write code that does a certain job on input data of a certain type, make sure it is able to perform that task for any given input data of that type.
- When you want to write a letter countig tool, it clearly makes sense to write it in a way so it will not only be able to count vowels, but "any letter".
- Since you might not know what the corpus you are parsing actually is, you may as well choose a very general encoding (UTF-16) and cover most (all?) written languages and their symbols.

Up to that point, we have a function with two arguments (the corpus and the letters to be counted). We are only concerned to find a reasonably general "type" or "class" the letters belong too: we certainly can do better than ASCII symbols!

Enter a demon wielding the "generalisation and reusability"-dogma:
- Why not count any symbol of any class in a input stream of that class? (abstract from letters to bit sequences of arbitrary but finite length as that is the most general you can get with a computer...)
- Wait, even then we are still counting in natural numbers. However counting can be generalized as a mapping from a countable set to itself fulfilling the axioms ... [you get the idea]

Now that example might be silly, but if you consider more complex design tasks than a counting tool you might well find all opportunity to introduce additional abstraction required according to some kind of design pattern you found in your book.

Seperation of "data" and "code" will probably be either trivial (function arguments) or you will find yourself treating invariants as variable ("data").

If there is ever any confusion it is likely about "interfaces" and "services" and all the class specifics (eg. types) being suddenly "data", that is dependencies to be injected from outside.
I feel that informatics courses taught at university have become much like lectures in philosophy and there is less time for real projects so that students can gain experience how to make software that works.
If you ever wonder why you are required to use an insanely complex pattern instead of an obvious solution, this developement is (likely) how that requirement was "created"...

To your specific problem:
If you could
1.) write a program with a maximum of hard-coding for your specific case
and then
2.) generalize from that code in a straight forward way by eg. introducing more function arguments and using other "trivial patterns"
you can be sure you are separating code and data, the obvious way, like it has been done since functional programming had be invented. (ofc you skip 1. and do 2. instantly...)

Anything non-obvious here is likely a case of "theory-deadlock": Like writing an interface refering to an interface and yet another interf... and at the end you have a neat little xml-file in order to configure all these interfaces and the dependencies to be injected into your class-interface-clutter.

Lets just hope, the xml-parser you then require does not need an xml-config in order to work...


答:
I liked the ternary operator where you provide an alternate value in case the denumerator is 0.

One more idea I didn't see is to produce a general "invalid" value. A general "this variable doesn't have a value because the program did something bad", which carries a full stack trace with itself. Then, if you ever use that value anywhere, the result is again invalid, with the new operation attempted on top (i.e. if the invalid value ever appears in an expression, the entire expression yields invalid and no function calls are attempted; an exception would be boolean operators - true or invalid is true and false and invalid is false - there may be other exceptions to that, too). Once that value is no longer referenced anywhere, you log a nice long description of the entire chain where things were wrong and continue business as usual. Maybe email the trace to the project lead or something.

Something like the Maybe monad basically. It will work with anything else that can fail, too, and you can allow people to construct their own invalids. And the program will continue to run as long as the error isn't too deep, which is what is really wanted here, I think.


答:
IEEE 754 actually has a well defined solution for your problem. Exception handling without using exceptions  http://en.wikipedia.org/wiki/IEEE_floating_point#Exception_handling

```<code>1/0  = Inf
-1/0 = -Inf
0/0  = NaN
</code>```

this way all your operations make mathematically sense.

\lim_{x \to 0} 1/x = Inf

In my opinion following IEEE 754 makes the most sense since it ensures that your calculations are as correct as it going to be on a computer and you are also consistent with the behaviour of other programming languages.

The only problem that arises is that Inf and NaN are gonna contaminate your results and your users will not know exactly where the problem is coming from. Take a look at a language like Julia that does this quite well.

```<code>julia> 1/0
Inf

julia> -1/0
-Inf

julia> 0/0
NaN

julia> a = [1,1,1] ./ [2,1,0]
3-element Array{Float64,1}:
   0.5
   1.0
 Inf

julia> sum(a)
Inf

julia> a = [1,1,0] ./ [2,1,0]
3-element Array{Float64,1}:
   0.5
   1.0
 NaN

julia> sum(a)
NaN
</code>```

The division error is correctly propagated through the mathematical operations but at the end the user does not necessarily know from which operation the error stems from.

edit: I didn't see the second part of the answer by Jim Pivarski which is basically what I am saying above. My bad.

Body:
IEEE 754 actually has a well defined solution for your problem. Exception handling without using exceptions  http://en.wikipedia.org/wiki/IEEE_floating_point#Exception_handling

1/0  = Inf
-1/0 = -Inf
0/0  = NaN

this way all your operations make mathematically sense.

\lim_{x \to 0} 1/x = Inf

In my opinion following IEEE 754 makes the most sense since it ensures that your calculations are as correct as it going to be on a computer and you are also consistent with the behaviour of other programming languages.

The only problem that arises is that Inf and NaN are gonna contaminate your results and your users will not know exactly where the problem is coming from. Take a look at a language like Julia that does this quite well.

julia> 1/0
Inf

julia> -1/0
-Inf

julia> 0/0
NaN

julia> a = [1,1,1] ./ [2,1,0]
3-element Array{Float64,1}:
   0.5
   1.0
 Inf

julia> sum(a)
Inf

julia> a = [1,1,0] ./ [2,1,0]
3-element Array{Float64,1}:
   0.5
   1.0
 NaN

julia> sum(a)
NaN

The division error is correctly propagated through the mathematical operations but at the end the user does not necessarily know from which operation the error stems from.

edit: I didn't see the second part of the answer by Jim Pivarski which is basically what I am saying above. My bad.


答:
There are two fundamental reasons for a divide by zero.

In a precise model (like integers), you get a divide by zero DBZ because the input is wrong. This is the kind of DBZ that most of us think of.

In non-precise model (like floating pt), you might get a DBZ because of rounding-error even though the input is valid. This is what we don't normally think of.

For 1. you have to communicate back to the users that they made a mistake because they are the one responsible and they are the one who know best how to remedy the situation.

For 2. This is not user fault, you can finger point to algorithm, hardware implementation, etc but this is not user's fault so you shouldn't terminate the program or even throw exception (if allowed which is not in this case). So a reasonable solution is to continue the operations in some reasonable manner.

I can see the the person asking this question asked for case 1. So you need to communicate back to the user. Using whatever floating point standard, Inf, -Inf, Nan, IEEE doesn't fit in this situation. Fundamentally wrong strategy.


问:
Deprecate a web API: Best Practices?
Eventually you need to depreciate parts of your public web API. However I'm confused on what would be the best way to do it. If you have a large 3rd party app base just yanking old versions of the API seems like the wrong way to do it as almost all apps would fail overnight. However you can't keep ancient web api's available forever as it might be outdated or there are significant changes that make working with it impossible. </p>

<p>What are some best practices for deprecating old web api's? </p>

答:
In addition to the existing answers, you should provide a drop-in replacement or a migration plan when removing something, so your users can update their code.

Try to avoid removing functionality without providing an alternative - this would make some of your users unhappy.

Title: Deprecate a web API: Best Practices?


问:
Deny use of my library to compete a certain company
I'm developing a library for reading/writing a file format of a program created by a certain company. The guys from that company were so kind that they provided me with a documentation for their format, which I'm really grateful for.

I'm intending to release the library as open-source under a license "derived" from MIT, the difference being that the library must not be used to create a program that would compete with the original program, as an expression of my gratefulness to the company.

What I'm asking: is adding this rule to the license legally possible?

答:
It is legally possible to add such a restriction to your license, but I would strongly advise against it.

Such restrictions take the license out of the realm of open-source software. All commonly accepted definitions of open-source disallow such restrictions on the usage of the software.

Drafting such a restriction so that it would hold up in court is hard and the gain is very small.

If you were given the specifications for the file format without such strings attached, then the chances are that the company feels secure enough that they don't fear competition from others that can work with their file format. Thus there is no need to restrict the usage of your library.


答:
Instead of trying to add such a restriction, you could alternatively make your library GPL, or dual-licensed - GPL & commercial, with an individual pricing for each one who want to use the commercial version.

That way it will still be possible for someone else to write a competing open-source software using your lib, but it will typically discourage bigger commercial vendors. When someone is really going to buy your lib, you can still decide in each case whom you will sell the lib for a moderate price, or whom you will make an offer so expensive he won't buy it.

Title: Deny use of my library to compete a certain company

Body:
I'm developing a library for reading/writing a file format of a program created by a certain company. The guys from that company were so kind that they provided me with a documentation for their format, which I'm really grateful for.

I'm intending to release the library as open-source under a license "derived" from MIT, the difference being that the library must not be used to create a program that would compete with the original program, as an expression of my gratefulness to the company.

What I'm asking: is adding this rule to the license legally possible?


问:
How to canonise a road network
I am working on geographical data which represents the road network of some city and I need to automatically fix inaccuracies in the data.

Data was manually produced by “drawing” the road network over some actual map overlay with a geographical system like qgis.  As a result, many road portions which connect in reality are not connected in the data, that is, endpoints of connected roads might be off by a few centimeters or sometimes a few meters.

As a result, the road network is “wrongly” digitized as a graph or combinatorial object—that is, the simple algorithm assuming that roads are connected when they have a common endpoint is too optimistic and misses a lot of connections.  How can I process and fix the geographic data to recover the correct combinatorial road network?

答:
I had to perform the treatment you describe on the road network of German city (about 200.000 inhabitants).  I devised a procedure that produced great results:  the road network has over 2000 road portions and about 200 connection failures and the procedure was able to fix automatically 95% of the failures and to mark the remaining ones as “requiring attention”.  There were so few of them that manual editing was affordable.

Let me now go into the details.

Wishlist

We want to build a procedure which, given the set M of missing or faulty connections,

detects and fixes automatically a large subset A of M

detects problematic places P in the network that require manual treatment.

We want to conduct step 1. without producing any false positive i.e. without introducing non-existant connections, i.e. enforcing the condition “A is a subset of M”.

We want to conduct step 2. so that all of M is in the union of A and P.  It is fine to have false positives here, as long as the ratio ”false positive / true positive” remains low.

Algorithm

The input is a road network R, i.e. a list of road portions (broken lines) represented by the list of their vertices. (This is what is stored in ESRI files.)

The output is an amended road network S together with a list P of places (points) requiring manual treatment.

Choose two thresholds α = 2.5m and β = 20m

Replace R by an equivalent network where road portions can only cross at a vertex and where if two road portions have points whose distance is smaller than α then they have two vertices whose distance is smaller than α.  This is achieved by introducing supplementary vertices in the descriptions of road portions.

Go through all the vertices of all the road portions of the road network and create equivalence classes for the relation A “vertices are closer than α” and B ”vertices are closer than β”.

To each equivalence class of A associate a point (e.g. center of mass) and replace each member of the class by that point.  The result is the final network S.

To each equivalence class of B not reduced to a point associate a point (e.g. center of mass), the list of points thus obtained is P.

Title: How to canonise a road network


问:
Sequence diagrams and the Implementation
In the design phase we create UML Sequence diagrams (in OOD). My understanding is that after creating an Use Case diagram if we need to show further information in terms of time sequence of events of that Use Case, we can go for sequence diagrams.

My question is, should a sequence diagram represent exact implementation details? If I ask in another way, should all method calls and object interactions in the implementation be shown in the Sequence Diagram? Or else it should present a high level picture of the implementation?

Normally in the implementation, things could be implemented with slight differences than specified in design diagrams. So that if a sequence diagram should show exact implementation details, we might have to revise them after the implementation.

Another related question would be, who are the audiences of these sequence diagrams other than the author? An answer for this question might answer the original question as well.

答:
At a very high level, sequence diagrams can represent high-level interactions between systems or sub-systems at a high level.

If they represent interactions between actual classes (or interfaces) they're nice because each message in the diagram corresponds directly to a method that class must have. You can almost write your code from the sequence diagrams by capturing the messages as methods.

If they represent interactions between services, each message represents a request or resource that the receiving APIs must support.

As for level of detail, I've created sequence diagrams that represent high-level interactions, with many implementation details left out, for the purposes of design documentation. But I've also created really detailed sequence diagrams that spell out specific methods and even parameters between classes.

It largely depends on what your needs are. I've found sequence diagrams to be a great way to both understand and communicate solutions where the requirements are big and complicated, as well as a way to do class design at a very specific level of detail.


答:
I would say go as high level as you can while still including all the necessary method calls, etc for your topic. My reasoning for this is that if you're including every single interaction then you might as well just write the code yourself.

Personally, I have always viewed sequence diagrams more or less as "guidance" for the implementer. I've never viewed them as living documents - if the implementation differs from the design I won't go update the diagram (unless it's different because my design was wrong). However, you're right in assuming that it largely depends on the audience.

If you have a team full of experienced developers with knowledge of your product, you should be able to leave a few things out here and there and trust them to fill in the blanks with their best judgement. In my case, I usually confine my sequence diagrams to a particular topic, say "Process XYZ", and only show method calls and object interactions that are relevant to that topic, leaving out things in between that are obvious or are defined in another diagram. If I'm writing a diagram for a junior developer who's learning the project and domain, then I tend to be more specific.

The only reason I would include every single method call and interaction is if you're actually generating the code from the model. For example, I've worked on some embedded systems where we generate our code out of a Rhapsody model, so obviously in that case you should include as much as you can.

Title: Sequence diagrams and the Implementation

Body:
In the design phase we create UML Sequence diagrams (in OOD). My understanding is that after creating an Use Case diagram if we need to show further information in terms of time sequence of events of that Use Case, we can go for sequence diagrams.

My question is, should a sequence diagram represent exact implementation details? If I ask in another way, should all method calls and object interactions in the implementation be shown in the Sequence Diagram? Or else it should present a high level picture of the implementation?

Normally in the implementation, things could be implemented with slight differences than specified in design diagrams. So that if a sequence diagram should show exact implementation details, we might have to revise them after the implementation.

Another related question would be, who are the audiences of these sequence diagrams other than the author? An answer for this question might answer the original question as well.


问:
Gathering IP address and workstation information; does it belong in a state class?
I'm writing an enterprisey utility that collects exception information and writes to the Windows Event Log, sends an email, etc. This utility class will be used by all applications in the corporation: web, BizTalk, Windows Services, etc.

Currently this class:

holds state given to it via public properties

calls out to .NET Framework methods to gather information about runtime details. Included are call to various properties and methods from System.Environment, Reflection details, etc.

This implementation has the benefit of allowing all those callers not to have to make these same calls themselves. This means less code for the caller to forget, screw up, etc.

Should this state class (please what's the phrase I'm looking for [like DTO]?) know how to resolve/determine runtime details (like the IP address and machine name that it's running on)?

It seems to me on second thought that it's meant to be a class that should hold state, and not know how to call out to the .NET Framework to find information.

```<code>var myEx = new AppProblem{MachineName="Riker"};

//Will get "Riker 10.0.0.1" from property MachineLongDesc
Console.WriteLine("full machine details: " + myEx.MachineLongDesc);

public class AppProblem
{
    public string MachineName{get;set;}
    public string MachineLongDesc{
        get{
            if(string.IsNullOrEmpty(this.MachineName)
            {
                this.MachineName = Environment.MachineName;
            }
            return this.MachineName + " " + GetCurrentIP();
        }
    }

    private string GetCurrentIP()
    {
        return System.Net.Dns.GetHostEntry(this.MachineName)
                     .AddressList.First().ToString();
    }
}
</code>```

This code was written by hand from memory, and presented for simplicity, trying to illustrate the concept.

答:
I would create a model/business entity/data transfer object/POCO (whatever you wish to call them) class which just holds the data which you have retrieved. I would then create a class which would call the appropriate API's to collect the data and pass back your populated model object to be consumed by the report/saved to persistence medium.

I'm working on quite a large project right now which collects Windows server configuration data. I have built various repository classes to collect the data from the servers using WMI/registry etc which populates a model object according to the area of interest. For example, I have a repository which collects services data populating and returning a ServicesData model, another collects network card data, populating a NicData model ...


问:
Trying to come up with a mapping convention for C# objects
so this is C# but it could apply to any OO language where different sets of objects exist across different layers of an application.

We have been trying to come up with a convention within the team for where to put the code when mapping objects in one layer to objects in another layer. For example; mapping a Data Transfer Object to a Service Object that is used by a WCF service, or something of the like.  I have the following methods that I have seen being used and am trying to decide which would be preferred by someone new looking at the code, and which of these fits best with the natural C# idioms.

These examples use AutoMapper to map an object Foo to an object Bar, but it applies to any mapping framework, or just manually creating Bar from Foo with an object initialiser.  Both these objects represent the same data, but they are in different assemblies:

1) Constructor on Bar

```<code>public class Bar
{
    public Bar(Foo foo)
    {
        Mapper.Map(foo, this);
    }
}
</code>```

2) Factory method on Bar

```<code>public class Bar
{
    public static Bar CreateFrom(Foo foo)
    {
        return Mapper.Map<Bar>(foo);
    }
}
</code>```

3) Method on Foo to return Bar

```<code>public class Foo
{
    public Bar GetBar()
    {
        return Mapper.Map<Bar>(this);
    }
}
</code>```

4) Explicit type conversion operator on Foo so it can be casted to Bar

```<code>public class Foo
{
    public static explicit operator Bar(Foo foo)
    {
        return Mapper.Map<Bar>(foo);
    }
}
</code>```

5) Some implementation of the factory pattern

```<code>public class BarFactory : IFactory<Bar>
{
    public Bar Create(Foo foo)
    {
        return Mapper.Map<Bar>(foo);
    }
}
</code>```

6) Just doing it in the piece code you need it in

```<code>    public void SomeMethod()
    {
        Foo foo = fooRepository.GetFoo();

        //I need it to be bar now...
        Bar bar = Mapper.Map<Bar>(foo);

    }
</code>```

Disclaimer: I wish I hadn't used AutoMapper in this example.  Just imagine "AutoMapper" here reads "IMappingProvider" or "IObjectConverter" or something

答:
I would write a mapper class and manually map the data from one type to the other. Yeah it's boilerplate, but you are fully in control, it's simple and it does the job. I would keep it out of the model assembly as your model objects shouldn't have any knowledge of the WCF returned types.</p>

```<code>public class FooMapper
{
    public Foo Map(Bar bar)
    {
        return new Foo
            {
                ValueOne = bar.ValueOne,
                ValueTwo = bar.ValueTwo,
                ....
            };
    }
}
</code>```

Body:
I would write a mapper class and manually map the data from one type to the other. Yeah it's boilerplate, but you are fully in control, it's simple and it does the job. I would keep it out of the model assembly as your model objects shouldn't have any knowledge of the WCF returned types.

public class FooMapper
{
    public Foo Map(Bar bar)
    {
        return new Foo
            {
                ValueOne = bar.ValueOne,
                ValueTwo = bar.ValueTwo,
                ....
            };
    }
}


问:
How can I judge whether a project is particularly complex or if I'm just slow in picking it up?
I'm making little progress on a major project.  The source is massive, many layers of objects, macaroni code, double-diamond graphs of multiple inheritance, half-baked features frozen when the original writer left, and no one knows why many pieces of it were designed the way they were.

I suppose any competent programmer would have some trouble figuring it all out well enough to fix bugs, finish the half-baked stuff and add new features.  However, I suspect I'm going slower than a typical programmer.

How do I judge whether the source is unusually bad and I'm just doing as well as anyone could, versus the source is typical for a project like this and I'm just slow-witted or underskilled?

答: How about taking a different view:  What do you need to know about this code and do you have a way to measure that?  For example, if you are trying to fix a bug, that may require a different kind of dive than if you were trying to migrate the code from one language to another,e.g. going from VBScript to C#.  If you are trying to get all the requirements out of the current code, that may take a while though I suspect most people would have that kind of problem.</p>


问:
How to handle divide by zero in a language that doesn't support exceptions?
I'm in the middle of developing a new programming language to solve some business requirements, and this language is targeted at novice users. So there is no support for exception handling in the language, and I wouldn't expect them to use it even if I added it.

I've reached the point where I have to implement the divide operator, and I'm wondering how to best handle a divide by zero error?

I seem to have only three possible ways to handle this case.

Ignore the error and produce 0 as the result. Logging a warning if possible.

Add NaN as a possible value for numbers, but that raises questions about how to handle NaN values in other areas of the language.

Terminate the execution of the program and report to the user a severe error occurred.

Option #1 seems the only reasonable solution. Option #3 is not practical as this language will be used to run logic as a nightly cron.

What are my alternatives to handling a divide by zero error, and what are the risks with going with option #1.

答:
As you a writing a programming language, you should take advantage of the fact and make it mandatory to include an action for the devise by zero state.
 a <= n / c :0 div-by-zero-action

I know what I've just suggested is essentially adding a 'goto' to your PL.


问:
Is testability and mockability really that important in web development?
I'm reading this series on Laravel, and it's in great depth dealing with making everything testable, using Repository instead of just using the Models, using Dependency Injection and other obscure techniques.

I've got a feeling that adding all this extra complexity in the name of Testability may not be the right thing. Writing unit tests for everything, that sounds plain silly.

I have used Laravel before, without all this "testability" stuff, and it just worked.

Is "testability" worth the effort and making code harder to understand?

(note that I'm posting here instead of StackOverflow, for this is kind of opinion based. I hope I won't be frowned upon for asking it.)

答:
There's a fair amount of debate in terms of when, where, and how to test an application of X complexity. And a fair amount of political zeal on all sides. In my own experience, I've been on a lot of projects that were small and simple, arguably requiring little automated testing. And truthfully, I developed with nearly zero automated testing and horrendously untestable code for 10+ years with no visible repercussions.

As time went on, I found that the complexity in these "simple" applications slowly grew. And as complexity grows, you'll more often track bugs to minute changes to a methods functioning that were benign seeming at the time. Or you'll find team members using a method wrong because it breaks a convention or doesn't match their expectations.

If you have high code coverage, these concerns are far lessened. And if you test first, you're more likely to write testable code that behaves as others would expect. You're starting with testable expectations; you're not contorting tests to match untestable code or letting expectations be biased by your implementation ideas. You're writing code to pass a meaningful test. (Make your tests meaningful.)

Testability is just a natural concern if you want to test. And you do want to test! The question is whether you want to automate that testing. (And you do.) Most complex applications benefit greatly from automated testing. Simple ones benefit too. And if you're tempted to forgo the testing because it adds more complexity than is initially inherent to the application, remember that most applications eventually become complex anyway.

In the interest of full disclosure, I've actually only been attempting to make my code more test-driven and more highly testable quite recently. That said, the number of bugs my automated tests have revealed and prevented is significant. My confidence in the highly-covered code has exponentially increased. My code has gotten prettier. And I've been more continuously motivated to write and satisfied with the successful outcome of every line of of code since I transitioned.

... I feel a bit like a brain-washed cult-member. But, it's all true!


问:
Setting fields with correct default value
When writing constructors, I regularly encounter a situation where some fields already have approperiate (default) values, such as false for boolean values and 0 for integers. What are reasons to emphasize these values, for example like:

state = 0;

Do you appreciate it when reading someones code? On one side I feel like expressing implementation details explicitly, on the other side I find it pointless to set a field when I'm sure it is already correct.

答:
I work in a projects company. I LOVE it when default values our explicitly defined in the code. This also implies:
1. Definition of the data - is the data type used correct ?
2. The semantic definition of a value - Like in your example, 0 is a clue for an initial state. In some cases I get no clue what 0 means.

Note :
State MUST be defined somewhere, be it a CONST value, or an enumeration somewhere. The value 0 has no other meaning than initial state. A string literal might add some more value to it.


答:
Just because you're sure it is correct, that intern over in the other building has no idea. Giving objects a nice sane default is good. Being explicit is good.

And remember, code is there for humans, not computers.

Title: Setting fields with correct default value

Body:
When writing constructors, I regularly encounter a situation where some fields already have approperiate (default) values, such as false for boolean values and 0 for integers. What are reasons to emphasize these values, for example like:

state = 0;

Do you appreciate it when reading someones code? On one side I feel like expressing implementation details explicitly, on the other side I find it pointless to set a field when I'm sure it is already correct.


问:
How to deal with Interviews where HR is missing?
The situation:

Person X, who already has a full-time job, applies to Company A. Money is good at A, but the real reason X had applied is 'cause the work at A really excites X.

Next someone from the technical dept. from A calls up X, gives some assignment and holds a round of technical interview over phone. X does very well in all of it so far.

Finally, X asks the tech guy from A "What's next?" The guy says we'd get back to you in 3-4 days time and then doesn't call up in the next 3-4 days. X is confused. He's got the mail-id of the tech guy but not sure if he should inquire -- this is no HR after all. In fact HR was never anywhere in this process. What should he do?

My Take: Don't mail. You already have a full-time job and this shows desperation.

The Problem: This isn't me and people tell me that some companies wait for candidate to get back just to double check their interest level.

Update

Mailing the engineering team proved very useful, they apologized for being busy and now I am told the next round is early January.

答:
If this is a consulting job: Mail

Ok, you should mail no matter what kind of job it is, but I was in the same situation when I applied for a consulting company.  At contract-based companies, it's generally a good idea (and makes economic sense) to hire someone when they can immediately be put on a project.  They could just be waiting on a project to come up to hire you for, rather than say "Absolutely you're hired, except we don't actually have work for you right now....can you wait a few weeks or months until something comes up?".  Most people will run if they know it will take months to place you, so there may be many tactics to hold you off.  So, if it's a consulting gig, which is always exciting work (IMHO), then send them a follow up.  They need to know that you aren't just "testing the waters" and that you mean business (and that you appreciate them enough to care about their decision).


问:
Should I Make my ASP.NET MVC N-tier?
I'm currently building a very small website, around 20 to 30 views, 10 controllers.

I know MVC is only a design pattern and should only be the top presentation layer.
I'm currently at a stage in development when you start question yourself and what you're doing. It feels like this small website don't 'need' the N-tier architecture because it's too small for that. But in the long run maybe it's worth it.

Is it worth the time to migrate to N-Tier?

IS there some level of abstraction when you should migrate to n-tier? Is there some magic point when the project grows too large? Or should it be done directly in the beginning of the development?

答:
Let's look at some questions I ask when I am building a website:

Do you expect your website to grow in either views or complexity?

Do you expect there to be more "pages" in the future?

Do you know that you will need a data provider on the back end at some point in the future, even if not currently?

Will you have other developers working on this site, possibly at the same time as you?

If you can answer yes to all (or most) of the above questions, then it is worth the time and effort to build out the n-tier framework. If you will have multiple developers working on it at the same time, that would almost guarantee (at least to me), that the additional effort will be worth it.

If you can't, then it may not be worth the effort.

Title: Should I Make my ASP.NET MVC N-tier?


答:
Well, let's evaluate what you are asking first.

Your application is currently a Model-View-Controller application.  What does that mean?  It means your application has:

A Presentation layer, the View,

An Application Processing Layer, the Controller, and

A Data Management Layer, the Model.

What would it take to convert it to N-tier?  Well, according to Wikipedia, a Multi-Tier application is

a client–server architecture in which presentation, application processing, and data management functions are physically separated.

Hmm, seems like you have multi-tier already.

If you don't buy that, then make your Data Layer a web service.  That way your MVC application will be able to access it, and so will your mobile application, your desktop application, or any other application that you wish to write.

In any event, multi-tier is primarily about scaling applications to multiple machines.  Writing web services accomplishes that in part, but so does splitting parts of your application to multiple machines on the same intranet.  Whether or not you need all this depends entirely on your application and its scope.

Title: Should I Make my ASP.NET MVC N-tier?

Body:
I'm currently building a very small website, around 20 to 30 views, 10 controllers.

I know MVC is only a design pattern and should only be the top presentation layer.
I'm currently at a stage in development when you start question yourself and what you're doing. It feels like this small website don't 'need' the N-tier architecture because it's too small for that. But in the long run maybe it's worth it.

Is it worth the time to migrate to N-Tier?

IS there some level of abstraction when you should migrate to n-tier? Is there some magic point when the project grows too large? Or should it be done directly in the beginning of the development?


问:
PHP Cache Strategy - Genius or Sheer Stupidity?
I have a shared hosting with limited capabilities. Memcache and mod_cache are not available to me. I would like to implement my own PHP caching method to cache the results of load-intensive SQL query. Using summary tables in SQL is not an option because the query takes multiple parameters that can assume thousands of different values (it's a statistical system).

My idea is like this

```<code>function execQuery($parameter)
{
     $query = "SELECT ....... " . $parameter; //query code has been generated

     $rand = mt_rand(0,10);
     //no need to check/save expiry dates,generate cache randomly for speed

     if($rand == 0)
     {
           //execute query normally and generate new cache
           $result = mysql_query($query);
           $md5 = md5($query); // the name of the cache file equals the md5 of the query
           $cache_file = fopen("/cache/" . $md5 ."php", "w");
           fwrite($cache_file, $result); // the result is written as php code generating a ready for use result array, code has to be modified I think
           //return the result
     }
     else
     {
            //cache will be used
            $md5 = md5($query);
            if(file_exists("/cache/" . $md5 ."php"))
            {
                  include("/cache/" . $md5 ."php");
                  return $result;
            }
            else
           {
                  //no cache exists, run query normally and generate cache
           }
     }
}
</code>```

What do you think of this and what are the possible pitfalls? What are the implications of using mt_rand, md5? Do you think they will out-perform a load-intensive query? Are the multiple system file writes worth it (only one write for every 10 hits and can be even increased)? Improvements and suggestions are highly welcomed.

答:
Basically you want to create a unique key for every query that you can use to find corresponding result in cache. So, should be something like

```<code>$key = md5(query);
</code>```

Then you test that key, in your example, if the file "/cache/$key.php" exists the you return the content otherwise run the query.

Of course the cache will go stale, so you also want how old is that entry, you can stat() the file to get the time and unlink() the file if it's too old (e.g. 30s).
You also want to have the same cache invalidating mechanism available to parts of the system that update the data so they always get the latest data.

OwnerDisplayName: Husein

Body:
Basically you want to create a unique key for every query that you can use to find corresponding result in cache. So, should be something like

$key = md5(query);

Then you test that key, in your example, if the file "/cache/$key.php" exists the you return the content otherwise run the query.

Of course the cache will go stale, so you also want how old is that entry, you can stat() the file to get the time and unlink() the file if it's too old (e.g. 30s).
You also want to have the same cache invalidating mechanism available to parts of the system that update the data so they always get the latest data.


问:
Is SourceSafe really safe?
Having spent all morning trying to check something in - I now realise I've lost a couple of days worth of work.

Its happened before - and is apparently common occurrence with SourceSafe.  Can SourceSafe be used successfully, without problems, and if so, how?

答:
I may get down voted to hell on this, but ..

VSS effectively puts you on dope, to the extent that you can't reconcile any sort of reality needed to realize that your now borked repo wasn't your fault.

Please, don't use it, ever.

Title: Is SourceSafe really safe?


问:
Is it a good idea to "#define me (*this)"?
This macro can be defined in some global header, or better, as a compiler command line parameter:

```<code>#define me (*this)
</code>```

And some usage example:

some_header.h:

```<code>inline void Update()
{
    /* ... */
}
</code>```

main.cpp:

```<code>#include "some_header.h"

class A {
public:
    void SetX(int x)
    {
        me.x = x;
        me.Update();
    }

    void SomeOtherFunction()
    {
        ::Update();
    }

    /*
        100 or more lines
        ...
    */

    void Update()
    {
        // ...
    }

    int x;
};
</code>```

So in a class method when I access a class member, I am always using me, and when accessing a global identifier I always use ::. This gives the reader which is not familiar with the code (probably myself after a few months) localized information of what is accessed without the need to look somewhere else. I want to define me because I find using this-> everywhere too noisy and ugly. But can #define me (*this) be considered a good C++ practice? Are there some practical problematic points with the me macro? And if you as C++ programmer will be the reader of some code using the me macro, would you like it or not?

Edit: Because many people arguing not specificaly contra using me, but generaly contra explicit this. I think it may not be clear what are benefits of "explicit this everywhere".

What are benefits of "explicit this everywhere"?

As a reader of the code you have certainty what is accessed and you can concentrate on different things than verify - in some distant code - that is really accessed what you think is accessed.

You can use search function more specifically. Search "this->x" can give you more wanted results than only search "x"

When you are deleting or renaming some member, compiler reliably notifies you at places where is this member used. (Some global function can have same name and exist chance you can introduce error if you are not using explicit this).

When you are refactoring code and making non-member function from member (to make better encapsulation) explicit this shows you place which you must edit and you can easily replace this with pointer to instance of class given as non-member function parameter

Generally when you are changing code, there are more posibilities to errors when you are not using explicit this than when you are use explicit this everywhere.

Explicit this is less noisy than explicit „m_“ when you are acessing member from outside (object.member vs object.m_member) (thanks to @Kaz to spot this point)

Explicit this solves problem universaly for all members – attributes and methods, whereas „m_“ or other prefix is practicaly usable only for attributes.

I would like to polish and extend this list, tell me if you know about other advantages and use cases for explicit this everywhere.

答:
I suggest not to do this. This gives a reader which is not familiar with your macro a big "WTF" whenever he sees this. Code does not get more readable when inventing "new conventions" over the generally accepted ones without any real need.

using this-> everywhere is too noisy and ugly

That may seem so to you, maybe because you did a lot of programming in languages using the keyword me (Visual Basic, I guess?). But in fact it is just a matter of becoming accustomed to it - this-> is pretty short, and I think most of experienced C++ programmers will disagree with your opinion. And in the case above, neither the use of this-> or the use of me is appropriate - you get the smallest amount of clutter by leaving those keywords out when accessing data members inside of member functions .

If you want your private member variables to be distinguished from local ones, add something link m_ as a prefix, or an underscore as a suffix to them (but as you can see here, even this convention is "too noisy" for many people).