答:
Throw-away prototyping

Throw-away prototyping is about creating, as fast as possible, a part of the future application to either ensure a feature is technically feasible or to show the feature to stakeholders or potential users in order to gather feedback from them.

Since the source code of this prototype is not reused later when developing the application itself, it makes it a throw-away prototype. Knowing that it's a throw-away code helps focusing on the actual feature, while leaving aside aspects such as maintainability of the code, style, design patterns or testing. This makes it possible to finish the prototype very fast, without affecting negatively the technical debt of the final product.

Throw-away prototyping is different from sketching. Sketching is more graphical and oriented towards user interfaces and user experience, and doesn't consist of writing programming code. Throw-away prototyping is usually used when sketching is not enough (for example when you need to show how a feature will perform on different smartphones or when you need to show the actual performance and responsiveness).

Throw-away prototyping can present a risk when dealing with stakeholders without technical background and in a context of tight deadlines and very limited resources: stakeholders may try to convince you to reuse in the final product the source code from the prototype. It is natural to believe that it will shorten the time required to release the product, but actually, it will only delay the shipment date. One way to prevent this is to use for the prototype a language which can't be used in production (for example use C# when you know that the final product will be hosted on Linux servers with only Python installed).

Fig. 1: Throw-away prototyping and sketching : prototypes help gathering early feedback before starting developing the actual feature.

Evolutionary prototyping

Evolutionary prototyping consists of building a prototype which is then refined based on the regular feedback from the stakeholders or potential users.

Here, maintainability of the code, style, design patterns or testing count from the beginning, which makes it possible to evolve the prototype into a fully featured, enterprise-grade product. The earlier steps of the prototype contain only the core part of the future product, and then, features are added progressively.

Fig. 2: Evolutionary prototyping : features are aggregated to the prototype to build the final product.

Evolutionary prototyping is different from incremental prototyping. Incremental prototyping consists of building several prototypes, each one representing a part of the future system, and then combine them. Evolutionary prototyping is closer to Agile: often, you will be able to obtain early a working product with limited features and extend it until stakeholder have money. Incremental prototyping, on the other hand, is better suited for large projects with many contributing teams, each team working on a separate prototype.

Fig. 3: Incremental prototyping : several prototypes are combined to form the final product.

Evolutionary prototyping is different from Agile methodologies too. Agile is about iterations and frequent milestones where a fully functional product can be released to manufacturing. If you have a working product every Thursday, you're doing Agile. In evolutionary prototyping, you expand the prototype, but nothing forces you to have a fully-functional product regularly. You can spend two months creating the first prototype, than expand it with a few features in respectively two and three days, and then spend three months on another feature. You can't have this sort of irregular patterns in Agile.

Specific Agile methodologies enforce additional rules. For example, if you don't do pair programming, you can't assert that you're doing Extreme Programming. If your team don't have daily meetings, you're not doing Scrum.

Title: Why we need Throw-away Prototyping?

Body: What is throw-away prototyping model in software engineering and why do we need it? How does it differentiate from Evolutionary Prototyping?</p>


问:
Asymptotic running time of for-loops
I have this question which I need answered:

What is the asymptotic running time for the following piece of code?

```<code>if (N < 1000)
  for (int i = 0; i < N; i++)
    for (int j = 0; j < N; j++)
      A[i] = j;
else
  for (int i = 0; i < N; i++)
    A[i] = i;
</code>```

logarithmic in N

linear in N ()

linearithmic in N

quadratic in N

And the correct result is “2. linear in N” which I can't figure out why, since that as far as I've understood, we want to accept the worst case>best case.

The worst case here is that the if statement is run and the time would then be quadratic in N. I am aware that we're trying to find some kind of average of more attempts, but how can I know what the value of N is? If N is really high (10000), it's obviously the else statement that is run most of the times. But can we assume this or have I misunderstood something?

答:
The definition of asymptotic running times is... well asymptotic. That is, it is the behavior of the function as N is very very large. The behavior of the function at smaller N is irrelevant. In this case, as N is very very large, it is larger than 1000. That means that the code inside the if clause is actually completely irrelevant as far as asymptotic running time goes (Note: I'm not sure why you said the else statement is run "most" of the times if N is really high, it's clearly run "all" the times when N is really high). All that matters is the code in the else.

Note, the "worst case" you're thinking of is legitimate in the cases of sequential operations. That is, if there was no if-else block, but both branches of the code were simply executed all the time, then what you said would be exactly correct: If you run code that is quadratic in N followed by code that is linear in N, the overall code is quadratic, as you said.

ContentLicense: CC BY-SA 3.0

Title: Asymptotic running time of for-loops


问:
How meaningful is the Big-O time complexity of an algorithm?
Programmers often talk about the time complexity of an algorithm, e.g. O(log n) or O(n^2).

Time complexity classifications are made as the input size goes to infinity, but ironically infinite input size in computation is not used.

Put another way, the classification of an algorithm is based on a situation that algorithm will never be in: where n = infinity.

Also, consider that a polynomial time algorithm where the exponent is huge is just as useless as an exponential time algorithm with tiny base (e.g., 1.00000001^n) is useful.

Given this, how much can I rely on the Big-O time complexity to advise choice of an algorithm?

答: A specific thought on big-O from my practical experience: generally the linear factors dominate over constants for any decent size N. That is, an O(n^2) algorithm is generally awful compared to O(n), for data of any reasonable size. However, the logarithmic factors can be comparable to constants in many cases. In other words, even for N quite large, O(nlogn) may be comparable or even faster than O(n), depending on the constants. For instance, sometimes you can do the same problem where one of the steps is either by putting all the data in a hash table, which is O(n) time, or by sorting in O(nlogn). Sorting is usually very efficiently implemented in most languages, and hashing doesn't have the best constants necessarily, so I've seen sorting beat out hashing.</p>


问:
Are first-class functions a substitute for the Strategy pattern?
The Strategy design pattern is often regarded as a substitute for first-class functions in languages that lack them.

So for example say you wanted to pass functionality into an object. In Java you'd have to pass in the object another object which encapsulates the desired behavior. In a language such as Ruby, you'd just pass the functionality itself in the form of an anonymous function.

However I was thinking about it and decided that maybe Strategy offers more than a plain anonymous function does.

This is because an object can hold state that exists independently of the period when it's method runs. However an anonymous function by itself can only hold state that ceases to exist the moment the function finishes execution.

In an object-oriented language that supports first-class functions, does the strategy pattern have any advantage over using functions?

答:
Just because two designs can solve the same problem doesn't mean they are direct substitutions for each other.

If you need to track state in a functional program, you don't mutate a closed over variable, even if the language allows it. You arrange to call a function that takes in one state as an argument and returns the new state as its return value.

Your architecture will look very different, but you'll accomplish the same goal. Don't try to force one paradigm's patterns directly onto the other one.


问:
Is it an anti-pattern to use void* and enums to enable type-checking?
Say in a game engine, you have Objects that composited of different components. One of these is a RenderComponent which can be either a Mesh, a Sprite or a Light.

Now, all these are vastly different classes with non-complatible interfaces, so deriving them all from RenderComponent makes little sense. Also, an Object can only have one RenderComponent at a time, so you saving three pointers in Object, two of which must always be nullptr, seems wasteful. So what I came up with is using RenderComponent to store a void* pointer and the type.

```<code>class RenderComponent{
public:
    enum class RenderType{
        Mesh, Sprite, Light
    };

    RenderType getType(){ return type_; }

    Mesh* asMesh(){
        if(type_ == RenderType::Mesh)
            return static_cast<Mesh*>(pointer_.get())
        else
            return nullptr;
    } /* the same stuff for Sprite and Light */

    RenderComponent(unique_ptr<Mesh>&& pointer) :
        pointer_(std::move(pointer)),
        type_(RenderType::Mesh)
    {} /* the same stuff for Sprite and Light */

private:
    unique_ptr<void> pointer_;
    RenderType type_;
}
</code>```

It should work as intended, but I feel like this is an anti-pattern. I'm basically discarding all typesafe aspects of C++ and then reimplement them myself. This can't be right.

So, is this an anti-pattern? What are common workarounds for this problem? Am I missing something obvious? Or is this a known, but (for good reason) only rarely used pattern?

答: This is anti-OO, but entity-component-system design is expressly not object oriented. I do not think that this is a bad practice in general for software that is based on CES, but in your example it is bad practice. In my opinion, the rendering function should probably try and get a sort of MeshComponent from the Entity and render that. If the component is not there, then return nullptr. For different rendering types you can have derived rendercomponents, too. Or different render systems, which might be an even clearer approach.


答:
The correct way to approach this is to use RTTI and dynamic_cast.  This does nearly the same thing as what you are doing, but in a type-safe, language approved manner.  (dynamic_cast throws if you try to case objects into things they are not related to.)

One reason people write code like this is that dynamic_cast came into the language after people had been using it a while.  Too often, developers don't keep up with language improvements and continue doing things they way they are used to.  So in 1994, this might have been perfectly good code.

The other reason people write code like this is because of the widespread belief that RTTI hurts performance.  The thought is that because RTTI has to store type information for every single class, it "wastes memory".  You often see this attitude with people who do embedded development, or in game development.  Also, dynamic_cast requires exception handling, and the same groups often turn this off exception handling.

