问:
How to select drawing system when requirements not yet known?
We're developping an application for 2D data processing and display. At the moment data is displayed by converting each point to a color depending on intensity, so in rather low level code. This works well. A new feature is displaying a grid and a bunch of lines that can be moved with the mouse on that image.

As usual when new technologies are going to be picked, I made a little demo to test some things out: using the current data plot, a line is drawn on top that can be moved up/down with the mouse, and at the same time there is text displaying the cursor coordinates. I tried some different ways: using a Canvas, using a somehwat lower level DrawingContext and using the low level WriteableBitmapEx api.

To me, there was no real difference in ease of coding nor display speed. Yes the Canvas option had a couple of lines less code than the others, while I had the impression the lower level options were somewhat faster to display. But no huge differenes making me pick one immediately.

So the problem now is: I have no idea how to select the most suitable system for the job, but it is a very important decision to make since the graphical part of the app will likely continue to grow. Needless to say it would be a small disaster if we pick A now, and in one year we figure out B would have been way better. Normally I'd select the fastest or most convenient option, or look at future requirements and use the system that seems to fit best, but in this case there is simply not enough difference, and future requirements are not exactly known: for now we think it's sufficient if we can draw lines, circles and some text, and update speed is not that important. However the application is in it's early stage, so is the underlying hardware and there are less than 100 customers. That however, might change rapidly. And so can requirements.

Question is simple: what to do? Some options I've been thinkig about:

pick one that 'feels' best (WriteableBitmapEx but probably just because I have an affinity with lowlevel stuff)

pick the one with the least amount of code (Canvas, also seems very easy on the UI level with effects and mouse events and what not)

make a more extensive demo so differences become more clear
pick one, but put everything behind an interface so the implementation can be swapped later (might be quite some work)

答:
First, you need to come to terms with the fact that you can't choose the right framework now, because you don't have enough information.  So you should choose the framework which minimizes regret if it turns out to be the wrong one.  In other words, choose the one that's most flexible.

For example, one nightmare scenario is to choose the low level framework, then it turns out all your needs are pretty standard. You spend lots of time writing, debugging and maintaining methods that are verbose and tedious in the low level framework, but already exist in the high level framework.  Well, does the high level one also allow you to write low level code when needed?  It might be the better choice.

In other words, if you don't know whether you'll be writing high level or low level code, choose a framework that's ok for both, rather than one that's really optimized for one but a disaster for the other.  A year from now, you'll know which framework you should have used, and it won't be this one.  But the more flexible one will only be a little worse than the optimal.  You need flexibility in performance as well: something that allows you to write fast code if it turns out you need to.

The other thing you can do is try to put your drawing code behind an internal interface, to allow you to swap it out later, in case you really need to.  This is harder than it sounds.  If you pick a low level framework, your interface will gravitate towards lower level concepts.  And -- surprise! -- often just the concepts in the framework.  But if you go this route, unit tests are a must.  First of all, writing a test which exercises just a given feature will force you to write that feature in a way that isn't intertwined with the rest of the code.  And second, if you later have to swap out the back end, you'll have an easy way to find out what you've broken.

Another thing to look at is, which framework has the most momentum?  Look at the mailing list archives.  Is much going on?  Perhaps a sub optimal framework will grow into a better one.  In any event, if you end up pushing a framework in ways it wasn't intended to be used, it's good to have a community of experts to ask.


问:
Point and click synonym replacement in text area with Javascript
I am trying to create a site that will allow you to type a sentence or passage of text, then click on words to bring up a list of synonyms (from an online API) and possibly authorized abbreviations from a list that I provide. Once clicked, it would replace that word with the word that was clicked on. It would function kind of like After the Deadline or a Javascript based spell checker.

Are there any libraries set up to make something like this easy, or what kind of Javascript do I need to be looking at? Are there any tutorials or examples for this kind of thing? I am aware that the source code for After the Deadline is available, but I only need a small portion of their technology, not all of the actual grammar and spelling check technology.

答:
After the Deadline uses TinyMCE, not a text area. This makes them able to decorate the edited text by underlining parts of the text, thing which wouldn't be possible in a <textarea />.

If you're not afraid deep into existent projects and if you can legally do it given their GNU GPL, you can use the After the Deadline code, taking only the part you need and throwing away everything else related to spell checking.

If, on the other hand, for any valid reason you want to start from scratch, it may not be too difficult if you use the contenteditable HTML attribute¹. When the user changes the content of a
, submit the changes to the server, get the list of synonyms, and decorate the
 by underlining the words which have synonyms. Once the user clicks on an underlined word, populate the list of synonyms.

¹ This attribute seems to be an HTML 5 one, but has a pretty good support in legacy browsers. I remember using it a few years ago, where HTML 5 wasn't so well known or used.

ContentLicense: CC BY-SA 3.0

Body:
After the Deadline uses TinyMCE, not a text area. This makes them able to decorate the edited text by underlining parts of the text, thing which wouldn't be possible in a <textarea />.

If you're not afraid deep into existent projects and if you can legally do it given their GNU GPL, you can use the After the Deadline code, taking only the part you need and throwing away everything else related to spell checking.

If, on the other hand, for any valid reason you want to start from scratch, it may not be too difficult if you use the contenteditable HTML attribute¹. When the user changes the content of a <div contenteditable="true" />, submit the changes to the server, get the list of synonyms, and decorate the <div /> by underlining the words which have synonyms. Once the user clicks on an underlined word, populate the list of synonyms.

¹ This attribute seems to be an HTML 5 one, but has a pretty good support in legacy browsers. I remember using it a few years ago, where HTML 5 wasn't so well known or used.


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

答:
One way I try to describe it to people, may not be the best way

Consider a Program that adds   2 + 2 and outputs 4

Consider a program that adds two numbers input by a user,  x + y = z

Which is more useful and general?

Title: What is abstraction?

ContentLicense: CC BY-SA 2.5


问:
When to prefer a generalized solution over solving specific cases
In programming we're often faced with a choice: cover each conceivable use case individually, or solve the general problem:

Its obvious that solving the immediate problem is faster, however creating a generalized solution will save time in the future.

How do I know when it's best to try and cover a finite list of cases, or make a generic system to cover all possibilities?

答:
How do I know when it's best to try and cover a finite list of cases, or make a generic system to cover all possibilities?

Experience.

The only way to know is to have tried one path before, seen how it's bitten you in the ass (or you've wasted a bunch of time). Repeat until you get bit in the ass less.

Even then, you don't really know; you just have a better guess.


问:
Best approach for writing a chess engine?
I'm a chess enthusiast and a programmer. I recently decided to start making a chess engine using my chess and programming knowledge. So here's my question:

What language (I'm familiar with Java, C++ and Python) and methodology should I adapt while writing a chess engine?

A little guidance would be much appreciated.

Edit:

So I decided to make it in JavaScript. I download this Chess UI from github and now I'm all set! My first step would be to write legal moves for it. So can anybody point me in the right direction? (I'm new to jQuery but have alot of programming experience).

P.S: I'm not trying to make a very efficient engine (I know its way too difficult), I just want to get familiar with the process and learn some new techniques along the way.

答:
I assume you already know about the concept of Min-Max, trees and pruning, heuristic and other basics and what I write here are just some details that might have been underestimated.

I with company a friend wrote our own chess engine sometimes ago. I share some issues and ideas we had and I hope you find them useful.

Since we both were java programmers our language turned our to be java and we started with an object oriented approach. Pieces were objects, board was object, files and ranks (rows and columns in chess literature) were objects. And this was wrong. The overhead was massive and the program was struggling to go further than 2 moves (4 ply) in the search tree.

So with some search we ended up with a brilliant idea (not ours though!): Representing pieces and board as Long integers (64bit). This makes sense because a chess board have 64 squares. The rest was bit wise operations (running very near to cpu = extremely fast). For example, consider a binary 64 bit integer in which the ones are presenting the squares on the board that your piece can attack. Now if you execute a logical "AND" between two numbers like this, a non-zero result states that you have an square with attackers. There are several ways of doing presenting the chess board and pieces, So:

1 - Decide about your Board Presentation

Then you need and opening database. Chess opening is somehow solved ant it is highly recommended to have and opening book. In this case, you have lot's of extra time in blitz games.