There is something behind this in that RTTI can increase your memory footprint.  This particularly happens when you make heavy use of templated classes like the STL as these can cause the compiler to create large numbers of classes under the covers, all of which get type information.  On one project I worked on like this, we saw nearly half a megabyte lost to type information.  My feeling, though, is that if you have a tight memory budget, you might be better off refactoring the templated classes into something that don't use templates.

Because of the general dislike of RTTI in the game industry, third party engines will almost never use it.  This is more about supplying what the customer is asking for than good engineering.

This all requires an inheritance tree, of course.  You say:

Now, all these are vastly different classes with non-complatible interfaces, so deriving them all from RenderComponent makes little sense.

But I find this questionable, because your first line is:

One of these is a RenderComponent which can be either a Mesh, a Sprite or a Light.

Emphasis mine.  "be" seems to denote an "is-a" relationship, which is a classic sign of a class hierarchy.

I don't think this is necessarily an "anti-pattern", though, as this is a way that many successful projects have approached the problem, and it's something that ended up being codified into the language.

Title: Is it an anti-pattern to use void* and enums to enable type-checking?

Body:
Say in a game engine, you have Objects that composited of different components. One of these is a RenderComponent which can be either a Mesh, a Sprite or a Light.

Now, all these are vastly different classes with non-complatible interfaces, so deriving them all from RenderComponent makes little sense. Also, an Object can only have one RenderComponent at a time, so you saving three pointers in Object, two of which must always be nullptr, seems wasteful. So what I came up with is using RenderComponent to store a void* pointer and the type.

```<code>class RenderComponent{
public:
    enum class RenderType{
        Mesh, Sprite, Light
    };

    RenderType getType(){ return type_; }

    Mesh* asMesh(){
        if(type_ == RenderType::Mesh)
            return static_cast<Mesh*>(pointer_.get())
        else
            return nullptr;
    } /* the same stuff for Sprite and Light */

    RenderComponent(unique_ptr<Mesh>&& pointer) :
        pointer_(std::move(pointer)),
        type_(RenderType::Mesh)
    {} /* the same stuff for Sprite and Light */

private:
    unique_ptr<void> pointer_;
    RenderType type_;
}
</code>```

It should work as intended, but I feel like this is an anti-pattern. I'm basically discarding all typesafe aspects of C++ and then reimplement them myself. This can't be right.

So, is this an anti-pattern? What are common workarounds for this problem? Am I missing something obvious? Or is this a known, but (for good reason) only rarely used pattern?


问:
What is the current status of software support for JPEG-2000?
The general recommendation to record original scanned images used to be "use TIFF". But programmers need evolution of format for "evolution of software", and I need to evolve my system to change from TIFF to JP2.

I have a big image storage (terabytes) for legal and scientific scanned materials, they need original recording. I use some caching rules, but the system need to show (via web download) or to manipulate (ImageMagick and others) original data.

I've read an article about migrating image storages from TIFF-lossless to JPEG-2000-lossless and the conclusion is to stay with TIFF. However the article is from 2009 and at the time they found support for the JPEG-2000 format by available software was very poor. The conversions to JPEG-2000 were lossy in the software they tested, and the available software for consuming images did not support the format well.

Is now the time to change from TIFF to JP2, or not? Is the software support still as flawed as it was in 2009?

答:
I think the answer depends on if you are questioning real life usage or library support coverage. Since you ask on programmers.stackexchange, maybe you mean library, but everyone seems to be assuming you asks about applications. I'll follow the crowd.

Speaking of applications, based on Wikipedia's list of applications, support these days looks pretty bad. The user software compatible with it are numbered, and usually are professional tools, and it is only gaining traction in some worldwide archive-oriented organizations that you can finish listing within one page. In short, jp2 is out of reach of the people. At this rate, it will never reach the break-even point for public acceptance, despite technical superiority.

Speaking of browsers, Wikipedia listed that only Safari has native support. All others, Firefox, Chrome, IE... don't, except some do with QuickTime, which can't be guaranteed on Android/Windows and is not there on Linux.

On my OpenSUSE 13.1, here are some browser results with samples (note that open the sample page does not count towards OK, you have to open the .jp2 images inside it):

Chromium 33: Can't do it, offer users to download.

Firefox 27: Can't do it, offer users to download.

(Since Linux itself support jp2, users can open the images after download)

**Edit after reading Peter Krauss' comment ** In the preservation context perhaps you can choose the format, because usually you supply users with tools; the users' desktop and browser environment are of secondary importance.

Evolving your software doesn't mean accepting latest technology standard. Latest technology standard is the hope of future technology of the standard committee, and people vote by feet after their decision. Examples: A lot migrated to XHTML then HTML5 while most from HTML4 directly to HTML5, and a lot migrated to FireWire (1394) then eSATA and USB3 while most from USB2 directly to USB3.


问:
Should I use nested matrices or dictionaries?
As per Should I ask my question about which data structure to use here? I'm asking this here.  Hopefully this isn't too implementation specific.

I'm currently developing a program that will represent chemical structures (and eventually allow manipulations/reactions of them).  I've hashed out two different systems of storing this data but I'm not sure how to pick which one.

Option 1: Nested matrices

Chemicals have (more or less) definite structures and relative positions of items, and it seems as though it would be easier to represent something like that with a matrix - then I can assign definite 'coordinates' to each atom or bond.  Unfortunately, you end up with some overlap if you have a structure that branches out a fair bit.  To solve this I ended up working out a solution that used nested, 5x5 matrices.

```<code>[[None,  None, [CH3], None, None ],
 [None,  None, Bond,  None, None ],
 [[CH3], Bond, C,     Bond, [CH3]],
 [None,  None, Bond,  None, None ],
 [None,  None, [CH3], None, None ]]
</code>```

Here C represents the element carbon (this could be represented a couple different ways, and isn't particularly relevant here).  Bond represents a bond, and [CH3] represents another 5x5 matrix.  This is the uppermost ([0][2]) CH3

```<code>[[None, None, H,    None, None],
 [None, None, Bond, None, None],
 [H,    Bond, C,    Bond, H   ],
 [None, None, Bond, None, None],
 [None, None, Root, None, None]]
</code>```

Here the lowermost Bond is a reference to the same object as the uppermost Bond in the first structure, while Root is (some undetermined) way of relating that this is where the matrix connects to the next level up.  If this were a more complex structure, one of the Hs would be replaced by another matrix, such as an additional [CH3].

Advantages of this method:

Everything is explicitly laid out, including structure, which is good
according to The Zen of Python.

When these chemicals are (eventually) represented graphically it will (theoretically) be     much easier to make sure everything is in its place

Disadvantages:

This isn't readable at all if you have a more complex structure

This is nested, not flat

This is going to require a lot of recursion to walk through

Option 2: Dictionaries

Another way I could represent these with significantly less nesting and better readability would be using dictionaries. Each molecule would be a key in a dictionary {Molecule1 : Data, Molecule2 : Data} and the data would be dictionaries as well Atoms: Data, Bonds: Data.  This requires quite a bit less nesting, but would require a little more work when I eventually want to display them.

Closing thoughts

Before asking this question, and indeed while writing it, I've been pretty set on dictionaries.  It seems like a cleaner and easier method of storing this data, and won't require figuring out a really nasty recursive technique to walk through a molecule.  However I wouldn't be surprised if I missed something which is why I'm asking here.

If this seems too implementation specific please let me know what you think I should change and I'll do my best to make it more general

答:
Dictionaries are what Python's primary graph library NetworkX uses. Each graph structure is a dictionary of dictionaries. So it's nested in a sense but not by much. Molecules are very much representable by graphs, being connected groups of nodes.

If you want to skip all that and go straight to the modelling work, there's a full toolkit for that. The Molecular Modelling toolkit is a set of libraries for dealing with molecular modelling in Python. It is mostly aimed at Bioscience but I'm sure you could use it for other kinds of chemical work say Geochemistry or Materials research. It can even output to various visualizers.


问:
comparison of an unsigned variable to 0
When I execute the following loop :

```<code> unsigned m;
 for( m = 10; m >= 0; --m ){
        printf("%d\n",m);
    }
</code>```

the loop doesn't stop at m==0, it keeps executing interminably, so I thought that reason was that an unsigned cannot be compared to 0. But when I did the following test

```<code>unsigned m=9;
if(m >= 0)
    printf("m is positive\n");
else
    printf("m is negative\n");
</code>```

I got this result:

```<code>m is positive
</code>```

which means that the unsigned variable m was successfully compared to 0.

Why doesn't the comparison of m to 0 work in the for loop and works fine elsewhere?

答:
You should compile with all warnings enabled.

A test like m >= 0 is always true if m is unsigned; so

```<code>if(m >= 0)
  printf("m is positive\n");
else
  printf("m is negative\n");
</code>```

can be optimized as

```<code>printf("m is positive\n");
</code>```

A recent version of GCC, invoked as gcc -Wall  (or gcc -Wall -O1) would have warned you.

And a test like m >0  is the same as m != 0  (or just m)

And your for ( m = 10; m >= 0; --m ) loop is understood as for(m=10; TRUE; --m) so loops indefinitely. Mabye you wanted for (m=10; (int)m>=0; m--) , then the test would fail when m becomes large enough to not fit in an int (without overflow to negative int). But such a (int)m>=0 is ugly and unreadable, so avoid it.

Title: comparison of an unsigned variable to 0

Body:
You should compile with all warnings enabled.

A test like m >= 0 is always true if m is unsigned; so

if(m >= 0)
  printf("m is positive\n");
else
  printf("m is negative\n");

can be optimized as

printf("m is positive\n");

A recent version of GCC, invoked as gcc -Wall  (or gcc -Wall -O1) would have warned you.

And a test like m >0  is the same as m != 0  (or just m)

And your for ( m = 10; m >= 0; --m ) loop is understood as for(m=10; TRUE; --m) so loops indefinitely. Mabye you wanted for (m=10; (int)m>=0; m--) , then the test would fail when m becomes large enough to not fit in an int (without overflow to negative int). But such a (int)m>=0 is ugly and unreadable, so avoid it.


问:
Commenting regular expressions
Are there any common practises for commenting the regular expressions: inline comments referring different part of RegEx or general comment for all expression?</p>

答:
Extract the RegEx into a separate class into a with a meaningful name. Then I'd document the code with automated tests.

This will ensure

That the code actually works - also for corner cases

Ensures that a quick "bugfix" doesn't screw up a lot of corner cases

May document optimizations where backtracking is disabled

Naturally, your class may host several regex's.

Title: Commenting regular expressions


问:
Why is cleverness considered harmful in programming by some people?
I've noticed a lot of questions lately relating to different abstraction techniques, and answers saying basically that the techniques in question are "too clever." I would think that part of our jobs as programmers is to determine the best solutions to the problems we are given to solve, and cleverness is helpful in doing that.

So my question is: are the people who think certain abstraction techniques are too clever opposed to cleverness per se, or is there some other reason for the objection?

EDIT: This parser combinator is an example of what I would consider to be clever code. I downloaded this and looked it over for about half an hour. Then I stepped through the macro expansion on paper and saw the light. Now that I understand it, it seems much more elegant than the Haskell parser combinator.

答:
If clever code + the amount of comments required to make it understandable code <= simple code, then I say go for the clever code.  Every time.

I think the problem arises when people who write "clever code" deliberately fail to comment it properly, because only by it being initially incomprehensible will future generations who come across it have to spend time "appreciating" how clever it is.

ContentLicense: CC BY-SA 2.5


答:
Strategy is a concept, a useful recipe for solving a particular, recurring problem. It's not a language construct, nor is it about any one form of implementation. A closure can be used to implement Strategy one day and Observer the next day.

The term Strategy is mostly useful in conversations with other programmers to concisely express your intent. There's nothing magical about it.

Title: Are first-class functions a substitute for the Strategy pattern?

Body:
The Strategy design pattern is often regarded as a substitute for first-class functions in languages that lack them.

So for example say you wanted to pass functionality into an object. In Java you'd have to pass in the object another object which encapsulates the desired behavior. In a language such as Ruby, you'd just pass the functionality itself in the form of an anonymous function.

However I was thinking about it and decided that maybe Strategy offers more than a plain anonymous function does.

This is because an object can hold state that exists independently of the period when it's method runs. However an anonymous function by itself can only hold state that ceases to exist the moment the function finishes execution.

In an object-oriented language that supports first-class functions, does the strategy pattern have any advantage over using functions?


问:
Is goto to improve DRY-ness OK?
My code has many checks to detect errors in various cases (many conditions would result in the same error), inside a function returning an error struct. Instead of looking like this:

```<code>err_struct myfunc(...) {
    err_struct error = { .error = false };

    ...

    if(something) {
        error.error = true;
        error.description = "invalid input";
        return error;
    }

    ...

        case 1024:
            error.error = true;
            error.description = "invalid input";  // same error, but different detection scenario
            return error;
            break;  // don't comment on this break please (EDIT: pun unintended)
            ...
</code>```

Is use of goto in the following context considered better than the previous example?

```<code>err_struct myfunc(...) {
    err_struct error = { .error = false };

    ...

    if(something) goto invalid_input;

    ...

        case 1024:
            goto invalid_input;
            break;

    return error;

    invalid_input:
        error.error = true;
        error.description = "invalid input";
        return error;
</code>```

答:
if using goto your code reads better, use it. It is a language feature like every other. We are anymore at the age of Dijkstra.

http://david.tribble.com/text/goto.html

```<code>int parse()
{
    Token   tok;

reading:
    tok = gettoken();
    if (tok == END)
        return ACCEPT;
shifting:
    if (shift(tok))
        goto reading;
reducing:
    if (reduce(tok))
        goto shifting;
    return ERROR;
}
</code>```

This is a case where goto-s are even more elegant than whatever other structure.

Title: Is goto to improve DRY-ness OK?

Body:
if using goto your code reads better, use it. It is a language feature like every other. We are anymore at the age of Dijkstra.

http://david.tribble.com/text/goto.html

int parse()
{
    Token   tok;

reading:
    tok = gettoken();
    if (tok == END)
        return ACCEPT;
shifting:
    if (shift(tok))
        goto reading;
reducing:
    if (reduce(tok))
        goto shifting;
    return ERROR;
}

This is a case where goto-s are even more elegant than whatever other structure.


问:
Would you still use Java in your next project, despite the whole mess in JCP
It seems that there is a whole mess around current JCP.

Quite of number of highly respected guys like Doug Lea, Tim Peierls had quit JCP.

Reference :

Is JCP dead? and Final results of the JSR Review Ballot for JSR #336

This put Java in an unfavorable future. As a Java developer, will you still consider using Java in your next project?

答: I won't use it. I don't like monsters like Oracle.</p>


问:
Organizing solution / project structure and classes for Line of Business Application (LOB)
The question how-do-you-organize-your-projects already has a few good answers. I would like to get a better understanding about this suggested structure:

```<code>MyApp.Core
MyApp.Model
MyApp.Presenter
MyApp.Persistence
MyApp.UI
MyApp.Validation
MyApp.Report
MyApp.Web
</code>```

Assuming MyApp is a winforms rich client to administer students, courses, rooms and teachers

Lets say i have a winforms user control to edit course information (name of the course, who teaches it, in  which room and which students did register for the course). The class below reflects all the information i need for the user control

```<code>public class CourseDetails{
    public int Id{ get; set;}
    public Course Course{ get; set;}
    public Teacher Teacher{get; set;}
    public Room Room{get; set;}
    public List<Student> StudentList{get; set;}
}
</code>```

Where would you put this class?

Methods of MyApp.Model

I would like to know how complex or simple the classes inside the namespace MyApp.Model shoud be.

Should the project MyApp.Model only contain very simple classes like

```<code>public class Course{
    public int CourseId{ get; set;}
    public string CourseName{ get; set;}
    public int CategoryId {get; private set;}

}
public class Teacher{
    public int TeacherId{ get; set;}
    public string TeacherName{ get; set;}
}
</code>```

or should MyApp.Model contain also

complex classes like CourseDetails

additional methods for each class like Save() or GetById() ?

Additional topics

Where (in which project) should interfaces be implemented and where should base classe be used.

When should this additional methods (Save(), GetById()) be inherited from a base class or be contained in the class which implents an interface that has all the methods for saving and selecting.

```<code>public class CourseDetails: ModelBase{
    ...
}

public class ModelBase{
    public bool Save() {
        Console.WriteLine("do something clever to save each entity");
        return true;
    }
}
</code>```

Sorry for not beeing more clear; I would like to understand what kind of things (classes, interfaces, ressources, etc) should be put in which project and why. I hope you get the idea.

答:
The structure you are outlining here is called an onion architecture, also known as ports and adapters or hexagon architecture.

The principle is that you have the application core, and then you can put on layers outside this core, such as a UI layer, a persistence layer, a service layer and so on.

You define the interfaces for your application in your core and then you let the outer layers implement them. In this way your core stays "pure" and if you for instance want to change out your persistence mechanism from MySQL to MongoDB, it's a matter of reimplementing your persistence interface defined in core, in another module that is specific to MongoDB.

See: http://alistair.cockburn.us/Hexagonal+architecture and
http://jeffreypalermo.com/blog/the-onion-architecture-part-1/

for a more in depth explanation.


问:
Implementing a modern web application with Web API on top of old services
My company has many WCF services which may or may not be replaced in the near future. The old web application is written in WebForms and communicates straight with these services via SOAP and returns DataTables.

Now I am designing a new modern web application in a modern style, an AngularJS client which communicates with an ASP.NET Web API via JSON. The Web API then communicates with the WCF services via SOAP.

In the future I want to let the Web API handle all requests and go straight to the database, but because the business logic implemented in the WCF services is complicated it's going to take some time to rewrite and replace it.

Now to the problem: I'm trying to make it easy in the near future to replace the WCF services with some other data storage, e.g. another endpoint, database or whatever. I also want to make it easy to unit test the business logic.

That's why I have structured the Web API with a repository layer and a service layer. The repository layer has a straight communication with the data storage (WCF service, database, or whatever) and the service layer then uses the repository (Dependency Injection) to get the data. It doesn't care where it gets the data from. Later on I can be in control and structure the data returned from the data storage (DataTable to POCO) and be able to test the logic in the service layer with some mock repository (using Dependency Injection).

Below is some code to explain where I'm going with this. But my question is, does this all make sense? Am I making this overly complicated and could this be simplified in any way possible? Does this simplicity make this too complicated to maintain? My main goal is to make it as easy as possible to switch to another data storage later on, e.g. an ORM and be able to test the logic in the service layer. And because the majority of the business logic is implemented in these WCF services (and they return DataTables), I want to be in control of the data and the structure returned to the client.

Any advice is greatly appreciated.

Update 20/08/14

I created a repository factory, so services would all share repositories. Now it's easy to mock a repository, add it to the factory and create a provider using that factory.

Any advice is much appreciated. I want to know if I'm making things more complicated than they should be.

So it looks like this:

1. Repository Factory

```<code>public class RepositoryFactory
{
    private Dictionary<Type, IServiceRepository> repositories;

    public RepositoryFactory()
    {
        this.repositories = new Dictionary<Type, IServiceRepository>();
    }

    public void AddRepository<T>(IServiceRepository repo) where T : class
    {
        if (this.repositories.ContainsKey(typeof(T)))
        {
            this.repositories.Remove(typeof(T));
        }

        this.repositories.Add(typeof(T), repo);
    }

    public dynamic GetRepository<T>()
    {
        if (this.repositories.ContainsKey(typeof(T)))
        {
            return this.repositories[typeof(T)];
        }

        throw new RepositoryNotFoundException("No repository found for " + typeof(T).Name);
    }
}
</code>```

I'm not very fond of dynamic but I don't know how to retrieve that repository otherwise.

2. Repository and service

```<code>// Service repository interface
// All repository interfaces extend this
public interface IServiceRepository
{
}

// Invoice repository interface
// Makes it easy to mock the repository later on
public interface IInvoiceServiceRepository : IServiceRepository
{
    List<Invoice> GetInvoices();
}

// Invoice repository
// Connects to some data storage to retrieve invoices
public class InvoiceServiceRepository : IInvoiceServiceRepository
{
    public List<Invoice> GetInvoices()
    {
        // Get the invoices from somewhere
        // This could be a WCF, a database, or whatever
        using(InvoiceServiceClient proxy = new InvoiceServiceClient())
        {
            return proxy.GetInvoices();
        }
    }
}

// Invoice service
// Service that handles talking to a real or a mock repository
public class InvoiceService
{
    // Repository factory
    RepositoryFactory repoFactory;

    // Default constructor
    // Default connects to the real repository
    public InvoiceService(RepositoryFactory repo)
    {
        repoFactory = repo;
    }

    // Service function that gets all invoices from some repository (mock or real)
    public List<Invoice> GetInvoices()
    {
        // Query the repository
        return repoFactory.GetRepository<IInvoiceServiceRepository>().GetInvoices();
    }
}
</code>```

答:
Since your goal actually IS to make it easy to change out the storage mechanism at a later point I think you are on the right track.

You might also consider actually making a separate model specific to your database and then map the object model back and forth between your domain object and your database objects.

This way you can use annotations and other technology specific attributes on your database objects without polluting the domain object with e.g SQL specific attributes if you are going for a NoSQL solution further down the line.


问:
One boilerplate class or many similar classes?
Lets say I'm trying to model a variety of objects that are virtually identical, the only difference being their class variables.  Am I better off creating one boilerplate class and just calling the constructor with the specific variables, or creating a lot (in this case 100+) of essentially identical classes and hard coding their class variables (which will never change)?

To be clear:

Identical methods

Identical class variable names but different values

Identical intended functionality

To be clear, my language (Python) doesn't support interfaces that I'm aware of - some of the other similar questions seemed to get answers recommending that.  The other option that seems to make sense to me would be to create a base class with each field and method and then create a bunch of unique child classes that contain their unique values.

The amount of work to create all the child classes isn't significant to me - I've written a program that quickly parses a text file (that has all the unique values) and can write all the classes to a .py file quickly and easily.  Making changes down the road is rather easy for the same reason.

(somewhat) Related questions

Create many similar classes, or just one

Good Programming Practice for similar child classes

答:
If the behaviour is the same to all classes and they all have the same reason to change, then I'd probably not subclass at all.

It is a matter of instantiation and configuration - it only affects the usage of the class but not the structure. So basically we are talking about trade offs in the usage of the class and its maintenance.

If you have an easy time instanatiating your objects from a datasource like you use for generating the classes, then why not do so? If the constructor only takes three easy to remember or easy to look up arguments, why subclass? There's no reason to create so many classes.

Generating the classes on the other hand can turn out to be harder maintenance, as you need to maintain the base class and also the generators if for some reason - and contrary to your expectations - things change.

I can only think of one reason to opt for the subclasses: When it makes your API significantly simpler and your code easier to understand. For example when your class is instantiated very often by the programmer and it's easier for her/him to remember the classname instead of a hard to remember qualifier for the data that is to be fetched from the datasource. Or if you absolutely can not fetch the data with a qualifier and the programmer has to lookup or calculate a lot of values to instantiate the class. IMHO that's some sort of convention over configuration then and can really turn out to be an API enhancement - especially if the subclass is the natural place to search for the values if a programmer needs to look them up. But in many cases you should also be able to adjust your data source format in a way that humans can easily interact with it.

Another reason to generate sublasses is when - also contrary to your expectations - you realize that you will need enhanced behaviour on at least some of them.

To be clear, my language (Python) doesn't support interfaces that I'm aware of - some of the other similar questions seemed to get answers recommending that.

That is because dynamically typed language don't need interfaces. Mose use duck typing.


问:
How is the correct way of writing TDD for a void API?
Ok so my scenario is this:
I have a third party component that offers an API for communicating with an external system. The method calls for commanding the external system to do stuff, all return void.

So what I have done is I have created a wrapper interface and have mocked out the external system. But since I have no real logic or checks in my code that calls stuff on the external API, the code is just procedural. I can't really test anything else than that the methods are being called.

```<code>_systemWrapper.DoStuff(a, b ,c , d);
_systemWrapper.DoStuff2(e, f);
_systemWrapper.DoStuff3(g);
</code>```

I can't configure the external system from my tests, so integration tests are out of the question.

So what I have done to test this, is that I have mocked out my "_systemWrapper" and am just verifying that the parameters I call on the mock contain the correct parameters. Is this a common way to solve this particular problem? To me it seems to be a bit exhaustive to have a test to make sure you have this and this line of code present.

The problem is that this system is getting BIG and writing tests that assert that this and this line is present is getting out of hand, and refactoring is becoming real hard with all the tests failing if we change a call to the third party.

答:
There are a number of techniques for dealing with the problem of external apis. I'm going to try to describe several possible approaches that may be helpful.

Mocking

This is where your tests assert that a particular sequence of calls was executed. This is the technique that you've tried, and you discovered where it falls down. It works really well when the external api is very simple. However, for complex apis it typically becomes problematic. The tests are brittle and don't even do a good job of catching real problems.

You can help brittleness of these tests a bit, by relaxing your tests. You typically don't need to assert the exact sequence of function calls produced by a test. Perhaps your tests can allow more lee-way.

Actual Implementation

The ideal solution, in many cases, is to actually test against the real implementation of the api. That way you can assert that what you want to happen is actually happening and not worry about the exact parameters you passed to the API. As you note, "I can't configure the external system from my tests, so integration tests are out of the question." So this looks like it may not work for you.

But depending on why exactly you can't configure the external system in a test, there may still be a way to use it. One possibility is to setup your tests such that they can be run in two modes. In the first mode, they actually run against the external system, and verify that the correct things happens. However, they also record the sequence of api calls that were made. In the second, you simply verify that the same sequence of calls were made.

During normal development, you simply run tests in the second mode, on the assumption that you don't usually need to modify the calls that were made. But in the case that you refactor the code and change the calls, you re-run the tests against the external api and recapture the sequence of calls made. Then you can continue coding having your tests maintain the new sequence.

Recording the Sequence

Another possibility, is to have two modes again. In recording mode, you record the sequence of calls made to the external api. In verifying mode, you verify that you are still making the same calls. Normally, you use verifying mode. However, whenever you do need to change the sequence of calls, you rerun the tests in recording mode to capture the new sequence of calls. You can then look at the diffs between the old and new sequence to verify that the sequence still makes sense.

Use a Fake

Instead of a mock, you can implement a fake. The difference is that the fake acts like the external api. It models the external api, maintains similar internal state and/or produces the same results. Instead of verifying that the right calls are made, verify that the fake got put into the right state or provided the same result. It can verify any number of rules about what the callers of the api are allowed to do. For example, if you can't call the "foobar" method before calling the "baz" method, then the fake can throw an exception.

Fakes are very nice and flexible, but do require time to implement.
Sometimes you may be able to improvise a fake by building on existing libraries/solutions. For example, a "real" SQL database can be faked by using an embedded database, such as H2.

Avoid The Api

You can try to structure your program so that as little as possible actually has to interact with the external api. This may require some clever thinking. Typically, you can reduce the amount of program that directly interacts with the problematic api to a small part.


答:
The "matrix method" has several problems:

Why only two dimensions?  Very few molecules are flat, two dimensional structures (unless you work exclusively with graphene).  Pretty much any program deals with chemical structures will want to work in 3D (excluding ones whose sole purpose is to draw structural formulas).  By collapsing everything into 2D, you are losing valuable information.

What benefit would this method give?  For one thing, finding adjacent atoms is rather complex: you have to look at adjacent neighbors in the matrix, of which you only get a maximum of 4 before you have to branch off using "Root".  The artificial restriction of 4 neighbors in a matrix will make your code very ugly.

My only guess as to why you want to use this is because you want to eventually display the molecules.  The display is the complicated part (flattening a 3D molecule into a 2D formula is a bit of an art even for a human), but you should seek to separate the display logic from the internal data that stores the molecular structure.

I'm not entirely clear what your "dictionary method" means: for example, what does Atoms denote?  Are they just arbitrary labels, IDs, or the element's symbol?  (Keep in mind that dictionary keys must be unique so element symbol won't work.)

You can take advantage of the fact that Python allows you to have cyclic references and construct graphs of the atoms.  This allows you easily figure out the adjacent atoms.

Here's an example:

class Atom(object):
    def __init__(self, element, position):
        self.element = element
        self.position = position
        # each one for a different bond order, starting at 1
        self.bonds = [set(), set(), set(), set()]
    def bond_with(self, other, order=1):
        self.bonds[order].add(other)
        other.bonds[order].add(self)

# construct hydrogen fluoride
H = Atom("H", (0.0, 0.0, 0.0))
F = Atom("F", (0.0, 0.0, 1.0))
H.bond_with(F)
HF = set((H, F))
```

Title: Should I use nested matrices or dictionaries?

Body:
As per Should I ask my question about which data structure to use here? I'm asking this here.  Hopefully this isn't too implementation specific.

I'm currently developing a program that will represent chemical structures (and eventually allow manipulations/reactions of them).  I've hashed out two different systems of storing this data but I'm not sure how to pick which one.

Option 1: Nested matrices

Chemicals have (more or less) definite structures and relative positions of items, and it seems as though it would be easier to represent something like that with a matrix - then I can assign definite 'coordinates' to each atom or bond.  Unfortunately, you end up with some overlap if you have a structure that branches out a fair bit.  To solve this I ended up working out a solution that used nested, 5x5 matrices.

```<code>[[None,  None, [CH3], None, None ],
 [None,  None, Bond,  None, None ],
 [[CH3], Bond, C,     Bond, [CH3]],
 [None,  None, Bond,  None, None ],
 [None,  None, [CH3], None, None ]]
</code>```

Here C represents the element carbon (this could be represented a couple different ways, and isn't particularly relevant here).  Bond represents a bond, and [CH3] represents another 5x5 matrix.  This is the uppermost ([0][2]) CH3

```<code>[[None, None, H,    None, None],
 [None, None, Bond, None, None],
 [H,    Bond, C,    Bond, H   ],
 [None, None, Bond, None, None],
 [None, None, Root, None, None]]
</code>```

Here the lowermost Bond is a reference to the same object as the uppermost Bond in the first structure, while Root is (some undetermined) way of relating that this is where the matrix connects to the next level up.  If this were a more complex structure, one of the Hs would be replaced by another matrix, such as an additional [CH3].

Advantages of this method:

Everything is explicitly laid out, including structure, which is good
according to The Zen of Python.

When these chemicals are (eventually) represented graphically it will (theoretically) be     much easier to make sure everything is in its place

Disadvantages:

This isn't readable at all if you have a more complex structure

This is nested, not flat

This is going to require a lot of recursion to walk through

Option 2: Dictionaries

Another way I could represent these with significantly less nesting and better readability would be using dictionaries. Each molecule would be a key in a dictionary {Molecule1 : Data, Molecule2 : Data} and the data would be dictionaries as well Atoms: Data, Bonds: Data.  This requires quite a bit less nesting, but would require a little more work when I eventually want to display them.

Closing thoughts

Before asking this question, and indeed while writing it, I've been pretty set on dictionaries.  It seems like a cleaner and easier method of storing this data, and won't require figuring out a really nasty recursive technique to walk through a molecule.  However I wouldn't be surprised if I missed something which is why I'm asking here.

If this seems too implementation specific please let me know what you think I should change and I'll do my best to make it more general


问:
Does a custom scripting language require it's own compiler/assembler?
Or is the script generally converted to a known language such as C++ first?

And how generally to you integrate a scripting language with the say a game engine?

答:
It varies by language. Many scripting languages are run on VMs that are coded in assembly or C. Python and Ruby are both examples of this. The second part of your question is far too broad so I'm going to narrow it down and talk about Lua for a bit.

Lua is an excellent case study for anyone wanting to understand or build a scripting language. It very much follows the philosophy of "Be fast, be light, and stay out of the way". It can be used with its own VM or in a number of other contexts such as compiled directly to C. This makes it a very popular choice for both game scripting as well as for embedded systems programming since it has a tiny memory footprint for a dynamically typed scripting language. Lua can have objects if you want or not if you don't.

Lua has a C API, this is how you bolt Lua on to your C based engine (or C++ if you'd like) In general, you use what are called foreign function interfaces (FFI) to do things like this in other languages.

Our game development site goes into massive detail on this process as well as specifics for Lua.


问:
I don't understand the arguments against operator overloading
I just read one of Joel's articles in which he says:

In general, I have to admit that I’m a little bit scared of language features that hide things. When you see the code

```<code>i = j * 5;
</code>```

… in C you know, at least, that j is being multiplied by five and the results stored in i.

But if you see that same snippet of code in C++, you don’t know anything. Nothing. The only way to know what’s really happening in C++ is to find out what types i and j are, something which might be declared somewhere altogether else. That’s because j might be of a type that has operator* overloaded and it does something terribly witty when you try to multiply it.

(Emphasis mine.) Scared of language features that hide things? How can you be scared of that? Isn't hiding things (also known as abstraction) one of the key ideas of object-oriented programming? Everytime you call a method a.foo(b), you don't have any idea what that might do. You have to find out what types a and b are, something which might be declared somewhere  altogether else. So should we do away with object-oriented programming, because it hides too much things from the programmer?

And how is j * 5 any different from j.multiply(5), which you might have to write in a language that does not support operator overloading? Again, you would have to find out the type of j and peek inside the multiply method, because lo and behold, j might be of a type that has a multiply method that does something terribly witty.

"Muahaha, I'm an evil programmer that names a method multiply, but what it actually does is totally obscure and non-intuitive and has absolutely nothing to do whatsoever with multiplying things." Is that a scenario we must take into consideration when designing a programming language? Then we have to abandon identifiers from programming languages on the grounds that they might be misleading!

If you want to know what a method does, you can either glance at the documentation or peek inside the implementation. Operator overloading is just syntactic sugar, and I don't see how it changes the game at all.

Please enlighten me.

答:
In general, I avoid using operator overloading in non-intuitive ways.  That is, if I have a numeric class, overloading * is acceptable (and encouraged).  However, if I have a class Employee, what would overloading * do?  In other words, overload operators in intuitive ways that make it easy to read and understand.

Acceptable/Encouraged:

```<code>class Complex
{
public:
    double r;
    double i;

    Complex operator*(const Compex& rhs)
    {
        Complex result;
        result.r = (r * rhs.r) - (i * rhs.i);
        result.i = (r * rhs.i) + (i * rhs.r);
        return result;
    }
};
</code>```

Not acceptable:

```<code>class Employee
{
public:
    std::string name;
    std::string address;
    std::string phone_number;

    Employee operator* (const Employee& e)
    {
        // what the hell do I do here??
    }
};
</code>```

Body:
In general, I avoid using operator overloading in non-intuitive ways.  That is, if I have a numeric class, overloading * is acceptable (and encouraged).  However, if I have a class Employee, what would overloading * do?  In other words, overload operators in intuitive ways that make it easy to read and understand.

Acceptable/Encouraged:

class Complex
{
public:
    double r;
    double i;

    Complex operator*(const Compex& rhs)
    {
        Complex result;
        result.r = (r * rhs.r) - (i * rhs.i);
        result.i = (r * rhs.i) + (i * rhs.r);
        return result;
    }
};

Not acceptable:

class Employee
{
public:
    std::string name;
    std::string address;
    std::string phone_number;

    Employee operator* (const Employee& e)
    {
        // what the hell do I do here??
    }
};


问:
Tracking contributions from contributors not using git
I have a central git repo located on a server. I have many contributors that are not tech savvy, do not have server access, and do not know anything about git. But they are able to contribute via the project's web side. Each of them logs on via a web browser and contributes to the project.

I have set things up so that when they log on, each user's contributions are made into a cloned repo on the server that is specifically for that user. Periodically, I log on to the server, visit each of their repos, and do a git diff to make sure they haven't done anything bad. If all is well, I commit their changes and push them to the central repo.

Of course I need to manually look at their changes so that I can add an appropriate commit message. But I would also like to track who made the changes. I am making the commit, and I (and the web server) are the only users that are actually writing anything to the server.

I could track this in the commit messages. While this strikes me as wrong, if this is my only option, is there a way to make userx's cloned repo always include "userx: " before each commit message that I add, so that I do not have to remind myself which user's repo I am in?

Or even better, is there an easy way for me to make the commit, but in such a way as I credit the user whose cloned repo I am in?

答:
In git there are two names associated with a commit. An "author" and a "committer". In Your case you want to be the commiter and set the "author" accordingly using git commit's --author option.

```<code>$ git commit --author "John Doe <john.doe@example.com>" file1.dat file2.dat
$ git log --pretty=full
commit 46963e65f337fa08cfbebcd09ddf248474d49212
Author: John Doe <john.doe@example.com>
Commit: Johannes <johannes@example.com>

     Sample commit
</code>```

Alternatively if the workspace is specific to the user you could simple configure the username accordingly

```<code>$ git config --local --add user.name "John Doe"
$ git config --local --add user.email john.doe@example.com
</code>```

then they are tracked as committer and author for all commits from that clone.

Body:
In git there are two names associated with a commit. An "author" and a "committer". In Your case you want to be the commiter and set the "author" accordingly using git commit's --author option.

$ git commit --author "John Doe <john.doe@example.com>" file1.dat file2.dat
$ git log --pretty=full
commit 46963e65f337fa08cfbebcd09ddf248474d49212
Author: John Doe <john.doe@example.com>
Commit: Johannes <johannes@example.com>

     Sample commit

Alternatively if the workspace is specific to the user you could simple configure the username accordingly

$ git config --local --add user.name "John Doe"
$ git config --local --add user.email john.doe@example.com

then they are tracked as committer and author for all commits from that clone.


问:
Are there technical limitations or language features that prevent my Python script from being as fast as an equivalent C++ program?
I'm a long-time Python user. A few years ago, I started learning C++ to see what it could offer in terms of speed. During this time, I would continue to use Python as a tool for prototyping. This, it seemed, was a good system: agile development with Python, fast execution in C++.

Recently, I've been using Python more and more again, and learning how to avoid all of the pitfalls and anti-patterns that I was quick to use in my earlier years with the language. It's my understanding that using certain features (list comprehensions, enumerations, etc.) can increase performance.

But are there technical limitations or language features that prevent my Python script from being as fast as an equivalent C++ program?

答:
But are there technical limitations or language features that prevent my Python script from being as fast as an equivalent C++ program?

No. It's just a question of money and resources poured into making C++ run fast vs. money and resources poured into making Python run fast.

For example, when the Self VM came out, it was not only the fastest dynamic OO language, it was the fastest OO language period. Despite being an incredibly dynamic language (much more so than Python, Ruby, PHP or JavaScript, for example), it was faster than most of the C++ implementations that were available.

But then Sun canceled the Self project (a mature general purpose OO language for developing large systems) to focus on a small scripting language for animated menus in TV set top boxes (you might have heard about it, it's called Java), there was no more funding. At the same time, Intel, IBM, Microsoft, Sun, Metrowerks, HP et al. spent vast amounts of money and resources making C++ fast. CPU manufacturers added features to their chips to make C++ fast. Operating Systems were written or modified to make C++ fast. So, C++ is fast.

I am not terribly familiar with Python, I'm more a Ruby person, so I will give an example from Ruby: the Hash class (equivalent in function and importance to dict in Python) in the Rubinius Ruby implementation is written in 100% pure Ruby; yet it competes favorably and sometimes even outperforms the Hash class in YARV which is written in hand-optimized C. And compared to some of the commercial Lisp or Smalltalk systems (or the afore-mentioned Self VM), Rubinius's compiler isn't even that clever.

There is nothing inherent in Python that makes it slow. There are features in today's processors and operating systems that hurt Python (e.g. virtual memory is known to be terrible for garbage collection performance). There are features that help C++ but don't help Python (modern CPUs try to avoid cache misses, because they are so expensive. Unfortunately, avoiding cache misses is hard when you have OO and polymorphism. Rather, you should reduce the cost of cache misses. The Azul Vega CPU, which was designed for Java, does this.)

If you spend as much money, research and resources on making Python fast, as was done for C++, and you spend as much money, research and resources on making operating systems that make Python programs run fast as was done for C++ and you spend as much money, research and resources on making CPUs that make Python programs run fast as was done for C++, then there is no doubt in my mind that Python could reach comparable performance to C++.

We have seen with ECMAScript what can happen if just one player gets serious about performance. Within a year, we had basically a 10x performance increase across the board for all major vendors.


答:
A scripting language like any computer language has to convert its commands to machine code in order to execute. Given this fact you can take various paths to accomplish the task. You can convert the code into another language, or directly to machine code or to some custom "machine code" that runs on a VM. All the solutions have their pros and cons so the solution you choose depends on the nature of your problems.
Integrating a scripting language with a game engine should not be that hard. All the game engines provide programming interfaces to integrate them with your code part of which is the scripting language.</p>

Title: Does a custom scripting language require it's own compiler/assembler?

Body:
Or is the script generally converted to a known language such as C++ first?

And how generally to you integrate a scripting language with the say a game engine?


问:
Implementation of instance testing in Java, C++, C#
For curiosity purposes as well as understanding what they entail in a program, I'm curious as to how instance testing (instanceof/is/using dynamic_cast in c++) works.  I've tried to google it (particularly for java) but the only pages that come up are tutorials on how to use the operator.

How do the implementations vary across those langauges?  How do they treat classes with identical signatures?

Also, it's been drilled into my head that using instance testing is a mark of bad design.  Why exactly is this?  When is that applicable, instanceof should still be used in methods like .equals() and such right?

I was also thinking of this in the context of exception handling, again particularly in Java.  When you have mutliple catch statements, how does that work?  Is that instance testing or is it just resolved during compilation where each thrown exception would go to?

答:
I'm curious as to how instance testing (instanceof/is/using dynamic_cast in c++) works

In Java, each object stores a pointer to its type. Each type knows its parent types, so it's straightforward to enumerate all ancestor types. x instanceof T iff we encounter T during the search.

Similarly, in C++, objects of classes with virtual methods will store a pointer to a type_info:

Every virtual table shall contain one entry that is a pointer to an object derived from std::type_info. (source)

(This is gcc-specific though; I don't know about other compilers.)

Also, it's been drilled into my head that using instance testing is a mark of bad design. Why exactly is this? When is that applicable, instanceof should still be used in methods like .equals() and such right?

The idea is that, when possible, it's preferable to use polymorphism rather than checking for specific subtypes. It tends to be more elegant, and there's no possibility of forgetting to update our subtype checks when we add a new subtype.

Totally contrived example: say we have Animal with subtypes Lion, etc. If we want to check if Animal a is a carnivore, we could write a instanceof Lion || a instanceof Bear || ..., but it would be cleaner and safer to add an abstract boolean isCarnivore(); in Animal.

But I agree, instanceof is still appropriate in equals since the API forces us to deal with Objects.

When you have mutliple catch statements, how does that work? Is that instance testing or is it just resolved during compilation where each thrown exception would go to?

In Java, it's not possible for a compiler to precompute each exception's path because new exception classes could be loaded at runtime.

The compiler does generate an "exception table" for each try/catch block, where a row in the table contains an exception type and a pc offset which should be applied if that exception is encountered. But if you declare catch (IOException), the exception table will only contain IOException, not subclasses like EOFException. An instanceof-like check has to be done at runtime to check if a thrown exception is an IOException.


问:
Relative encapsulation design
Let's say I am doing a 2D application with the following design:

There is the Level object that manages the world, and there are world objects which are entities inside the Level object.

A world object has a location and velocity, as well as size and a texture. However, a world object only exposes get properties. The set properties are private (or protected) and are only available to inherited classes.

But of course, Level is responsible for these world objects, and must somehow be able to manipulate at least some of its private setters. But as of now, Level has no access, meaning world objects must change its private setters to public (violating encapsulation).

How to tackle this problem? Should I just make everything public?

Currently what I'm doing is having a inner class inside game object that does the set work. So when Level needs to update an objects location it goes something like this:

```<code>void ChangeObject(GameObject targetObject, int newX, int newY){
 // targetObject.SetX and targetObject.SetY cannot be set directly
 var setter = new GameObject.Setter(targetObject);
 setter.SetX(newX);
 setter.SetY(newY);
}
</code>```

This code feels like overkill, but it doesn't feel right to have everything public so that anything can change an objects location for example.

答:
This has clear answer: Interfaces (or variations of them in languages than don't support them).

Objects can implement various interfaces, that allow level to manipulate them. For example, there could be IMovable interface, that allows object to change it's position. Then, if you used is and as operators, you could cherry-pick objects that are movable and operate on them. This has multiple advantages. First is that it is not necessary to objects themselves to implement those interfaces. You could have wrappers around those objects, which them implement level interfaces, achieving higher decoupling. You could also use C#'s explicit interface implementation to "hide" those interfaces, so their methods are not called "accidentally".

Title: Relative encapsulation design


问:
How to verify the code that could take a substantial time to compile?
As a follow up to my prev question:

What is the best aproach for coding in a slow compilation environment

To recap: I am stuck with a large software system with which a TDD ideology of "test often" does not work. And to make it even worse the features like pre-compiled headers/multi-threaded compilation/incremental linking, etc is not available to me - hence I think that the best way out would be to add the extensive logging into the system and to start "coding in large chunks", which I understand as code for a two-three hours first (as opposed to 15-20 mins in TDD) - thoroughly eyeball the code for a 15 minutes and only after all that do the compilation and run the tests.

As I have been doing TDD for a quite a while, my code eyeballing / code verification skills got rusty (you don't really need this that much if you can quickly verify what you've done in 5 seconds by running a test or two) - so I am after a recommendations on how to learn these source code verification/error spotting skills again.

I know I was able to do that easily some 5-10 years ago when I din't have much support from the compiler/unit testing tools I had until recently, thus there should be a way to get back to the basics.

答:
```<code>   >  I am after a recommendations on how to learn these source
   > code verification/error spotting skills again.
</code>```

What about pair-programming.

4 eyes see more errors/flaws that 2 eyes

and you learn a lot about errors when thinking about questions like "why are you doing it this way?"

Body:
   >  I am after a recommendations on how to learn these source
   > code verification/error spotting skills again.

What about pair-programming.

4 eyes see more errors/flaws that 2 eyes

and you learn a lot about errors when thinking about questions like "why are you doing it this way?"


问:
FFmpeg: Can I replace libx264 with OpenH264 in order to go LGPL?
I have some video processing to run and FFmpeg already contains much of what I need. However my videos are all compressed with H.264 video codec and libx264 is a GPL part of FFmpeg. On the other hand, the Constrained Baseline Profile is pretty enough for my application which means I could perfectly use OpenH264. So would it be possible both in theory and in practice to make this replacement?</p>

答:
As OpenH264 is available under a permissive, BSD-style license, it it legally possible to create a version of it that will work as a codec for FFmpeg.

Given enough time, I am sure that it is also technically possible to create a FFmpeg compatible version of OpenH264.

The remaining question is if it makes economic/business sense to create a wrapper around OpenH264 or to modify OpenH264 itself to fit the expected codec API of FFmpeg. This question can only be answered by yourself.


问:
In the days of modern computing, in 'typical business apps' - why does performance matter?
This may seem like an odd question to some of you.

I'm a hobbyist Java programmer. I have developed several games, an AI program that creates music, another program for painting, and similar stuff. This is to tell you that I have an experience in programming, but not in professional development of business applications.

I see a lot of talk on this site about performance. People often debate what would be the most efficient algorithm in C# to perform a task, or why Python is slow and Java is faster, etc.

What I'm trying to understand is: why does this matter?

There are specific areas of computing where I see why performance matters: games, where tens of thousands of computations are happening every second in a constant-update loop, or low level systems which other programs rely on, such as OSs and VMs, etc.

But for the normal, typical high-level business app, why does performance matter?

I can understand why it used to matter, decades ago. Computers were much slower and had much less memory, so you had to think carefully about these things.

But today, we have so much memory to spare and computers are so fast: does it actually matter if a particular Java algorithm is O(n^2)? Will it actually make a difference for the end users of this typical business app?

When you press a GUI button in a typical business app, and behind the scenes it invokes an O(n^2) algorithm, in these days of modern computing - do you actually feel the inefficiency?

My question is split in two:

In practice, today does performance matter in a typical normal business program?

If it does, please give me real-world examples of places in such an application, where performance and optimizations are important.

答:
Yes. Yes, it does. Run-time speed isn't the only concern you should be having, and it's not as pressing as it was in 1982, or as it still is on low-powered embedded systems, but it's always a concern, and it's important that you understand why this is so.

For one, the asymptotic complexity you mention describes a program's behaviour as its input size grows. A non-linear program that deals with 10 items can get away with doing superfluous work, but it will bite you when one day you have to deal with 1000, because it won't just seem slower, but much, much slower. And you don't know (without extensive analysis and benchmarking) whether that point will be at 100 items, at 1000 items, or not until you hit 100,000 items. It may be hard to believe, but choosing the  best algorithm as a matter of course is in fact a lot easier than estimating this point for every routine and choosing your implementation depending on this estimate.

Also, please read up on user experience basics. There are well-researched thresholds that determine how the interaction with a program is perceived depending on its response times (10ms, 100ms, a few seconds etc.). Crossing one of these thresholds will cause users to disengage from your application, and unless you are in the happy position of writing monopoly software that people have to use, disengaged users translates directly to negative business value because it leads to loss of customers.

These are only a few of the reasons why a professional programmer must know about algorithmic complexity and handle it responsibly. These days it's usually not necessary to go out of your way and program especially optimized, badly-readable code for anything unless it's turned out to be  time-critical inner loop, but you should never, ever invoke a complexity class higher than is obviously necessary to do the job.


答:
In practice, today does performance matter in a typical normal business program?

I don't know what is a typical normal business program.  What I do know, is that users always end up by feeding our programs with much more data than we planned (often after aksing them how big it would be and adding a security margin) and that in those case, they expect a linear increase of run-time, accept a n log n behavior and complain that the application freezes when anything else happens. And they tend to consider the size of the result more than the size of the input excepted in case where it is obvious from their POV that all input data has to be processed.

So yes, performance, at least at the complexity level, matters. Micro-optimization inside a complexity class does not really matter, excepted if you are visibly worse than the competition (either in benchmarks in some markets or by raw perception -- changing the class in the progression "instantaneous", "not instantaneous but user doesn't switch to something else", "slow enough that the user switch to something else at the risk of interruption the flow of actions", "slow enough that the user launch the task and then check from time to time", "slow enough that the user plan to launch the task over lunch, over night, over the week-end").

Title: In the days of modern computing, in 'typical business apps' - why does performance matter?

Body:
This may seem like an odd question to some of you.

I'm a hobbyist Java programmer. I have developed several games, an AI program that creates music, another program for painting, and similar stuff. This is to tell you that I have an experience in programming, but not in professional development of business applications.

I see a lot of talk on this site about performance. People often debate what would be the most efficient algorithm in C# to perform a task, or why Python is slow and Java is faster, etc.

What I'm trying to understand is: why does this matter?

There are specific areas of computing where I see why performance matters: games, where tens of thousands of computations are happening every second in a constant-update loop, or low level systems which other programs rely on, such as OSs and VMs, etc.

But for the normal, typical high-level business app, why does performance matter?

I can understand why it used to matter, decades ago. Computers were much slower and had much less memory, so you had to think carefully about these things.

But today, we have so much memory to spare and computers are so fast: does it actually matter if a particular Java algorithm is O(n^2)? Will it actually make a difference for the end users of this typical business app?

When you press a GUI button in a typical business app, and behind the scenes it invokes an O(n^2) algorithm, in these days of modern computing - do you actually feel the inefficiency?

My question is split in two:

In practice, today does performance matter in a typical normal business program?

If it does, please give me real-world examples of places in such an application, where performance and optimizations are important.


答: Bear in mind that for server based applications, you may have hundreds, thousands or even millions of users trying to do things at the same time. A small saving in efficiency in such a situation can have a major impact on the amount of hardware required to service requests.</p>


答:
In modern business applications, the performance problems are not in form of lack of CPU or memory. But they are in form of network latencies, I/O performance and abstractions hiding all of those. It all depends on how good the design and how experienced the developers are. Even simple CRUD application can crawl to a halt if it is pulling from DB one row at a time instead of running a query (also known as N+1 problem).

The problem is that having good design and experienced developers is expensive. And it is usually much cheaper to have irritated users than investing into actual performance optimizations. There are some cases, where customers will require high performance(eg. web browsers), but those rarely apply to common business applications.


答:
You're right, performance in business apps is not really an important subject the way it is discussed by most programmers. Usually, performance-related discussions I hear from programmers have several issues:

They are mostly premature optimization. Usually, someone wants "the fastest way" to do an operation with no apparent reason, and ends up either making code changes which are made by most compilers anyway (such as replacing division by multiplication or inlining a method), or spending days making changes which will help gaining a few microseconds at runtime.

They are often speculative. I'm glad to see that on Stack Overflow and Programmers.SE, profiling is mentioned frequently when the question is related to performance, but I'm also disappointed when I see two programmers who don't know what profiling are discussing about performance-related changes they should do in their code. They believe the changes will make everything faster, but practically every time, it will either have no visible effect or slow the things down, while a profiler would have pointed them to another part of the code which can easily be optimized and which wastes 80% of the time.

They are focused on technical aspects only. Performance of user-oriented applications is about the feeling: does it feel fast and responsive, or does it feel slow and clunky? In this context, performance problems are usually solved much better by user experience designers: a simple animated transition may often be the difference between an app which feels terribly slow and the app which feels responsive, while both spend 600 ms. doing the operation.

They are based on subjective elements even when they are related to technical constraints. If it's not the question of feeling fast and responsive, there should be a non-functional requirement which specifies how fast an operation should be performed on specific data, running on specific system. In reality, it happens more like that: the manager tells that he finds something slow, and then, developers need to figure out what does that mean. Is it slow like in "it should be below 30 ms. while currently, it wastes ten seconds", or slow like "we can maybe lower the duration from ten to nine seconds"?

Early during my career as a programmer, I was working on a piece of software for a bunch of my customers. I was convinced this software is the next great thing which will bring happiness to the world, so I was obviously concerned by performance.

I've heard terms such as "profiling" or "benchmark", but I didn't know what they mean and couldn't care less. Moreover, I was too focused reading the book about C, and especially the chapter where optimization techniques were discussed. When I discovered that computers perform multiplication faster than division, I replaced division by multiplication anywhere I could. When I discovered that calling a method can be slow, I combined as much methods as I could, as if the previous 100 LOC methods weren't already an issue.

Sometimes, I spent nights doing changes which, I was convinced, made difference between a slow app nobody wants, and a fast one everybody wants to download and use. The fact that two actual customers who were interested by this app requested actual features wasn't bothering me: "Who would want a feature, if the app is slow?"—I thought.

Finally, the only two customers stopped using the app. It wasn't amazingly fast despite all my efforts, mostly because when you don't know what indexes are and your app is database-intensive, there is something wrong. Anyway, when I was doing just another performance-related change, which was improving by a few microseconds the execution of code which is used once per month, customers didn't see changes. What they were seeing is that user experience is terrible, documentation is missing, crucial features they were requesting for months were not here and the number of bugs to solve was constantly growing.

Result: I hoped this app will be used by thousands of companies around the world, but today, you won't find any information about this application on the internet. The only two customers abandoned it, and the project was abandoned as well. It was never marketed, never publicly advertised, and today, I'm not even sure I can compile it on my PC (nor find the original sources). This wouldn't have happened if I was focusing more on things that actually matter.

This being said, performance in general is important:

In non-business apps, it can become crucial. There is embedded software, software ran on servers (when you have a few thousand of requests per second, which is not that big, performance starts to be a concern), software ran on smartphones, video games, software for professionals (try to handle a 50 GB file in Photoshop on a not very fast machine to be convinced) and even ordinary software products which are sold to lots of people (if Microsoft Word spends twice its time to do every operation it does, the time lost multiplied by the number of users will become an issue).

In business apps, there are many cases where an application which feels and is slow will be hated by the users. You don't want that, making performance on of your concerns.


问:
Should I limit my type name suffix vocabulary when using OOP?
My co-workers tend to think that it is better to limit non-domain type suffixes to a small fixed set of OOP-pattern inspired words, e.g.:

*Service

*Repository

*Factory

*Manager

*Provider

I believe there is no reason to not extend that set with more names, e.g. (some "translation" to the previous vocabulary is given in brackets):

*Distributor (=> *DistributionManager or *SendingService)

*Generator

*Browser (=> *ReadonlyRepositoryService)

*Processor

*Manipulator (=> *StateMachineManager)

*Enricher (=> *EnrichmentService)

(*) denotes some domain word, e.g. "Order", "Student", "Item" etc.

The domain is probably not complex enough to use specialized approaches such as DDD which could drive the naming.

答:
You can have any vocabulary you want, as long as everyone in team understands and agrees on what it means.

The reason why design patterns exist is that their names are (usually) widely known and even someone else outside your team knows what you mean when you say "This is a Builder". The problem I see with your proposal is just that. I have no idea what any of those mean. If you can agree with your team that you are using some pattern and agree on what that pattern is, then giving it some fitting name is obvious final step.


答:
You wouldn't believe the amount of 3rd party business programs we use at work, and many of them are just ridiculously slow to use compared to my personal standards. If the programs were something I use at home, I would have replaced them with an alternative one a long time ago.

In some cases, the difference goes directly into the costs, as some programs directly affect how many tasks I can accomplish during a day, and thus lowers my productivity and amount billable items. So I would say it is quite important for business programs, too, to be at least performant enough as not to be the limiting item for income.

An example is incident management where the work is measured in 15 minute intervals (service desk). If the program is slow enough to push one ticket to take more than 15 minutes (incl. the actual work), it will slow down the process quite a lot. One cause could be a slow database access that simply "waits for a while" whenever the user does an action (fill resolution details, update work info, or similar). I can imagine there are cases where slow programs can even affect more critical things, such as hospital patient details on urgent poisoning cases - maybe medicine allergies or such?


问:
How to handle "circular dependency" in dependency injection
The title says "Circular Dependency", but it is not the correct wording, because to me the design seems solid.

However, consider the following scenario, where the blue parts are given from external partner, and orange is my own implementation. Also assume there is more then one ConcreteMain, but I want to use a specific one. (In reality, each class has some more dependencies, but I tried to simplify it here)

I would like to instanciate all of this with Depency Injection (Unity), but I obviously get a StackOverflowException on the following code, because Runner tries to instantiate ConcreteMain, and ConcreteMain needs a Runner.

```<code>IUnityContainer ioc = new UnityContainer();
ioc.RegisterType<IMain, ConcreteMain>()
   .RegisterType<IMainCallback, Runner>();
var runner = ioc.Resolve<Runner>();
</code>```

How can I avouid this? Is there any way to structure this so that I can use it with DI? The scenario I'm doing now is setting everything up manually, but that puts a hard dependency on ConcreteMain in the class which instantiates it. This is what i'm trying to avoid (with Unity registrations in configuration).

All source code below (very simplified example!);

```<code>public class Program
{
    public static void Main(string[] args)
    {
        IUnityContainer ioc = new UnityContainer();
        ioc.RegisterType<IMain, ConcreteMain>()
           .RegisterType<IMainCallback, Runner>();
        var runner = ioc.Resolve<Runner>();

        Console.WriteLine("invoking runner...");
        runner.DoSomethingAwesome();

        Console.ReadLine();
    }
}

public class Runner : IMainCallback
{
    private readonly IMain mainServer;

    public Runner(IMain mainServer)
    {
        this.mainServer = mainServer;
    }

    public void DoSomethingAwesome()
    {
        Console.WriteLine("trying to do something awesome");
        mainServer.DoSomething();
    }

    public void SomethingIsDone(object something)
    {
        Console.WriteLine("hey look, something is finally done.");
    }
}

public interface IMain
{
    void DoSomething();
}

public interface IMainCallback
{
    void SomethingIsDone(object something);
}

public abstract class AbstractMain : IMain
{
    protected readonly IMainCallback callback;

    protected AbstractMain(IMainCallback callback)
    {
        this.callback = callback;
    }

    public abstract void DoSomething();
}

public class ConcreteMain : AbstractMain
{
    public ConcreteMain(IMainCallback callback) : base(callback){}

    public override void DoSomething()
    {
        Console.WriteLine("starting to do something...");
        var task = Task.Factory.StartNew(() =>{ Thread.Sleep(5000);/*very long running task*/ });
        task.ContinueWith(t => callback.SomethingIsDone(true));
    }
}
</code>```

答: Use an IOC container that supports this scenario. I know that AutoFac and possible others does. When using AutoFac the restriction is that one of the dependencies must have PropertiesAutoWired=true and use a Property for the dependency.</p>


答:
Yes it does!

Since you asked for examples, several every-day situations come to mind:

Handling big-data: Many business-applications are backed by data-bases and in many instances these data-bases overflow with data. And since drive-space is cheap, the amounts of recorded and stored data are insane. Just last week a customer complained, that his application is sooo slow, when just displaying some average numbers (queries over some million rows...) - Also in everyday use we have batch-data conversions and calculations with runtimes in the league of several hours. Last year an algorithmic optimization brought the process time of one batch run down from 8 to 4 hours, now it doesn't collide with the day shift anymore!

Responsiveness: There have been usability studies (if I have time I will add links to the relevant questions on ux.se...) that user satisfaction is heavily related to responsiveness. A difference in a response-time of 200ms vs. 400ms can easily cost you a big percentage of your customers leaving you for your competitors.

Embedded Systems: Computers are not getting faster, they are getting slower and smaller ^_^ Mobile development has a huge impact on application development. Sure we can throw around memory and CPU cycles like Jelly Beans on modern Desktop computers, but now your boss asks you to implement the sleep-analyzing algorithm on a freakin watch or on a SIM-Card...


问:
How to write a user story specific to tasks in this case
We have planned to take up an user story say

As a player I want to view the game map to know current standings of my team

The sprint is for two weeks. We will be able to complete only HTML in two weeks time, this user story will take 4-6 weeks to be completed as we have a shortage of content designing resources.

How can we change this user story so that HTML completion can be considered as a done for this user story and we need to take up the integration of this user story in the next sprint?

Is it possible to create two different user stories, one for HTML and other for integration, testing, bug fixing etc?

答:
As with all stories, think of what you need, who it's for, and why they need it. The user doesn't have to be the end user. Remember that the end goal of writing stories is to help you and your team. You don't get bonus points for making stories that fit a definition from a book. Break the story up into smaller pieces that help your team focus.

For example, a front end story:

As a developer building the game map, I need the HTML markup to be created so that I can display the map.

... and a back end story

As a developer building the game map, I need to back-end API to support fetching the game data so that I can display it on the map

... perhaps a design story

As a developer building the game map, I need to final style sheets to be developed so that the user enjoys using the map.

...and so on.


问:
single for-loop runtime explanation problem
I am analyzing some running times of different for-loops, and as I'm getting more knowledge, I'm curious to understand this problem which I have still yet to find out.
I have this exercise called "How many stars are printed":

```<code>for (int i = N; i > 1; i = i/2) System.out.println("*");
</code>```

The answers to pick from is

A: ~log N
B: ~N
C: ~N log N
D: ~0.5N^2

So the answer should be A and I agree to that, but on the other side.. Let's say N = 500 what would Log N then be? It would be 2.7. So what if we say that N=500 on our exercise above? That would most definitely print more han 2.7 stars? How is that related?

Because it makes sense to say that if the for-loop looked like this:

```<code>for (int i = 0; i < N; i++)
</code>```

it would print N stars.

I hope to find an explanation for this here, maybe I'm interpreting all these things wrong and thinking about it in a bad way. Thanks in advance.

答:
You've overlooked the key characteristic of the logarithm base.

Because i is divided by 2 in each iteration, the running time is logarithmic with base 2. And

log2(500) ~ 8.9

What you are looking at is

log10(500) ~ 2.7

(logarithm with base 10)

By the way, the reason why the base is often omitted in runtime discussions (and your calculator probably doesn't have a button for log2) is that due to the mechanisms of logarithmic math, a different base corresponds to a constant factor and thus is not relevant when you're ignoring constant factors anyway. It can be calculated easily:

loga(x) = logb(x) / logb(a)


答:
I think you're interpreting the amount of questions asked about performance as an indication that performance requirements for business apps are important instead of recognizing that improving performance is difficult. Just getting it to work can be accomplished by brute-force techniques, trial and error or copying and pasting example code.

Anyone can get lucky and keep making changes until something runs faster, but that rarely works. Due to a lack of experience, developers will see outside help. In some environments, performance improvements are a unique problems, so asking a specific question on a site like StackOverflow may be the only option. Also, many consultants make their money by being able to step in and fix these kinds of problems.