2 - Find yourself an opening book.

We did these, but still we were far from being good:

3 - A good chess engine should be able to see 6 moves (12 ply) ahead.

So what we did then, was to use the dead time (if it's a human vs computer engine).

4 - Use the time when opponent is thinking to create some levels of your tree.

And still we were far far away from 12 plies. By more study, we discover some tricks! For example it was suggested to skip one ply of the tree and start from the next ply (like there is no opponent). The idea is that if a move is extremely idiotic, then why to waste the time and see what are the opponents responses to that move. However, one good engine should be able to distinguish between and idiotic move and genius queen sacrifice.

5 - Learn the programming tricks for this specific problem (chess).

Me and my friend, in this state, were still bad :/
What we could do -and we partially did- was to save the calculated positions. If you calculate a position, then save it for future! The same goes for loops in the search tree. The point was to save/retrieve the efficiently:

6 - Save the data you generate...Efficiently!

and finally:

7 -  Code with maximum optimization.

This problem is extremely expensive both in CPU time and memory. It's very important to write your code very efficiently. Remember that we are talking about the branch factor of 35. This means a useless "if" somewhere in your heuristic, can be turn into 3.3792205e+18 useless "if"s somewhere deep in your search tree.

Chess programming is a very very interesting challenge and it's the time that you can put your programming capabilities into a serious test. There are few more points that I can suggest but I'm sure you will discover them by yourself. There many more points that I don't know but you can find them on internet!

Good luck and have fun!

p.s. I don't know javascript very well but something is telling me base on the difficulty of the problem, maybe, considering all that C++ can offer, it would be a better to drop javascript and do it in C++.


问:
Use cases for "private" interfaces?
I was wondering if there was a valid use case for being able to properly define the specific internal properties and functions of a class in a way similar to how an interface defines the public properties and functions of a class.

Imagine the task that you have to build a class that describes a human being.

Obviously, each human is a humanoid creature but not every humanoid creature is a human so you'd probably have an interface IHumanoid with functions like these (since it isn't useful to hardcode the body plan into the class):

```<code>public interface IHumanoid {
    function get head():IHead;
    function get torso():ITorso;
    function get leftArm():IArm;
    function get rightArm():IArm;
    function get leftLeg():ILeg;
    function get rightLeg():ILeg;
}
</code>```

Further and also obviously, each human is a mammal but not every mammal is a human, so there's probably another interface IMammal with two definitions for males and females floating around somewhere:

```<code>public interface IMammal {
    function procreate(partner:IMammal):void;
}

public interface IMaleMammal extends IMammal {
    function inseminate(female:IFemaleMammal):void;
}

public interface IFemaleMammal extends IMammal {
    function conceive(partner:IMaleMammal):Boolean;
    function giveBirth():IMammal;
    function nurse(offspring:IMammal):void;
}
</code>```

Thus our class probably looks something like this now:

```<code>public class Human implements IHumanoid, IMammal {
    private var _head:IHead;
    private var _torso:ITorso;
    private var _leftArm:IArm;
    private var _rightArm:IArm;
    private var _leftLeg:ILeg;
    private var _rightLeg:ILeg;

    public function Human() {
        // ctor...
    }

    public function get head():IHead {
        return _head;
    }

    public function get torso():ITorso {
        return _torso;
    }

    public function get leftArm():IArm {
        return _leftArm;
    }

    public function get rightArm():IArm {
        return _rightArm;
    }

    public function get leftLeg():ILeg {
        return _leftLeg;
    }

    public function get rightLeg():ILeg {
        return _rightLeg;
    }

    public function procreate(partner:IMammal):void {
        // "abstract" function
    }
}

public class MaleHuman extends Human implements IMaleMammal {
    override public function procreate(partner:IMammal):void {
        if (partner is IFemaleMammal) {
            inseminate(partner);
        }
    }

    public function inseminate(female:IFemaleMammal):void {
        female.conceive(this);
    }
}

public class FemaleHuman extends Human implements IFemaleMammal {
    override public function procreate(partner:IMammal):void {
        if (partner is IMaleMammal) {
            conceive(partner);
        }
    }

    public function conceive(partner:IMaleMammal):Boolean {
        // ...
    }

    public function giveBirth():IMammal {
        // ...
    }

    public function nurse(offspring:IMammal):void {
        // ...
    }
}
</code>```

From this we can implement our classes further and everything's working nice and fine until we get the task to use the existing interfaces to implement some other classes. Perhaps a gorilla, an orca and a platypus.

Ignoring the massive issue the platypus will pose to our current interface structure (*cough* egg  laying mammal *cough*), we have the "problem" that nothing prevents us from giving the gorilla 2 brains, the orca 8 lungs and the platypus half a dozen livers. And while we might be disciplined enough to follow the structure mammals typically have we cannot guarantee the same if we open the API for other developers who might code some seriously screwed up things which still look okay to the outside world.

Therefore I was wondering if there was a valid use case to create something like a "private interface" which defines non-public functions and properties. Perhaps something along these lines:

```<code>public structure SMammal {
    function get brain():IBrain;
    function get liver():ILiver;
    function get leftLung():ILung;
    function get rightLung():ILung;
    function get leftKidney():IKidney;
    function get rightKidney():IKidney;
}

public class Human implements IHumanoid, IMammal follows SMammal {
    private function get brain():IBrain {
        // ...
    }

    private function get liver():ILiver {
        // ...
    }

    // etc. etc.
}
</code>```

Does such a feature exist in any programming language? Can abstract classes be used to solve this? Or shouldn't we care about this at all as long as the public interface somehow works as expected?

答:
And while we might be disciplined enough to follow the structure
  mammals typically have we cannot guarantee the same if we open the API
  for other developers who might code some seriously screwed up things
  which still look okay to the outside world.

What exactly do you gain by forcing them to follow your structure? You possibly break some advanced usages, maybe there is a case for an animal with multiple brains. And the client programmer can mess up the implementation of a class in so many crazy ways that trying to prevent this feels like trying to a close window in an attempt to keep a horse in a barn.

Don't treat your client programmers like prisoners. If they follow the public interface, let the code run.

Title: Use cases for "private" interfaces?


答:
2072-rated chess player here.  I made this website in pure JavaScript over a weekend.  It's not a chess engine (I designed it to create entertaining opening positions as sort of a perverse Chess960 engine), but it's a starting point.  The source code is here.

There are a lot of complications involved in making a functional board.  These include:

First, figuring out how to represent the basic legal moves.  You have to kind of do math with the beginning and ending coordinates.  For instance, with rook moves, one of the coordinates has to be the same before and after.  With knight moves, the sum of the absolute value of the coordinate changes has to be 3, and both coordinates must change.  With bishop moves, either the sum of the coordinates remains the same, or they both increase by the same amount.  Pawns are trickiest because you not only have to figure out if they can move two squares or one (check the row and the color instead of storing how many moves they've made) but also have to deal with the whole capture-diagonally, move-forward thing.

Capturing is a challenge because of pawns and check.  You can't just say that if a piece moves to another piece's square, then it's a capture.  After all, pawns can't move to another piece's square to capture - they have their own special way of capturing.

You have to figure out an efficient way to see if enemy pieces are in the way of a piece's move in order to decide if it's legal or not.

Check is challenging to deal with.  After every move, you have to check all the squares that the enemy pieces can go to and see if one of them involves your king and, if so, it's an illegal move.

Castling, en passant, promotion, stalemate, forced draws, repetition - none of these are trivial to handle given the scale of the problem.

All chess engines work by looking at all (possibly a heuristically determined subset) of the legal moves in a position and evaluating numbers to represent their relative values by making those moves and recursively doing the same thing for the resulting positions.  Your twin problems here are

How to store this data efficiently

How to proceed with this recursive search - after all, you can't let it go on forever, so you have to put a limit and then figure out how to design your algorithm to do the most optimal and thorough search within that limit.  For instance, you want to make sure that it at least comes up with some evaluation for each possible starting move, but you might also want it to spend more time evaluating more promising moves instead of giving an equal amount of time to every move.

This all on top of designing the algorithm in the first place, which there is plenty of information available on.

As for which language to go with (although I guess you already decided on JavaScript), I think it depends more on your goal than anything else.  I wanted to make mine online (and get better at JavaScript), so JavaScript was my choice.  Any object-oriented programming language will do though.

Once you get comfortable with what you're doing, the following resources will probably prove really helpful:

Chess Programming Wiki

Chess Programming Forum

StockFish on Github

Good luck!

Title: Best approach for writing a chess engine?

Body:
I'm a chess enthusiast and a programmer. I recently decided to start making a chess engine using my chess and programming knowledge. So here's my question:

What language (I'm familiar with Java, C++ and Python) and methodology should I adapt while writing a chess engine?

A little guidance would be much appreciated.

Edit:

So I decided to make it in JavaScript. I download this Chess UI from github and now I'm all set! My first step would be to write legal moves for it. So can anybody point me in the right direction? (I'm new to jQuery but have alot of programming experience).

P.S: I'm not trying to make a very efficient engine (I know its way too difficult), I just want to get familiar with the process and learn some new techniques along the way.


答:
It seems easier to be generic in the small, i.e. don't make a class to handle a lookup table that maps integers to strings when you can make a reasonable dictionary class that handles any pair of types (where the first type supports some type of comparison).

In a previous life I did a lot of industrial automation projects for machinery that handled a continuous web of material.  Steel, aluminum, paper, plastic, ... .  You unroll it at one end and roll it up again at the other after doing something useful in the middle.  In one industry you start at the "payoff reel", not the "unwinder".  If you use the wrong terminology then you're an idiot in the client's multi-million dollar eyes.  You would be amazed at how little could be abstracted for reuse from one project to the next.  OTOH, one could often create a framework or template as a starting point.  It would be customized for the job at hand, but at least it had the benefit of learning from prior projects.  And everyone on the team knew where we were starting from.

Title: When to prefer a generalized solution over solving specific cases

Body:
In programming we're often faced with a choice: cover each conceivable use case individually, or solve the general problem:

Its obvious that solving the immediate problem is faster, however creating a generalized solution will save time in the future.

How do I know when it's best to try and cover a finite list of cases, or make a generic system to cover all possibilities?


问:
Representing business rules with exceptions
I know it is expensive but (IMO) I believe it is a very good practice. I'm talking about rules like say, you can't save an Invoice if you are not a sales person... so in that case throwing an exception saying 'your are not authorized' or such...

Another approach it would be having objects with a status or something like that

Is there any other approach? how do you feel about it?

答:
expressing business rules is one thing, implementing them is another

think about the user experience; if the user is not a salesperson, why give them a button that says 'create invoice' at all?


问:
Why are errors named as "Exception" but not as "Error" in programming languages?
I've been thinking about that for quite a while actually. I am not a native English speaker myself but still, I have years of programming experience and I always asked myself this. Why is it named as Exception but not Error since they are errors?

It could be PageNotFoundError instead of PageNotFoundException!

答:
Exceptions and errors are different.

Exceptions are situations a program can overcome, like say you try to open a file and it doesn't exist, while errors are situations a program can't do nothing about, like a disk failure or a RAM failure.

ContentLicense: CC BY-SA 4.0


答:
First, you pass the salt. Then you pass the pepper. Then you pass the grated parmesan cheese. At this point, you have enough experience to start developing a general condiment-passing system.

It works in software projects in the same way: use special purpose systems that you develop as your learning steps to generalized ones, so when it is time to start your general-purpose system, you have a better confidence in what you are building, because you have several special-purpose systems under your belt.


答:
make a more extensive demo so differences become more clear pick one,
  but put everything behind an interface so the implementation can be
  swapped later (might be quite some work)

This will be necessary.

This "graphical" UI control will have the following requirements:

Fast image composition of text and labels

Double-buffering (to avoid flicker)

Ability to map mouse click coordinates to graphical objects.

Pay special attention to the situations where multiple graphical objects overlap. Unsatisfactory handling of this situation will make an application unusable to most people.

while I had the impression the lower level options were somewhat
  faster to display.

Contrary to your belief, some high-level frameworks delegate the heavy-lifting of pixel rendering and composition to lower-level frameworks, (which then delegate to the hardware) thus the performance difference may not be significant.

The main question is, what composition algorithm is used underneath the framework you will be choosing, and whether it will be sufficiently fast enough.

I give two examples of such composition strategies:

For each text and label to be drawn on top of the canvas, it is first rendered to an individual RGBA32 transparent layer. All these layers are then composited onto the final bitmap at a later time.

For each text and label to be drawn, the "destination" bitmap is locked, and their pixels are modified directly. Only the "inked pixels" need to be modified.

These strategies have different trade-offs. (The first one can be parallelized, but require more memory (RGBA32) and more computation (composition). The second one is serial but require less memory and computation.) Also, some strategy is more portable to GPU rendering than the other.

Since we aren't computer graphics experts, we do not know enough to predict which strategy will win, therefore we rely on experimentation (extensive demo) to find out.

Title: How to select drawing system when requirements not yet known?

Body:
We're developping an application for 2D data processing and display. At the moment data is displayed by converting each point to a color depending on intensity, so in rather low level code. This works well. A new feature is displaying a grid and a bunch of lines that can be moved with the mouse on that image.

As usual when new technologies are going to be picked, I made a little demo to test some things out: using the current data plot, a line is drawn on top that can be moved up/down with the mouse, and at the same time there is text displaying the cursor coordinates. I tried some different ways: using a Canvas, using a somehwat lower level DrawingContext and using the low level WriteableBitmapEx api.

To me, there was no real difference in ease of coding nor display speed. Yes the Canvas option had a couple of lines less code than the others, while I had the impression the lower level options were somewhat faster to display. But no huge differenes making me pick one immediately.

So the problem now is: I have no idea how to select the most suitable system for the job, but it is a very important decision to make since the graphical part of the app will likely continue to grow. Needless to say it would be a small disaster if we pick A now, and in one year we figure out B would have been way better. Normally I'd select the fastest or most convenient option, or look at future requirements and use the system that seems to fit best, but in this case there is simply not enough difference, and future requirements are not exactly known: for now we think it's sufficient if we can draw lines, circles and some text, and update speed is not that important. However the application is in it's early stage, so is the underlying hardware and there are less than 100 customers. That however, might change rapidly. And so can requirements.

Question is simple: what to do? Some options I've been thinkig about:

pick one that 'feels' best (WriteableBitmapEx but probably just because I have an affinity with lowlevel stuff)

pick the one with the least amount of code (Canvas, also seems very easy on the UI level with effects and mouse events and what not)

make a more extensive demo so differences become more clear
pick one, but put everything behind an interface so the implementation can be swapped later (might be quite some work)


问:
When do we need to apply a software development methodology?
There are many software development methodologies - SCRUM, agile, XP, etc. - and they all have there advantages and disadvantages I suppose.

But when do we really need to apply them? Surely they are not necessary for small 1-man projects, but for large 50+ teams you can most certainly not go about ad-hoc:ing the whole thing.

So what's the line for when to use and when to not use such a methodology, if there indeed is one?

答:
Software methodologies are purely a means to reduce project risk.

It's fairly well known that if you take a team of developers practising some methodology and tell them they don't have to follow it anymore and can work however they want, their productivity will increase, but the risk that they will build the wrong thing at the wrong price in the wrong amount of time will greatly increase.

Thus in order to choose an appropriate methodology you first need to determine what the risks are if the project fails.

If the only thing to lose is a couple of weeks of your evenings then a few sketches in a note book and no measurement of progress or deliverables is fine.

If the lives of seven astronauts and billions of dollars is the price of software failure then you better have world class planning, development process, project management and testing in place.


问:
Abstract DAL - Use Interface with Internal Class?
We have a business logic layer (BLL) that is tightly coupled to our data access layer (DAL). We make calls like this:

```<code>using (FooData data = new FooData())
{
  data.DoSomething();
}
</code>```

It's important to note that all of our data classes are internal, and they're in the same assembly as the logic classes, so that only the BLL can access the DAL.

In order to decouple these (to help facilitate unit testing), one idea is to create IDataClass interfaces, like IFooData. At first I thought it may be a problem because we'd have to make our data classes public to implement the interfaces. But we should be able to keep the data classes internal, even though we still need the methods to be public:

```<code>public interface IFooData
{
  void DoSomething();
}

internal class FooData : IFooData  // Notice the class is internal
{
  public void DoSomething();  // Method is public, but that's ok because class is internal
}
</code>```

So even though the method is public, since the class itself is internal, we should still allow only our BLL access.

Is there anything inherently wrong with this approach? Is there a better way to abstract the DAL, for unit testing, without opening the DAL to the world by making it public?

答:
Extracting an interface and ensuring the BLL is using only interface types is a good way forward to make the BLL testable without the database.

What you are doing is absolutely fine.


问:
What kinds of visual content, tables or diagrams might I want to include in my Project Architecture Document?
Besides logical and physical architecture diagrams, comps / mockups and tables for expected network load between components and various data schemas, what kinds of visual content, tables or diagrams might I want to include in my Project Architecture Document?

The specific project is an integration of 3rd party social networking features into a fashion site.

Please post example graphics. Thanks.

答:
When it comes to architecture it always depends. When building a simple throw away application you document way less than when building a large service oriented architecture. When building an application in an agile organisation you document less then when building an application in a highly governed waterfall organisation.

When it comes to determining what to use I like the IEEE 1471 way of thinking

(image from http://iea.wikidot.com/ieee1471 )

Look at your stakeholders, determine their concerns, identify the viewpoints which best describe how your architecture addresses the concerns, describe these viewpoints.

As an alternative and a more common way the "4+1 Architectural View Model" addresses the need for a lot of projects.

What you probably did not mean, but which could give you also some new ways of thinking about it is the PSA (Project start architecture). Which is more of an enterprise architecture document. A great presentation on the PSA and how it fits into TOGAF can be found here (pdf)

A great book that also give a lot of insights on how to describe software architectures is "Software Architecture in practice" ( third edition coming out soon)

Hope this helps and good luck.


答:
An error is always an error. An exception is an error in the current context. That is, an exception is context sensitive. An example of an exception would be adding an ascii "a" to an integer "1". An error might be something like using an undefined operator like "+!" in most languages.

Some languges will allow you to Define your way out of the situation if that is really what you want to do.

Title: Why are errors named as "Exception" but not as "Error" in programming languages?

Body:
I've been thinking about that for quite a while actually. I am not a native English speaker myself but still, I have years of programming experience and I always asked myself this. Why is it named as Exception but not Error since they are errors?

It could be PageNotFoundError instead of PageNotFoundException!


答:
Either way, you are going to need higher-level code.  The question is who is better qualified to write it?  Someone with almost no experience in the area or someone who makes a living writing libraries used by thousands of people?  I'm  not trying to be mean here, but they've already solved dozens of problems you aren't even aware exist yet.  Use the higher level APIs until you're qualified and have good reason to replace them.

Also, in my experience the worst bottlenecks tend to be in my own code rather than in what third party library I happened to choose.  Focus on things like keeping the data cached instead of constantly recalculating it.  Avoid disk accesses.  Keep your GUI code as decoupled as possible from the rest of the system.  Think about the bare minimum your drawing code needs to know to do its job, and use well-defined interfaces to provide it.


问:
Why can't there be an "universal" programming language that serves all purposes?
why not combine the best features of the all existent programming languages and fit it in a universal programming language?</p>

答: We must look to economics to answer this question. If it saved business money to have just one language, we would have it. They would standardize on it and require everyone to use it.  The other languages would languish in dusty academic buildings and the basements of wild-eyed enthusiasts. This has not happened, so their must be no profit incentive in a universal programming language or one would have naturally evolved by now.</p>


答:
The interface approach is a good / mainstream one for mocking out your DAL during testing of consumers like the BLL.

One thing to note however is that by making your DAL concrete classes internal, is that you may be making your concrete DAL harder to test directly, as this now implies that your DAL unit tests must also be in this assembly without needing to use back doors like reflection.

Also, at some point in future you may consider using an IoC container to build up the implementation behind an interface, which also might trip up on the internal.

You could mimic the encapsulation you are trying to achieve with 'internal only' by adding a convention / LINT rule that your BLL / other layers must couple to the DAL via the interface, not on the concrete implementation.

Title: Abstract DAL - Use Interface with Internal Class?

Body:
We have a business logic layer (BLL) that is tightly coupled to our data access layer (DAL). We make calls like this:

```<code>using (FooData data = new FooData())
{
  data.DoSomething();
}
</code>```

It's important to note that all of our data classes are internal, and they're in the same assembly as the logic classes, so that only the BLL can access the DAL.

In order to decouple these (to help facilitate unit testing), one idea is to create IDataClass interfaces, like IFooData. At first I thought it may be a problem because we'd have to make our data classes public to implement the interfaces. But we should be able to keep the data classes internal, even though we still need the methods to be public:

```<code>public interface IFooData
{
  void DoSomething();
}

internal class FooData : IFooData  // Notice the class is internal
{
  public void DoSomething();  // Method is public, but that's ok because class is internal
}
</code>```

So even though the method is public, since the class itself is internal, we should still allow only our BLL access.

Is there anything inherently wrong with this approach? Is there a better way to abstract the DAL, for unit testing, without opening the DAL to the world by making it public?


答:
I think all the "because you don't carve statues with a pencil" answers are missing the point.

Who here, TRULY selects a language before every new project?

The truth is, we only need a few programming languages, and the programming world would be better off that way: people would focus on making the scripting language better instead of being scattered across python/ruby/perl/younameit for example.

C# is programmed on/for windows (alright, there's Mono, anybody here runs a C# under Mono app every day?) and that makes users buy Windows7/8, and that makes money for Microsoft.

Other companies do the same, then open source knows better, then mister genius too... and we got lots of look-alike languages, it's just humanity's self-centered nature.

Title: Why can't there be an "universal" programming language that serves all purposes?

Body: why not combine the best features of the all existent programming languages and fit it in a universal programming language?</p>


问:
What's the best way to inject science into everyday programming?
I work better when I have some firm foundations. This helps me to solve everyday problems better, because I can generalize them. The thing I find in programming is so many things are black boxes. Logic is scientific, but commands are not. A command in a language is just "something that does something". It is very hard to work out what its logic is, without understanding the underlying hardware. I learned brainfuck for a little bit, and enjoyed it very much, but it still has commands. These commands are packages of functionality that cannot really be understood without understanding all the lower levels of logic, unfortunately. What I would like to know is if there are any mathematical or logic principles that help with being able to generalise programming problems? </p>

答:
There is a mathematical foundation to programming. It is called Lambda Calculus and is very interesting. Unfortunatley, except if you are doing some research in CS or designing a new funky language, it won't help you in your every day life.

It will help to learn and really understand languages though. It will also help you to have fun with the haskell people who like to work with things like homeomasofemtomophisms. So I would still recommend some culture in lambda calculus to anyone interested in programming.

If you haven't met them, I would recommend learning about design patterns. I wouldn't call them "science" but it provides a good basis to speak with some precision about some code without redefining everything all the time.


答:
The thing I find in programming is so many things are black boxes.

Here are some resources that will open those black boxes:

Code: The Hidden Language of Computer Hardware and Software by
Charles
Petzold.

According to an Amazon review:

...The real value of Code is in its explanation of technologies that
  have been obscured for years behind fancy user interfaces and
  programming environments, which, in the name of rapid application
  development, insulate the programmer from the machine...

The Hardware/Software
Interface

This Coursera course examines key computational abstraction levels below modern high-level languages. According to the course's description:

...We will develop students’ sense of “what really happens” when
  software runs — and that this question can be answered at several
  levels of abstraction, including the hardware architecture level, the
  assembly level, the C programming level and the Java programming
  level...

And finally my favorite:

How do computers
work?

@LieRyan provided an excellent explanation from the atom all the way up to assembly language.

EDIT 1:

What's the best way to inject science into everyday programming?

There are so many arguments as to whether a Computer Scientist is really a scientist and whether a Software Engineer is really an engineer.

Anyway, the following resources will help you inject science into everyday programming:

The Art of Computer Programming by Donald
Knuth

Knuth's books are considered to be the bible for algorithms. The study of data structures and algorithms are the closest to the scientific method in the Computer Science field I could think of.

Algorithms, Part 1 and Part 2

This course covers the essential information that every serious
  programmer needs to know about algorithms and data structures, with
  emphasis on applications and scientific performance analysis of Java
  implementations.

Is Computer Science
Science?
(PDF)

Body: I work better when I have some firm foundations. This helps me to solve everyday problems better, because I can generalize them. The thing I find in programming is so many things are black boxes. Logic is scientific, but commands are not. A command in a language is just "something that does something". It is very hard to work out what its logic is, without understanding the underlying hardware. I learned brainfuck for a little bit, and enjoyed it very much, but it still has commands. These commands are packages of functionality that cannot really be understood without understanding all the lower levels of logic, unfortunately. What I would like to know is if there are any mathematical or logic principles that help with being able to generalise programming problems? </p>


答:
It is a mistake to think that "combining all features" will make a better language.

You are more likely to end up with a bloated, complex, unreadable mess.

Good language design requires choice and trade-offs to be made. Arguably the best / most revolutionary / most successful languages are the ones that take something out and provide a better alternative rather than add new things in. e.g.

Structured programming languages (C, Pascal) - takes out "goto", replaces with procedures and structured loops etc.

Java - takes out "manual memory management", replaces with GC/managed memory

Haskell/Clojure - takes out "uncontrolled mutable state"

Lisp - takes out most "language syntax", replaces with a flexible homoiconic tree of s-expressions

There's a great talk on this top by Uncle Bob Martin - The Last Programming Language


答:
Technically, there is nothing wrong with your design.

However, I would consider an alternative approach: instead of decoupling your BLL from your DAL, better decouple your DAL from your database. Allow creation of DAL objects in-memory, and if your BLL needs to load DAL objects from somewhere, use the repository pattern (see here) to avoid direct contact of the BLL to the database. That way, you can

create unit tests for you DAL objects easily without the need of a database

create unit tests for your BLL by providing in-memory created DAL objects through a mock repository as test data (ok, you can argue now if those tests should be really called unit-tests)

In fact, what you loose is the capability of testing the BLL with DAL mocks. But in reality, those DAL mock objects will typically look a lot like your real DAL objects to provide a base for useful tests of the BLL. IMHO it avoids a lot of code duplication and unnecessary effort when re-using your real DAL objects for automated tests of the BLL.


答:
I also would check so called Turing machines, see http://en.wikipedia.org/wiki/Turing_machines

They are completely formal and stand on their own (meaning no lower level understanding is needed). It is quite complex theory but serves as the most low level base of programming languages and has a mathematical/formal background.

Title: What's the best way to inject science into everyday programming?


问:
What do you consider to be the essential design patterns? And do you use them?
It seems to me that programmers have an increasingly uphill task of staying up-to-date.

In my efforts to improve my programming ability, I am in search of the essential design patterns that are commonly used in computing (more specifically around .net).

For example, should I bother to memorise:

Search algorithms?

MVC?  (is it bad to use this just for the smart url's? lol)

MVVM? (seems no point, but haven't researched it)

etc...

What are your top 5 design patterns that you commonly use day to day (not just the ones you like)?

答:
Actually I don't use design patterns, unless it is 100% clear I need one that fits.
This means I don't check for every problem: is there a design pattern? But I use it when I notice that the solution I created is (similar) to a design pattern or when I encounter a problem I don't have an answer for.

I tend to use the simpler design pattern, simply because how simpler, how more generic they can be used, these are:

singleton

facade (useful for interfacing to others)

abstract factory (useful in my work since we have a lot of more or less related devices)

observer (in C# kind of embedded)


问:
Efficient algorithm to sort html list of players
We have list of players, which is represented in form like this:

```<code><div class="players_list">
   <div class="player" data-points="500">
        <div class="name">Player1</div>
        <div class="position">1</div>
   </div>
   <div class="player" data-points="400">
        <div class="name">Player2</div>
        <div class="position">2</div>
   </div>
   <div class="player" data-points="300">
        <div class="name">Player3</div>
        <div class="position">3</div>
   </div>
   <div class="player" data-points="200">
        <div class="name">Player4</div>
        <div class="position">4</div>
   </div>
</div>
</code>```

Something happens, and Player 4 recieves 600 points. So it goes on 1st place.
With him - player3 recieves 300 points and goes on 2nd place.

It happens after same event - let's assume, that they get these points from server, but that's all load that is allowed on server and server does not calculate positions.

What is most efficent way to get view like this:

```<code><div class="players_list">
   <div class="player" data-points="800">
        <div class="name">Player4</div>
        <div class="position">1</div>
   </div>
   <div class="player" data-points="700">
        <div class="name">Player3</div>
        <div class="position">2</div>
   </div>

   <div class="player" data-points="500">
        <div class="name">Player1</div>
        <div class="position">3</div>
   </div>
   <div class="player" data-points="400">
        <div class="name">Player2</div>
        <div class="position">4</div>
   </div>
</div>
</code>```

It's not question about code, it's question about:

What kind of task it is? Just sort?

Is it ok to use JavaScript to solve this task if lists are less than 500 rows?

Is it ok to re-render whole players list, or there are some ways to just change div element position(index in DOM or something like this)?

Are there any tools and libraries around, that can help solve this task efficiently?

P.S.: If we want to animate all this story - we should create a queue of animation tasks each time scores for all players recalculates?

Update:

I have followed @Jalayn's answer, and stuck on following problem:

Let's assume that list [1,2,3,4] transforms to [2,3,4,1]. If we map it, we will get following position diffs [+1, +1, +1, -3].. Now, if we move one by one elements to it's position change, all will be ok, till we get to negotiate position diff - 1st position diff can't move down any more..

So, my update to question - how we can animate rows more than twice?

And final problem, on which I am stucked:

Not sure, if it most be solved in this question. BTW, if 2 players have same points - animation plan brakes and element_ids duplicates.

My question now is how to make following transformation of  structures list:
[(#id1, 1, 100),(#id2, 2, 50), (#id3, 2, 50), (#id4, 4, 25)] => [(#id3, 1, 150), (#id1, 2, 100), (#id4, 3, 75), (#id2, 4, 50)]

For now my solution is to refresh whole list, but not completly regenerate it - just move all elements to the first position in order they sorted in backed JSON. Animation is too complex to be done cause of final problem.

答:
Well I hope, I'll answer all your questions and be precise enough.

The answer to all your questions is yes, it is possible to do all of that in Javascript:

What kind of task it is? Just sort?

You have to sort data, but you also have to update some data (points, name?, position) and display it to the user.

Is it ok to use JavaScript to solve this task if lists are less than
  500 rows?

You can rearrange tables composed of 500 rows with JavaScript, no problem (using a bit of JQuery), and I don't think you would have any performance trouble with that. The only problem you could have is if you attempt to animate 500 moving rows (more on that later)

Is it ok to re-render whole players list, or there are some ways to
  just change div element position(index in DOM or something like this)?

Well, I think it is ok to re-render the whole players list, but if you do that, how will perform position-change animations ?

Are there any tools and libraries around, that can help solve this
  task efficiently?

Obvious answer: JQuery and JQuery UI (or your favorite JavaScript framework for performing animations)

If we want to animate all this story - we should create a queue of
  animation tasks each time scores for all players recalculates?

I think you should perform the animations one by one after you know the final position of each player. Otherwise, you could perform animations when nothing has changed (player3 may move from 3 to 1, then player2 moves from 2 to 1, then player1 moves from 1 to ... 1, nothing has changed!)

DOM only vs DOM backed by a JSON Data Model

Now, regardless of the tools, or algorithm you are going to use, if you work only with DOM elements, without having a "backend" JSON data model (please someone complete here if you see more problems):

Finding the new position of a given player will be a pain

Updating the positions of every player will be a pain

If you work with DOM elements for rendering, backed by a JSON data model, and provided you make the following changes to your individual player display, you will have a much easier time:

```<code>   <div class="player" id="player2">
        <div class="name">Player2</div>
        <div class="points" id="playerPoints2">400</div>
        <div class="position" id="playerPosition2">2</div>
   </div>
</code>```

Notice that I've added an id attribute to the player
 and to the elements displaying the points ("playerPoints2") and the position ("playerPosition2"). Doing that will allow you to quickly find the position of a player or its points, given its unique id. You could do without, but that would affect performance and you would have to use more complex queries (see JQuery's .find())

My attempt:

In short, what I try to do is moving as few DOM elements as possible, and decorrelating the data from the display.

Imagine having the following JSON data model in addition to your DOM model for displaying the players:

player (array of players)

id

position (you can write a custom function for sorting the array given the "position" attribute if each item of the array)

points

name

and the following JSON data model for performing animations later:

playerChanges (array of player changes)

id

deltaPosition (example: +3 = 3 ranks higher than before)
.   * isComputed (boolean)

After receiving data from the server, here's what I would do:

sort the list of backend players, given their respective position. The first element of the array should be the top ranked player.

loop over the data received from the server

if the points of a player change, then:

look up the player in the array

update its points

move the player to the position in the array where it should fit, but don't change the "position" attribute

create a new entry in the "playerChanges" array, storing only the id of the player (we will compute the delta only at the end)

loop on the array of backend players, and for each player in "playerChanges" (this is important) that is nit yet conputed, compute the position attribute regarding to the position of the player in the array. Since you have his "old" position, and the position in the array, you can compute the "deltaPosition". Edit: after you compute the delta, mark the "playerChange" as computed and restart looping on the array of backend players. Do that as long as there is an uncomputed ""playerChange"" in the array.

In the end you should have an array of "playerChanges". This is the list of rows that you should move, given the "deltaPosition" of each player. Notice that it could be 0, which means that the player received new points, but his position did not change. To perform the animation, I would suggest looking at this brilliant answer.

After you have done these animations, you can loop again on the list of backend players in order to update the displayed position ("playerPositionXXX" where XXX is the id of the player) of each player.

What I've attempted to do here is to decorrelate the "update and sort" from what happens on the screen, the animation that the user sees.

Edit: here is a working code sample (on Chrome at least) of an animation with JQuery and JQueryUI.

```<code><html>
    <head>
        <title>Temp test</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
        <style type="text/css">
            * { font-family: Calibri;}
            .player { border: 1px solid grey; background: #f0f0f0; width: 300px;
                        padding: 10px; margin-bottom: 5px; margin-top: 5px; }
                .name { margin-left: 30px; font-size: 20px; font-weight: bold; }
                .points { float: right; color: whitesmoke; font-size: 24px; font-weight: bold; margin-top: -30px;
                            background-color: #999; padding: 3px;}
                .position { clear: both; display: block; float: left;
                            font-size: 20px; font-weight: bold; margin-top: -29px; padding-right: 10px;
                            border-right: 1px solid black;}
        </style>
        <script type="text/javascript">

            function movePlayer(playerToMoveId, delta) {
                var $old = $(playerToMoveId);
                var $new = $old.clone();

                // TODO: here I don't take into account the delta
                //
                // you need to write a simple method for determining the player
                // that will be replaced (here I hardcoded "p4").
                $("#p4").before($new);

                var newOffset = $new.offset();
                //Get the old position relative to document
                var oldOffset = $old.offset();
                //we also clone old to the document for the animation
                var $temp = $old.clone().appendTo('body');
                //hide new and old and move $temp to position
                //also big z-index, make sure to edit this to something that works with the page
                $temp
                  .css('position', 'absolute')
                  .css('left', oldOffset.left)
                  .css('top', oldOffset.top)
                  .css('zIndex', 1000);
                $new.hide();
                $old.hide();
                //animate the $temp to the position of the new img
                $temp.animate( {'top': newOffset.top, 'left':newOffset.left}, 'slow', function(){
                   //callback function, we remove $old and $temp and show $new
                   $new.show();
                   $old.remove();
                   $temp.remove();
                });
            }
        </script>
    </head>
    <body>
        <div class="players_list" id="plist">
           <div class="player" id ="p4">
                <div class="name" id="pName4">Player4</div>
                <div class="points" id="pPts4">800</div>
                <div class="position" id="pPos4">1</div>
           </div>
           <div class="player" id="p3">
                <div class="name" id="pName3">Player3</div>
                <div class="points" id="pPts3">500</div>
                <div class="position" id="pPos3">2</div>
           </div>

           <div class="player" id="p1">
                <div class="name" id="pName1">Player1</div>
                <div class="points" id="pPts1">300</div>
                <div class="position" id="pPos1">3</div>
           </div>
           <div class="player" id="p2">
                <div class="name" id="pName2">Player2</div>
                <div class="points" id="pPts2">250</div>
                <div class="position" id="pPos2">4</div>
           </div>
        </div>

        <input type="button" onclick="movePlayer($('#p2'), 3)" value="Animate"/>
    </body>
</html>
</code>```

Body:
Well I hope, I'll answer all your questions and be precise enough.

The answer to all your questions is yes, it is possible to do all of that in Javascript:

What kind of task it is? Just sort?

You have to sort data, but you also have to update some data (points, name?, position) and display it to the user.

Is it ok to use JavaScript to solve this task if lists are less than
  500 rows?

You can rearrange tables composed of 500 rows with JavaScript, no problem (using a bit of JQuery), and I don't think you would have any performance trouble with that. The only problem you could have is if you attempt to animate 500 moving rows (more on that later)

Is it ok to re-render whole players list, or there are some ways to
  just change div element position(index in DOM or something like this)?

Well, I think it is ok to re-render the whole players list, but if you do that, how will perform position-change animations ?

Are there any tools and libraries around, that can help solve this
  task efficiently?

Obvious answer: JQuery and JQuery UI (or your favorite JavaScript framework for performing animations)

If we want to animate all this story - we should create a queue of
  animation tasks each time scores for all players recalculates?

I think you should perform the animations one by one after you know the final position of each player. Otherwise, you could perform animations when nothing has changed (player3 may move from 3 to 1, then player2 moves from 2 to 1, then player1 moves from 1 to ... 1, nothing has changed!)

DOM only vs DOM backed by a JSON Data Model

Now, regardless of the tools, or algorithm you are going to use, if you work only with DOM elements, without having a "backend" JSON data model (please someone complete here if you see more problems):

Finding the new position of a given player will be a pain

Updating the positions of every player will be a pain

If you work with DOM elements for rendering, backed by a JSON data model, and provided you make the following changes to your individual player display, you will have a much easier time:

   <div class="player" id="player2">
        <div class="name">Player2</div>
        <div class="points" id="playerPoints2">400</div>
        <div class="position" id="playerPosition2">2</div>
   </div>

Notice that I've added an id attribute to the player <div> and to the elements displaying the points ("playerPoints2") and the position ("playerPosition2"). Doing that will allow you to quickly find the position of a player or its points, given its unique id. You could do without, but that would affect performance and you would have to use more complex queries (see JQuery's .find())

My attempt:

In short, what I try to do is moving as few DOM elements as possible, and decorrelating the data from the display.

Imagine having the following JSON data model in addition to your DOM model for displaying the players:

player (array of players)

id

position (you can write a custom function for sorting the array given the "position" attribute if each item of the array)

points

name

and the following JSON data model for performing animations later:

playerChanges (array of player changes)

id

deltaPosition (example: +3 = 3 ranks higher than before)
.   * isComputed (boolean)

After receiving data from the server, here's what I would do:

sort the list of backend players, given their respective position. The first element of the array should be the top ranked player.

loop over the data received from the server

if the points of a player change, then:

look up the player in the array

update its points

move the player to the position in the array where it should fit, but don't change the "position" attribute

create a new entry in the "playerChanges" array, storing only the id of the player (we will compute the delta only at the end)

loop on the array of backend players, and for each player in "playerChanges" (this is important) that is nit yet conputed, compute the position attribute regarding to the position of the player in the array. Since you have his "old" position, and the position in the array, you can compute the "deltaPosition". Edit: after you compute the delta, mark the "playerChange" as computed and restart looping on the array of backend players. Do that as long as there is an uncomputed ""playerChange"" in the array.

In the end you should have an array of "playerChanges". This is the list of rows that you should move, given the "deltaPosition" of each player. Notice that it could be 0, which means that the player received new points, but his position did not change. To perform the animation, I would suggest looking at this brilliant answer.

After you have done these animations, you can loop again on the list of backend players in order to update the displayed position ("playerPositionXXX" where XXX is the id of the player) of each player.

What I've attempted to do here is to decorrelate the "update and sort" from what happens on the screen, the animation that the user sees.

Edit: here is a working code sample (on Chrome at least) of an animation with JQuery and JQueryUI.

<html>
    <head>
        <title>Temp test</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
        <style type="text/css">
            * { font-family: Calibri;}
            .player { border: 1px solid grey; background: #f0f0f0; width: 300px;
                        padding: 10px; margin-bottom: 5px; margin-top: 5px; }
                .name { margin-left: 30px; font-size: 20px; font-weight: bold; }
                .points { float: right; color: whitesmoke; font-size: 24px; font-weight: bold; margin-top: -30px;
                            background-color: #999; padding: 3px;}
                .position { clear: both; display: block; float: left;
                            font-size: 20px; font-weight: bold; margin-top: -29px; padding-right: 10px;
                            border-right: 1px solid black;}
        </style>
        <script type="text/javascript">

            function movePlayer(playerToMoveId, delta) {
                var $old = $(playerToMoveId);
                var $new = $old.clone();

                // TODO: here I don't take into account the delta
                //
                // you need to write a simple method for determining the player
                // that will be replaced (here I hardcoded "p4").
                $("#p4").before($new);

                var newOffset = $new.offset();
                //Get the old position relative to document
                var oldOffset = $old.offset();
                //we also clone old to the document for the animation
                var $temp = $old.clone().appendTo('body');
                //hide new and old and move $temp to position
                //also big z-index, make sure to edit this to something that works with the page
                $temp
                  .css('position', 'absolute')
                  .css('left', oldOffset.left)
                  .css('top', oldOffset.top)
                  .css('zIndex', 1000);
                $new.hide();
                $old.hide();
                //animate the $temp to the position of the new img
                $temp.animate( {'top': newOffset.top, 'left':newOffset.left}, 'slow', function(){
                   //callback function, we remove $old and $temp and show $new
                   $new.show();
                   $old.remove();
                   $temp.remove();
                });
            }
        </script>
    </head>
    <body>
        <div class="players_list" id="plist">
           <div class="player" id ="p4">
                <div class="name" id="pName4">Player4</div>
                <div class="points" id="pPts4">800</div>
                <div class="position" id="pPos4">1</div>
           </div>
           <div class="player" id="p3">
                <div class="name" id="pName3">Player3</div>
                <div class="points" id="pPts3">500</div>
                <div class="position" id="pPos3">2</div>
           </div>

           <div class="player" id="p1">
                <div class="name" id="pName1">Player1</div>
                <div class="points" id="pPts1">300</div>
                <div class="position" id="pPos1">3</div>
           </div>
           <div class="player" id="p2">
                <div class="name" id="pName2">Player2</div>
                <div class="points" id="pPts2">250</div>
                <div class="position" id="pPos2">4</div>
           </div>
        </div>

        <input type="button" onclick="movePlayer($('#p2'), 3)" value="Animate"/>
    </body>
</html>


问:
Is there any advantage to learning C first?
I've got a little bit of history with programming, having gotten my start with Visual Basic. I let it slide as a hobby from a little after VB6 up until just a year or so ago when I got on the iPhone bandwagon, when I decided to take up Objective-C programming.

I now have what I feel to be an intermediate level of knowledge on the language, but I can't help but feel that there's a substantial gap in where my knowledge is, given that there seems to be a substantial bit of the language I don't feel I understand.

Would I benefit from reviewing the underlying C structure, or would I be better served from continuing to practice solely in Objective-C whilst reviewing the documentation for various features?

Edit: Though I've accepted the first answer given, more insight is always appreciated from those with supplementary or opposing views.

答:
The features of Objective-C are more or less a Superset of the features of C.

So, for me, the answer is yes.

You'll be learning the most critical concepts of Objective-C and most will find procedural programming a lot simpler and less surprising than similar solutions solved with object oriented programming.

You have a much better chance of understanding all of the concepts in C than you do in Objective-C.  Assembly language  is another good language with few surprises and few features.

You might have trouble solving a complex problem when you use lower level languages, but you'll actually be able to learn and understand them much easier.


问:
Are there deprecated practices for multithread and multiprocessor programming that I should no longer use?
In the early days of FORTRAN and BASIC, essentially all programs were written with GOTO statements.  The result was spaghetti code and the solution was structured programming.

Similarly, pointers can have difficult to control characteristics in our programs.  C++ started with plenty of pointers, but use of references are recommended.  Libraries like STL can reduce some of our dependency.  There are also idioms to create smart pointers that have better characteristics, and some version of C++ permit references and managed code.

Programming practices like inheritance and polymorphism use a lot of pointers behind the scenes (just as for, while, do structured programming generates code filled with branch instructions).  Languages like Java eliminate pointers and use garbage collection to manage dynamically allocated data instead of depending on programmers to match all their new and delete statements.

In my reading, I have seen examples of multi-process and multi-thread programming that don't seem to use semaphores.  Do they use the same thing with different names or do they have new ways of structuring protection of resources from concurrent use?

For example, a specific example of a system for multithread programming with multicore processors is OpenMP.  It represents a critical region as follows, without the use of semaphores, which seem not to be included in the environment.

```<code>th_id = omp_get_thread_num();
#pragma omp critical
{
  cout << "Hello World from thread " << th_id << '\n';
}
</code>```

This example is an excerpt from: http://en.wikipedia.org/wiki/OpenMP

Alternatively, similar protection of threads from each other using semaphores with functions wait() and signal() might look like this:

```<code>wait(sem);
th_id = get_thread_num();
cout << "Hello World from thread " << th_id << '\n';
signal(sem);
</code>```

In this example, things are pretty simple, and just a simple review is enough to show the wait() and signal() calls are matched and even with a lot of concurrency, thread safety is provided.  But other algorithms are more complicated and use multiple semaphores (both binary and counting) spread across multiple functions with complex conditions that can be called by many threads.  The consequences of creating deadlock or failing to make things thread safe can be hard to manage.

Do these systems like OpenMP eliminate the problems with semaphores?

Do they move the problem somewhere else?

How do I transform my favorite semaphore using algorithm to not use semaphores anymore?

答:
One of the major changes to parallel programming is that CPUs are tremendously faster than before, but to achieve that performance, require a nicely filled cache. If you try to run several threads at the same time swapping between them continually, you're nearly always going to be invalidating cache for each thread (ie each thread requires different data to operate on) and you end up killing performance much more than you used to with slower CPUs.

This is one reason why async or task-based (eg Grand Central Dispatch, or Intel's TBB) frameworks are more popular, they run code 1 task at a time, getting it finished before moving to the next one - however, you must code each each task to take little time unless you want to screw the design (ie your parallel tasks are really queued). CPU-intensive tasks are passed to an alternative CPU core rather than processed on the single thread processing all the tasks. Its also easier to manage if there are no truly multi-threaded processing going on too.


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

Any language that has whitespace as tokens needs to die.

posted later on the same answer:

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

I can see some clear arguments for each side:

using whitespace:

helps reduce inconsistent indentation in code

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

using tokens:

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

more consistent. Some text editors display whitespace differently.

more popular currently.

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

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

答:
Personally I find I need the blank line introduced by having a token on it's own line to make my mind realise that the code is in another scope.

I hate it when in python people go:

```<code>if something
    do something
    do somethingelse

    cleanup
else
    do the other thing
</code>```

while in token land I hate when people copy and paste and don't clean up the indentation,

```<code>if something
{
I have been too lazy
      {
            to clean up
            }
what I pasted
}
</code>```

or don't use a separate line for the token.

```<code>if something {
    I find this confusing
}
else {
especially when combined with the previous
do something
}
</code>```

I can read all three, but they aren't as I expect and I have to expend effort to parse them and as Joel says when things don't work like you expect it makes you frustrated.

Body:
Personally I find I need the blank line introduced by having a token on it's own line to make my mind realise that the code is in another scope.

I hate it when in python people go:

if something
    do something
    do somethingelse

    cleanup
else
    do the other thing

while in token land I hate when people copy and paste and don't clean up the indentation,

if something
{
I have been too lazy
      {
            to clean up
            }
what I pasted
}

or don't use a separate line for the token.

if something {
    I find this confusing
}
else {
especially when combined with the previous
do something
}

I can read all three, but they aren't as I expect and I have to expend effort to parse them and as Joel says when things don't work like you expect it makes you frustrated.


答:
You can use the InternalsVisibleToAttribute in order to break your DAL out from your Business Layer, but still keep the DAL methods internal.  You'll end up creating your DAL as a friend assembly.

This may not be a great approach as you would have to specify in your DAL's Assembly.cs file which assemblies can access the DAL.  So there's still some coupling involved (DAL knowing about BLL).

So, to answer your question, there isn't anything wrong with your approach.  But taking advantage of friend assemblies can provide you a bit more abstraction and probably help you out with making your code more testable.

I hope this helps.

OwnerDisplayName: David Hoerster


答:
You seem immoveable on your ideas that you expounded in your question, but I'll tender an answer anyway - someone may find it useful sometime in the future.

If you insist on keeping your DAL internal but still want to hit it with some unit tests and don't mind using the Microsoft Unit Testing tools, then try the PrivateObject approach. This is a wrapper for reflection that you could always code yourself, but it saves you a few lines of typing.

Note that using InternalsVisibleTo is a viable approach, but it's clumsy - if you are using it then you may already be on a fast slide downhill. internal means something is public only within the bounds of it's assembly, that modifier is normally used because you don't want stuff useable from outside that assembly, then you promptly turn around and violate that concept by declaring a InternalsVisibleTo... that is a big dirty red flag that is screaming out for some refactoring. Decoupling is a waste of time when only one assembly is calling the other, you may as well glue them together. Decoupling infers that multiple assemblies are calling the target (introducing unit testing doesn't count towards the 'multiple' because there are ways to get to the target assembly like I've already mentioned).

OwnerDisplayName: slugster


问:
Can unit testing software be used to unit test itself?
QUnit advertises itself on its web page like this:

...capable of testing any generic JavaScript code, including itself!

Can you really use unit testing software to test itself? Wouldn't defects in the software mean that the results are unreliable?

答:
Yes, it can. JUnit has an extensive test suite to test its own features, and ask any of the authors you like - they will tell you that this is essential to their productivity in extending the project. Probably most testing tools do the same.

The trick is that there is no particular need for a test of a new feature to be actually using the new feature itself - it merely has to exercise it and test the result. In this way, confidence in part of the functionality of a system can be used to establish confidence in a much larger part. This is similar to the way self-hosting compilers are bootstrapped, and it is a fundamental technique in computing theory.


答:
I don't know about qunit, but I have worked several projects where previous versions of a solution were used to validate later versions so I don't view it as an invalid approach.

Any unit test package in a vacuum with not integration or UAT testing is going to be susceptible to a flaw in the test package itself as well as all the usual integration issues a unit test suite cannot cover so I am not certain I would even go as far as saying self testing on the same version is any more flawed than trusting new unit tests in any other project.

From briefly reading the project's linked site it more sounds like they are pointing out that there is nothing special case about the test scenario or the targets you can test than they are advertising that a self testing library is a perfect solution.

Title: Can unit testing software be used to unit test itself?

Body:
QUnit advertises itself on its web page like this:

...capable of testing any generic JavaScript code, including itself!

Can you really use unit testing software to test itself? Wouldn't defects in the software mean that the results are unreliable?


问:
Dealing with units in arithmetic operations (multiplication and division)
I need to design a function to perform the basic arithmetic operations that are addition (+), subtraction (-), multiplication (x), and division (/) between 2 numbers.

That function takes 3 arguments:

-number1: composed of a value and a unit.

-number2: compoased of a value and a unit.

-operation_type: one of the 4 aforementioned operations.

and should return:

-number3: composed of a value and a unit.

Returning number3's value is easy as all I need to do is use conditional statements to perform the corresponding operation (e.g. if (operation_type == 'addition') { number3.value = number1.value + number2.value; } ).

However I'm having difficulties figuring out how I should represent and deal with the unit (for multiplication and subtraction operations, as for addition and subtraction it remains the same) in a way that I can chain up multiple operations and properly update the resulting unit every time. Here is an example:

```<code>operations type: multiplications
number1.unit: Kw
number2.unit: h / user / year
number3.unit: Kwh / user / year  _
                                  |
number1.unit: Kwh / user / year  <-
number2.unit: user
number3.unit: Kwh / year  _
                           |
number1.unit: Kwh / year  <-
number2.unit: year
number3.unit: Kwh
...
</code>```

My only constraint is that the unit must initially be represented as a string because it is stored in the database, then we can parse parse it into an object/array as needed.

Some of the problems I'm facing:

Q1: how to ensure consistent order in the resulting unit (e.g. h x Kw and Kw x h should both give Kwh)?

Q2: how to deal with complex units (e.g. foo / Kw x h / bar)?

And because hope dies last:

Q3: Are there any known algorithms / design patterns for dealing with this?

答:
I would just create a lookup table.

It's the fastest way to guarantee that when you get kW and h, regardless of order, that you'll come back with kW*h.

The only downside is if you have a very large number of combinations then it can be a pain to put the table together.


答:
If you just need to deal with physical quantities, then you can choose an n-dimensional system of physical units (length, mass, time, charge, etc.) that fits your domain.  Any physical unit is a product of powers of the fundamental units (positive and negative): e.g. force = mass * length * time^-2.  When you multiply physical quantities, you can just add the powers of the fundamental units.  If you need to handle fractional powers, I would represent them as ratios (1/3), not floating point (0.33333333)

Ordering for human display is largely a matter of custom.  Typically the order is positive powers of mass, length, time in the numerator and denominator, e.g. km-m^2/sec^2.  But there are many exceptions.  For example, Hubble's constant has dimension time^-1, but it is typically expressed as velocity / distance, e.g. km/sec / megaparsec.

As far as I know, C++ is the only popular language with a type system powerful enough to conveniently verify physical unit balance at compile time.  There are several C++ libraries available, including one in Boost.  If you are not using C++, you may want to look at one of them for inspiration.

Title: Dealing with units in arithmetic operations (multiplication and division)

Body:
I need to design a function to perform the basic arithmetic operations that are addition (+), subtraction (-), multiplication (x), and division (/) between 2 numbers.

That function takes 3 arguments:

-number1: composed of a value and a unit.

-number2: compoased of a value and a unit.

-operation_type: one of the 4 aforementioned operations.

and should return:

-number3: composed of a value and a unit.

Returning number3's value is easy as all I need to do is use conditional statements to perform the corresponding operation (e.g. if (operation_type == 'addition') { number3.value = number1.value + number2.value; } ).

However I'm having difficulties figuring out how I should represent and deal with the unit (for multiplication and subtraction operations, as for addition and subtraction it remains the same) in a way that I can chain up multiple operations and properly update the resulting unit every time. Here is an example:

```<code>operations type: multiplications
number1.unit: Kw
number2.unit: h / user / year
number3.unit: Kwh / user / year  _
                                  |
number1.unit: Kwh / user / year  <-
number2.unit: user
number3.unit: Kwh / year  _
                           |
number1.unit: Kwh / year  <-
number2.unit: year
number3.unit: Kwh
...
</code>```

My only constraint is that the unit must initially be represented as a string because it is stored in the database, then we can parse parse it into an object/array as needed.

Some of the problems I'm facing:

Q1: how to ensure consistent order in the resulting unit (e.g. h x Kw and Kw x h should both give Kwh)?

Q2: how to deal with complex units (e.g. foo / Kw x h / bar)?

And because hope dies last:

Q3: Are there any known algorithms / design patterns for dealing with this?


问:
Getting non-programmers to understand the development process
When starting a project for a company that's not primarily a programming company, one of the expectations is that there's a finished product at the end free of all bugs and does everything needed right away. However, that's rarely the case.

What are some ways to manage expectations and explain to non-programmers how software development differs from other types of product development?

答: If you have any familiarity with hi-rel software development, such as for nuclear reactor control, deep space communications, or medical implant devices (etc.), you might explain how the cost and delivery time structure for that level of priject management and QA might be magnitudes greater than what typical businesses can afford for their software projects.</p>


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

答:
I would argue that an abstraction is something that hides unnecessary details.  One of the most basic units of abstraction is the procedure.  For instance, I don't want to worry about how I'm saving data to the database when I'm reading that data in from a file.  So I create a save_to_database function.

Abstractions can also be joined together to form bigger abstractions.  For instance, functions may be put together in a class, classes can be put together to form a program, programs can be put together to form a distributed system, etc.

Title: What is abstraction?