答:
For infrastructure tasks (device drivers, embedded systems, compression algorithms, encryption algorithms, core OS functions) C will remain unbeatable.

In these areas type safety is a nuisance you need to be able to address arbitrary areas of memory, you need twiddle bits in data that may not be defined as a bit twiddling type.

Ada and native assembly do actually compete in this space and are both viable alternatives.

Java etc. is completely unfeasible as these low level functions use structures to pass data to and fro, Other than "walking" along a buffer and laboriously pulling out each data element Java does not handle  structures.

C++ is possible but does not really confer enough advantages is these areas to justify the performance overhead, or, the "comprehension" overhead ( the language is just to complex for casual reading of code.).

So far the only candidate language which could possibly compete in this space is Google's "Go" but it is still relatively immature, and, many companies would be nervous about betting the farm on something from a major competitor.

Title: What do other languages offer when it comes to infrastructure technology that could indicate its advantage over C in the future?

Body:
I have been going through interview questions and I saw one which made me stop and think for a while. It starts with a quote and asks about your interpretation and whether you agree or not.

"For infrastructure technology, C will be hard to displace." - Dennis Ritchie

From a bit of background reading you can find that he was the mastermind behind C language as well as the UNIX OS. At the time it was a phenomenal improvement and at the forefront of cutting edge techniques. I feel that C++ and Java are becoming increasingly popular languages, but C will always be an important language.

What do other languages offer when it comes to infrastructure technology that could indicate its advantage over C in the future. On a side note, does anybody know which year this quote was made? I just want the opinions of people who use these languages a lot, I myself use python language and would love to learn a bit more about the framework around C and it's importance firsthand.


问:
How are new file formats constructed?
I've used a software suite that is installed in offices and on remote vessels. The installations communicate back and forth, and they do that by using a simple proprietary file format that looks something like this:

```<code>/SHIP:16
MILES=45213

/ORDER:22943
STATUS=OPEN
TOTAL=447.84
URGENCY=HIGH

/ORDERLINES:22943
ITEM=3544
QUANTITY=1
PRICE=299.99
ITEM=11269
QUANTITY=5
PRICE=29.57
</code>```

Recently, I've been writing a piece of software for a customer that saves information in the same kind of flat file format.

When the file is opened, the lines are iterated over, and "stuff happens" to the lines (i.e. they're inserted into a database, or whatever).

But it got to me on to thinking, how would this kind of file scale? (I like things being able to scale)

I could of course gzip it; but how does a file format evolve from being something basic like to this, to being monolithic? What typical practises are employed when making a file format for a new piece of software? How are they typically built?

Related: Is there a proper way to create a file format? and Should I encrypt files saved by my program

答:
The ability to scale will depend on the specific usage.

If I take your example of lines inserted in a database, the closer model is a log. An application, such as a web server, writes some data to a log. Daily (or once per hour, or any other period of time), the log is rotated, i.e. the application frees the current file and starts writing to another one. Once the file is freed, an ETL can process this file and load the transformed data into the database.

If I take a different example, such as a large file (and by large, I mean several gigabytes or terabytes) which should be read in a context where any information in it should be accessed quickly, then the format would be different and will probably use pages and indexes to point to the right content; additionally, fragmentation will be a concern too if the data in the file is modified. You can find more information about this sort of usage by reading about PST file format used by Microsoft Outlook (it can often take gigabytes) or file formats used by database files.

This means that the format you are actually using is maybe extremely scalable in the context in which it is used.

How are they typically built?

Like any data structure and any piece of software in general.

Ideally, during architecture and design phase, developers think about ways they can store information in a file, given the different requirements, priorities and constraints. Then the file format can evolve to take in account new requirements, priorities and constraints, while being, if needed, backwards compatible.

Examples:

If a requirement in the format you've shown in your question is that values can be multiline and contain “=”, this brings a specific issue of a value such as “12345¶=PRICE=123”.

If a requirement is to follow the standards, then something like EDIFACT can be used instead of the current format (maybe with some metadata if needed).

If the priority is to make the file readable, “item” and “price” are fine or may even be expanded to be more explicit. If the priority is to shorten the size of the file, “item” could become “i”, “quantity” — “q”, etc. Even better, the file can become:

```<code>> 22943:3544,1,299.99;11269,5,29.57…
</code>```

or be transformed to a binary format.

If a constraint is to keep the data secure, cryptography will be used. If another constraint tells that some of the involved systems don't support Unicode, this is an additional problem to solve.

ContentLicense: CC BY-SA 3.0

Title: How are new file formats constructed?

Body:
The ability to scale will depend on the specific usage.

If I take your example of lines inserted in a database, the closer model is a log. An application, such as a web server, writes some data to a log. Daily (or once per hour, or any other period of time), the log is rotated, i.e. the application frees the current file and starts writing to another one. Once the file is freed, an ETL can process this file and load the transformed data into the database.

If I take a different example, such as a large file (and by large, I mean several gigabytes or terabytes) which should be read in a context where any information in it should be accessed quickly, then the format would be different and will probably use pages and indexes to point to the right content; additionally, fragmentation will be a concern too if the data in the file is modified. You can find more information about this sort of usage by reading about PST file format used by Microsoft Outlook (it can often take gigabytes) or file formats used by database files.

This means that the format you are actually using is maybe extremely scalable in the context in which it is used.

How are they typically built?

Like any data structure and any piece of software in general.

Ideally, during architecture and design phase, developers think about ways they can store information in a file, given the different requirements, priorities and constraints. Then the file format can evolve to take in account new requirements, priorities and constraints, while being, if needed, backwards compatible.

Examples:

If a requirement in the format you've shown in your question is that values can be multiline and contain “=”, this brings a specific issue of a value such as “12345¶=PRICE=123”.

If a requirement is to follow the standards, then something like EDIFACT can be used instead of the current format (maybe with some metadata if needed).

If the priority is to make the file readable, “item” and “price” are fine or may even be expanded to be more explicit. If the priority is to shorten the size of the file, “item” could become “i”, “quantity” — “q”, etc. Even better, the file can become:

> 22943:3544,1,299.99;11269,5,29.57…

or be transformed to a binary format.

If a constraint is to keep the data secure, cryptography will be used. If another constraint tells that some of the involved systems don't support Unicode, this is an additional problem to solve.


问:
What do other languages offer when it comes to infrastructure technology that could indicate its advantage over C in the future?
I have been going through interview questions and I saw one which made me stop and think for a while. It starts with a quote and asks about your interpretation and whether you agree or not.

"For infrastructure technology, C will be hard to displace." - Dennis Ritchie

From a bit of background reading you can find that he was the mastermind behind C language as well as the UNIX OS. At the time it was a phenomenal improvement and at the forefront of cutting edge techniques. I feel that C++ and Java are becoming increasingly popular languages, but C will always be an important language.

What do other languages offer when it comes to infrastructure technology that could indicate its advantage over C in the future. On a side note, does anybody know which year this quote was made? I just want the opinions of people who use these languages a lot, I myself use python language and would love to learn a bit more about the framework around C and it's importance firsthand.

答:
C is the lowest common denominator and for some things, mainly glueing different languages together, you need just that. Only another language with straightforward translation to assembly could replace it here. And there is not much demand anyway, because the key infrastructure is already written in C and nobody wants to rewrite just for sake of using new language.

C++, containing C as it's subset, can be used anywhere C is, but has to be used with care because one must control where the ++ features may get and where not. Still it is now being used for things like writing micro-controller software and operating system kernels because of the added safety (mainly via RAII) and the improved performance of templates compared to "generic" C code taking void pointers.

D and rust are two languages written to advance on the safety while still containing C-compatible subset and allowing direct unsafe access where needed. Go ruled itself out of this set because it does not provide the unsafe part.


问:
Naming conventions for Java classes that have a static main method?
After reading gnat's answer to Why a static main method in Java and C#, rather than a constructor? I take his answer to mean that the purpose of a Java class with a static main method is to define a program entry point and that it is not meant to be the program itself.

There may be a better way to do this, but I usually have the class with the static main method to do something simple like this:

```<code>public class MenuLauncher
{
    public static void main(String[] args) {
        Menu menu = new Menu();
        menu.run();
    }
}
</code>```

Would the code above be the best practice for OOP where the class with static main doesn't do much more than launch or start program logic contained within a separate non-static object; after-all main is static so wouldn't the MenuLauncher class itself be very limited? Since main is a starting point I don't see any other purpose for the class other than to be a point of entry.

Is there a Java naming convention commonly used for classes that contain a main method and serve the purpose of being a program entry-point?

答:
No, there is no widely used naming conventions for this. Examples I have seen are Main, Application, XLauncher or X, where X is the name of the project/application.

And yes, I think it's good for this class to contain only the minimum logic/code necessary to set up the application and start it. But I'm sure there are a lot of God Objects and Big Balls of Mud out there with a main method tacked onto a multi thousand line monstrosity.


答:
YAGNI

There are many different ways to "scale". If you try to design a future-proof file format without knowing with high degree of certainty how the future is going to look, you are bound to fail.

Formats readable with a plain text editor have a huge advantage for debugging. You can always open them and check them with your eyes and makeshift tools using simple text search and replacement. The development time saved compared to binary format for which you need to write debugging tools is significant. As long as your simple text format works, just stick with it.

A file of records that are processed sequentially will scale linearly with the amount of data no matter what the format is. If you change it to binary format, it will probably be smaller, but it will still scale linearly. The same effect can be achieved by compressing and it keeps most of the advantages of text format.

You only need "advanced" format when you need random access. Usually you'd than just take some existing container. If you need to just bundle resources together, most popular is plain old zip archive (it has index at the end, so you can directly read any member). If you need random access to small elements, you want either "*dbm" (berkeley db, ndbm, gdbm, odbm) or sqlite. Or a database server, of course (sqlite is faster than any rdbm server, but only allows limited concurrent access and no clustering and limited triggers etc).

Title: How are new file formats constructed?

Body:
I've used a software suite that is installed in offices and on remote vessels. The installations communicate back and forth, and they do that by using a simple proprietary file format that looks something like this:

```<code>/SHIP:16
MILES=45213

/ORDER:22943
STATUS=OPEN
TOTAL=447.84
URGENCY=HIGH

/ORDERLINES:22943
ITEM=3544
QUANTITY=1
PRICE=299.99
ITEM=11269
QUANTITY=5
PRICE=29.57
</code>```

Recently, I've been writing a piece of software for a customer that saves information in the same kind of flat file format.

When the file is opened, the lines are iterated over, and "stuff happens" to the lines (i.e. they're inserted into a database, or whatever).

But it got to me on to thinking, how would this kind of file scale? (I like things being able to scale)

I could of course gzip it; but how does a file format evolve from being something basic like to this, to being monolithic? What typical practises are employed when making a file format for a new piece of software? How are they typically built?

Related: Is there a proper way to create a file format? and Should I encrypt files saved by my program


答:
How does a file format evolve from being something basic like to this?

By not thinking ahead and refusing to use existing standards because it's cool to reinvent the wheel.

There are various industry standards, all of which formats have their own quirks, and all of them went through the same drama when they were 'scaled up' (i.e. used outside the company that made them up).  Character encodings, line endings, repetitions, parsers, all of it has to be reinvented as soon as an organization uses their inhouse developed format to communicate to the outside world.

What once started as a 'quick and dirty' way to exchange messages between two machines now becomes an heritage you'll never lose.

Sometimes though, thought is put into the structure of such formats. When you are looking to create a new format to use to store or transmit data from or to your application, please make sure absolutely no existing format fits your needs.

Title: How are new file formats constructed?


问:
What mistakes in managing software products must be avoided to keep people from hating the vendor?
A previous question about why people hate Microsoft was closed. This is an attempt at a somewhat more constructive question along the same general line. This one is both broader and narrower though. It's more general by being about software vendors in general, not just Microsoft. It's narrower by dealing only with management of software products.

So, what steps should be taken (and/or avoided) in managing individual software products to assure that not only the individual products, but the company as a whole is respected/liked/seen in a positive light?

答:
Keeping a software company in a positive light involves both sides of the transaction.

The company must:

Continuously provide code that is most fit for purpose in their chosen fields

Be seen to be continuously striving to improve by acting on customer feedback

Be seen to be fair

The customer must:

Provide feedback to the company that they are doing well/badly

Be reasonable in their expectations of responses

From these simple rules, lots of good things naturally follow. The trouble is, market forces
and competition being what it is, sticking to them is a nightmare.

ContentLicense: CC BY-SA 2.5


问:
Graph to show decreasing desirability when taking shortcuts
I'm responsible for creating a presentation to management that details how a system should be refactored or rewritten. We have an existing system that has had production failures and the code base is not in a desirable state.

Here are the current possible options:

Rewrite the system using developers that provide the best code quality

Rewrite the system using developers that write less-than-ideal code quality

Leave the system as is and just maintain it

Rewrite the system using cheaper labor on the other side of the world

The issue isn't which one to choose, because I believe #1 provides the best long-term value to the business. The issue is how to present this to management so they understand the costs to each shortcut they take from #1.

For example, I would start with presenting #1... then what? My original idea is to somehow show each shortcut and what that means in terms of long-term cost/benefit. So, perhaps management wants to use cheaper labor. I need to show what that does to quality, time, etc. How do I show that? Perhaps management wants to use a hybrid of the above options. How do I show that? There could be 20 different permutations of the above options, and I'd like to show that if they take the short-term approach of low-cost everything, what that eventually means to the quality of the product.

Are there graphs for this type of thing? A recommended approach? I could just start typing, but I don't want management's eyes to glaze over from too many words. Hope that all makes sense.

An idea is to present something like this for each option:

答:
First estimate the effort required to refactor/rewriting the code.

Then find out the cost implications of all 4 options.

Find out the loss made due to production outages of the legacy system
and then compare the benefit each approach would give comparing it with potential loss if there is a produciton outage.

You can emphasise point 2 and 3 are not something you would recommend and you can concentrate on point 1 and 4 of your presentation

Give pros and cons of both approaches and try to keep you presentation objective.
Really speaking management will be more interested in cost-benefit ratio, rather than just cost. IF the low cost offshore developers are going to fix your problem for cheap why not use them.


答:
You have to understand why C is useful for low-level systems, its mainly because it offers a compromise between how the computer works, and how humans can understand the same. Assembler would be a better systems language, if us meatbags could understand it and be productive in it.

So the key is that the level of abstraction fits a sweet spot between not slowing things down from the computers perspective, and keeping things understandable from ours.

In keeping with this, a hypothetical new language would do exactly the same things as C, with as few abstractions.

There are some things that the compiler, or tools could help us with - though, note some tools like, say garbage collection, are useful to us and theoretically make the system work more efficiently, but in practice slow things down and make them unpredicatable and sometimes more difficult to work with. I can imagine the areas that an improved C would be RAII (I love this in C++, it is awesome, the compiler puts your de-allocation routines in where you would put them!), and a better string routines - making strings null delimited made sense when memory was very expensive, but in systems where we use 2 bytes per character, this limitation is no longer around. I'd have a string prefixed with a dword for length that should improve a lot of performance. Note I wouldn't go further than that - no referenced counting string classes or anything similar, and I probably wouldn't do "classes", though I would introduce some form of mini module that helps to encapsulate related code (and compiler-generated routines like for RAII).
You might want to have some memory location routines built in, that helps with CPU cache coherency, and maybe a primitive form of threading - not so people can abuse it by spawning off threads and locks willy-nilly, but so they have to think what they are doing.

I think the latter aspect is important in C, while we can add a load of features to make life easier for the programmer, they all introduce overhead, that gets compounded by people creating more abstractions using those abstractions where you end up with seriously in-efficient code, that people use because its "fast enough". Its never fast enough for low-level systems programming :)


问:
Sort an array in a specific order - not ascending/descending
I'm working on an algorithm that works best if the inputs are passed to it in a particular order, so I want to sort them that way. The difference is drastic enough for me to consider re-sorting the array.

Consider an array a with length n. I want to sort it the following way, and return the array of indices of a instead of the values:

I define another array w, also of length n. I want to sort such that the first element is closest to the first element of w. Then, from the rest of the elements (excluding the one already sorted), the second element is closest to the second element of w, and so on.

For example a = {5.5, 6.5, 2.4, 3.1}, w = {1, 2, 6, 5}.

2.4 is closest to 1, so output[0] = 2, the index of 2.4.

2.4 is closest to 2, but already processed, so choose 3.1, output[1] = 3.

Next come 0 and 1, in that order. 0 is chosen because it comes first, although both are equidistant.

So, output = {2, 3, 0, 1} and the sorted array would be sorted = {2.4, 3.1, 5.5, 6.5} (each index is used to find the corresponding element).

I can only think of brute-forcing this algorithm. Can there be a more efficient way to do it?

答:
Insert all elements of a into a (self-balancing) Binary Search Tree (BST) - O(n log n)

For each element of w, lookup and remove the closest element in the BST and add it to the output - O(n log n)

Finding the closest element in a BST is rather easy. If the element is greater than the current node's element, look right, if it's smaller, look left, if it's equal, stop. As you go down the tree, simply keep track of the closest element.

Having it return the indices instead of the element should be trivial.

Total running time - O(n log n)


答:
Price in a manner which is open and clear - this includes not only initial purchase price but upgrades, additional features or modules, support, consultancy, training and any other associated costs.

You don't have to be cheap, you can price as aggressively as you like, but the one thing in my experience that will upset clients more than anything when it comes to price is unclear extras and the idea that they're having more money unfairly extracted from them now they've made the purchase.

Unknown costs aren't about the money, they're about people's reputation.  The person making the purchase has put some of their reputation on the line when they put a budget for the project forward.  Even if the extra expense is value for money, you've when they have to go back to their boss and ask for more money, you're making them publicly admit that they screwed up and they will hate you for that.

Title: What mistakes in managing software products must be avoided to keep people from hating the vendor?

Body:
A previous question about why people hate Microsoft was closed. This is an attempt at a somewhat more constructive question along the same general line. This one is both broader and narrower though. It's more general by being about software vendors in general, not just Microsoft. It's narrower by dealing only with management of software products.

So, what steps should be taken (and/or avoided) in managing individual software products to assure that not only the individual products, but the company as a whole is respected/liked/seen in a positive light?


问:
How to initialize all your references?
I have recently taken a project with another developer, and he has a certain way of initializing his references.

```<code>class Player
{
    private:
        Console &console;
        Armor &armor1, &armor2;
        Debugger &debugger;
        sf::RenderWindow &window;
        sf::Event &event;

   public:
       Player(Console &console, Armor &armor1, ...) : console(console), armor1(armor1), ... {};
}
</code>```

And it's perfectly fine with me, but what if we add new stuff? Our constructor is massive, and so messy, I would like to know if there are better ways of initializing your references if you have a large project, because if we keep up with this, eventually our constructor will have more lines of code than what it actually does.

答:
Your method is a good way to initialise properties in c++.

Please note the order  of properties initialise.

If you use C struct,you can use:

```<code>struct Obj
obj={.a="a",.b="b"};
</code>```

to init all properties.

I think that C is better than C++.

C++ has many traps.

Title: How to initialize all your references?

Body:
Your method is a good way to initialise properties in c++.

Please note the order  of properties initialise.

If you use C struct,you can use:

struct Obj
obj={.a="a",.b="b"};

to init all properties.

I think that C is better than C++.

C++ has many traps.


问:
Serializing an object in different ways
It is usual for me, when doing web development, to copy attributes from my model classes to the other class that will be sent to the client. Usually, with a class that accepts a model and extracts the necessary information this is sufficient (something like a adapter I suppose), but sometimes it is not that easy.

In some systems, for different reasons I need to send a different sets of attributes, and this is where simplicity seems to disappears.

With my usual approach I end up with lot's of classes very similar one from each other, just because one is for being used in one channel that requires some information and the others for channels that require very similar information. But cannot be the same sum of the two because performance or security. (When I say channels it is because it could be a serialized using json or xml, or used in other protocols, or just displayed as html by the server.)

The question is: Is there a pattern that allows for different transformations of a object (that might aggregate others objects) depending the context being used? (without too much code duplication)

Case of study: in a distributed cards game (like poker), I need to send to every user the score, the name of the players, the cards that were played, and the cards he has in his hand. But when the game ends I need to send the cards in the hands of the others players too. And in other view of the game I need to send only the score and the name of the players.

Sorry about my English, it is not my first language (and the idea I am trying to communicate seems a little complex for me).

答:
Design a class system.Every class has a method

char *toString(struct Obj *self);

You can only use sprintf to serialize your data to a string buffer.

I like to use the JSON format to serialize, because this format is easy to read, parse and combine.

Title: Serializing an object in different ways


答:
Let's take a look at the example array a:

```<code>a = {5.5, 6.5, 2.4, 3.1}
</code>```

Now we know that for any number x < 2.75 the closest number in that array will be 2.4 (at index 2). Similarly, for every number x, 2.75 < x < 4.3, the closest number in that array will be 3.1 (at index 3), and so on:

```<code>upper limit        index
2.75               2
4.3                3
6.0                0
"+infinity"        1
</code>```

Now, using this table finding the closest number in a for w[0] = 1 is easy. Just find the closest upper limit for 1, which is 2.75 and the corresponding index of array a is 2. (This can be optimized by using binary search.)

Since that index can be used only once, we must now alter the table by removing that entry:

```<code>upper limit        index
4.3                3
6.0                0
"+infinity"        1
</code>```

Next, the closest upper limit for w[1] = 2 is 3 and after removing that the table looks like this:

```<code>upper limit        index
6.0                0
"+infinity"        1
</code>```

After next step (w[2] = 6) the table has only one entry:

```<code>upper limit        index
"+infinity"        1
</code>```

In this example we didn't have to remove the last entry from the table during the process. If that needs to be done, then last entry entry of the resulting table has to be updated to have the upper limit of "+infinity".

NOTE: I have not checked whether this algorithm actually works!

Title: Sort an array in a specific order - not ascending/descending

Body:
I'm working on an algorithm that works best if the inputs are passed to it in a particular order, so I want to sort them that way. The difference is drastic enough for me to consider re-sorting the array.

Consider an array a with length n. I want to sort it the following way, and return the array of indices of a instead of the values:

I define another array w, also of length n. I want to sort such that the first element is closest to the first element of w. Then, from the rest of the elements (excluding the one already sorted), the second element is closest to the second element of w, and so on.

For example a = {5.5, 6.5, 2.4, 3.1}, w = {1, 2, 6, 5}.

2.4 is closest to 1, so output[0] = 2, the index of 2.4.

2.4 is closest to 2, but already processed, so choose 3.1, output[1] = 3.

Next come 0 and 1, in that order. 0 is chosen because it comes first, although both are equidistant.

So, output = {2, 3, 0, 1} and the sorted array would be sorted = {2.4, 3.1, 5.5, 6.5} (each index is used to find the corresponding element).

I can only think of brute-forcing this algorithm. Can there be a more efficient way to do it?

Body:
Let's take a look at the example array a:

a = {5.5, 6.5, 2.4, 3.1}

Now we know that for any number x < 2.75 the closest number in that array will be 2.4 (at index 2). Similarly, for every number x, 2.75 < x < 4.3, the closest number in that array will be 3.1 (at index 3), and so on:

upper limit        index
2.75               2
4.3                3
6.0                0
"+infinity"        1

Now, using this table finding the closest number in a for w[0] = 1 is easy. Just find the closest upper limit for 1, which is 2.75 and the corresponding index of array a is 2. (This can be optimized by using binary search.)

Since that index can be used only once, we must now alter the table by removing that entry:

upper limit        index
4.3                3
6.0                0
"+infinity"        1

Next, the closest upper limit for w[1] = 2 is 3 and after removing that the table looks like this:

upper limit        index
6.0                0
"+infinity"        1

After next step (w[2] = 6) the table has only one entry:

upper limit        index
"+infinity"        1

In this example we didn't have to remove the last entry from the table during the process. If that needs to be done, then last entry entry of the resulting table has to be updated to have the upper limit of "+infinity".

NOTE: I have not checked whether this algorithm actually works!


问:
I don't know C. And why should I learn it?
My first programming language was PHP (gasp).  After that I started working with JavaScript.  I've recently done work in C#.

I've never once looked at low or mid level languages like C.

The general consensus in the programming-community-at-large is that "a programmer who hasn't learned something like C, frankly, just can't handle programming concepts like pointers, data types, passing values by reference, etc."

I do not agree. I argue that:

Because high level languages are easily accessible, more "non-programmers" dive in and make a mess

In order to really get anything done in a high level language, one needs to understand the same similar concepts that most proponents of "learn-low-level-first" evangelize about.

Some people need to know C; those people have jobs that require them to write low to mid-level code. I'm sure C is awesome, and I'm sure there are a few bad programmers who know C.

Why the bias?  As a good, honest, hungry programmer, if I had to learn C (for some unforeseen reason), I would learn C.  Considering the multitude of languages out there, shouldn't good programmers focus on learning what advances us? Shouldn't we learn what interests us?  Should we not utilize our finite time moving forward?  Why do some programmers disagree with this?

I believe that striving for excellence in what you do is the fundamental deterministic trait between good programmers and bad ones.

Does anyone have any real world examples of how something written in a high level language—say Java, Pascal, PHP, or JavaScript—truly benefited from a prior knowledge of C? Examples would be most appreciated.

答:
C has many advantages:

C is a low level language.You can use c to develop kernel and driver.

C is fastest language.Many power software be developed by c. For
example: memcached,redis,nginx,apache,mysql etc.

C is a cross-platform language. The program developed by c can run at every platform.
Other cross-platform languages can not do this. Java,python,php etc
can not run at iOS platform.

C++ can not run at many embedded systems.


问:
Best practices for deploying multilingual API
I have a hobby project and it looks like there is need to have some API library (which in turn is a wrapper over existing http API) at least for two languages - JavaScript and Python, adding support to Perl would be nice as well.

The question is - what are the best practices for minifying the cost of supporting and developing of such multilanguage APIs? Is it better to choose one language and write just wrappers that for other ones? Or it's better do move slower but to implement thoroughly each method on each language.

答:
From my experience: If you have to write for embedded systems the core functionality is mostly C or something similar and therefor multi language support is likely to be realized with wrappers because Python, Java, Ruby and likewise are not 100% suitable for the task.

Did I get you right? You think about writing the whole functionality multiple times in different languages?
Well, if so that means an order of magnitude more effort to test, because you cannot verify the "core" and once it's done compare the wrapper results with the expected ones from core test but have to write unit tests for each and every function multiple times.

So to me it feels like wrapping is the better choice.

You could have a look into git repositories of famous open source projects, to see what they did to have it ultra accessible.

By the way:
Putting wrappers onto wrappers sounds like there might be some good use for the  adapter pattern though.


答: See, as per my point of view then as long as one can "save" files in the non-x format, things will be fine. But one can never be sure at to which version a recipient has, saving in the "non-x" format is the safest.</p>

Title: How are new file formats constructed?


问:
How would you evaluate object oriented design skills?
what kind of insights or questions would lead you to determine a person's OOAD skills.</p>

答:
Having a good knowledge of all the most popular design patterns can prove the candidate actually searched for solutions to his design problems.

Being able to discuss them and know when to apply them or not is a good indication that he understands them.

Asking him for example usages in his past experiences may also helps.


问:
Reading a specific type of input from file
I have a software that reads from a file. Each object in the software takes 7 inputs viz.

 string string string float string float int

I have an input file. It contains a number of input values. If input for one object is like:

hss cscf "serving cscf" 32.5 ims 112.134 124

(Note: when an object's variable needs multi word string, I used "....", for single word string, it is without quotes)

How can I read it using ifstream? (I searched google but didn't find.)

I tried to read entire line using getline and but again got stuck when it came to find out whether its a single word or multi word input! I thought to read a line and then search char by char. If its '"', I know its a multi word. But I stuck when it comes to an integer or float. For char, you can use

if(line[i]>='a'&&line[i]<='z')

 but how to go ahead when integer or float is the next value?

Please give some suggestions for this.

答:
You can differentiate numbers from words by looking at the characters within them. Basically, if a word contains exclusively [0-9.], you can assume it's a number.

In the same way, if an assumed number contains only [0-9], it's an integer. Otherwise, it's a float.

Beware of edge cases:

Cultures matter. In French, for example, you don't write 19.95, but 19,95. Even worse, the number 1 582.16 can be written 1582.16, 1,582.16, 1.582,16, etc., depending on the culture.

How do you escape strings? What if a multiword string contains a quote character?

Unicode can make things difficult, since unicode characters can be normalized and decomposed.

What if, one day, you need to have a word which has only digits, but still be interpreted as a word?

Side note: couldn't you reuse an existent format, like JSON, with already written and tested parsers? See also: How are new file formats constructed?


答:
Members of reference types can only be initialized in the initializer list in constructor, because references cannot be rebound. So they have to be initialized in constructor like you wrote. It's the only way.

Which brings up two points:

Isn't the class too big?

Are they really all injected dependencies to be held by reference? A "Player" class looks more like it should own things like "Armour". That is hold it by (preferably smart) pointer and construct it itself.

Title: How to initialize all your references?

Body:
I have recently taken a project with another developer, and he has a certain way of initializing his references.

```<code>class Player
{
    private:
        Console &console;
        Armor &armor1, &armor2;
        Debugger &debugger;
        sf::RenderWindow &window;
        sf::Event &event;

   public:
       Player(Console &console, Armor &armor1, ...) : console(console), armor1(armor1), ... {};
}
</code>```

And it's perfectly fine with me, but what if we add new stuff? Our constructor is massive, and so messy, I would like to know if there are better ways of initializing your references if you have a large project, because if we keep up with this, eventually our constructor will have more lines of code than what it actually does.


问:
MVC Architecture -- How many Controllers do I need?
I have been coding for a while, but mostly scripts and simple applications. I've moved into a new role where it is all about developing Web Apps and using a proper MVC architecture, so I am desperately trying to learn about all that very quickly.

I hope this question is not too similar to "Best Practices for MVC Architecture" but as I am going through a few different tutorials, I noticed that some have multiple controllers for different things.

How many controllers does a single web app need?

I realize this would be difficult to answer without an example so I'll provide one:

Application:

User logs in.

User can do one of three things:

a)  Upload a file (stored in a mongodb database with meta data).

b)  Search for a file.

c)  Log out.

My question is a general one, but I gave the example to help out anyone trying to answer.

答:
It really depends on the web app.  In your example, one is probably sufficient.  If you were to implement a full blown ecommerce app with shipping, tax, inventory management, tiered pricing, etc., then you just might want to have a couple more.

If your controller suffers from one or more code smells (especially Large Class or God Object) then you know you're probably past the point where just one will do.


答:
For your example I would create two controllers:

Sessions Controller for Login and Logout (create and destroy session for REST like layout)

Files Controller for everything on files (index=search and create=upload)

In general a RESTful approach where you think about everything as a resource that can be displayed, created, edited and destroyed gives you a good idea how to structure things. As you can see from my examples I don't stick too close to every single verb in REST.

You would most likely need more controllers for further functionality. For example a Users Controller where users can create new accounts. And in addition to this you would need an admin interface where you can edit the resources with higher privileges. In such a case it is quite common to have nearly every controller duplicated.

A very very rough estimate to get an initial idea could be one controller for every table in your database that users can access. But this is really only a very crude measurement.

Title: MVC Architecture -- How many Controllers do I need?

Body:
I have been coding for a while, but mostly scripts and simple applications. I've moved into a new role where it is all about developing Web Apps and using a proper MVC architecture, so I am desperately trying to learn about all that very quickly.

I hope this question is not too similar to "Best Practices for MVC Architecture" but as I am going through a few different tutorials, I noticed that some have multiple controllers for different things.

How many controllers does a single web app need?

I realize this would be difficult to answer without an example so I'll provide one:

Application:

User logs in.

User can do one of three things:

a)  Upload a file (stored in a mongodb database with meta data).

b)  Search for a file.

c)  Log out.

My question is a general one, but I gave the example to help out anyone trying to answer.


答:
It really depends on your application needs and architecture of business modules.

A general rule of thumb, number of required controllers depend on a number of modules and sub-modules in the Web app.

As a complementary, it would be helpful to organize the  controllers into Areas. The concept of Areas is build into the ASP.NET MVC framework and it simplifies the organization of controllers that serve one module.

There are a number of related discussions:

MVC Architecture

ASP.NET MVC controller actions design

mvc Controller And View directories organization

What does MVC class organization look like for multiple views and controllers?


答:
I like Apple's way of doing it.

Every view is controlled by only one view controller.
  ~View Controller Programming Guide for iOS

The idea is that you should be able to easily swap out Views. IMO, by only having 1 Controller per View it makes it easier to accomplish this. But I'm sure you could have a Controller with multiple Views and still design it so you can switch Views without changing program logic.


问:
Why do some software packages have an "amd64" suffix for 64-bit systems?
When downloading various software packages, and executables for Windows, I always see two different types of executables to download. One just says ...32-bit and the other always says ...amd64. I know this has nothing to do with AMD, but it is referring to 64-bit operating systems, so why is this still a norm? Even large companies like Google and Ubuntu have packages set up like this.

Thanks for any insight!

~Carpetfizz

答:
The 64-bit extension for 80x86 processors (nowadays called just x86) was invented by AMD.

Back then Intel was betting on the Itanium line for servers and even went on record saying that "64 bits won't be needed on the desktop anytime soon".

AMD, on the other hand, was producing the successful Athlon line, which for a short while was much faster and cheaper than Xeon chips.  The 64 bit capability while retaining current software compatibility put AMD back on the map.  Intel had to quickly license the 64 bit extensions, so now it could be said that Intel chips are AMD-compatible, and not the other way around...


问:
Refactored to a fancy global variable?
I am currently refactoring an application that i built in JavaScript.

The application uses a starting hour and a total working hour count in order to construct a timetable for daily, weekly and monthly views. The starting hour and total working hour count are the same for all timetables

I considered using a pattern to initialise the Timetable and started reading up on how to proceed in doing so in Javascript as I am not too familiar with the language. My orginal initialisation function for the Timetable had the following signature:

```<code>FillTimeTable( startingTimeWeekDay, workinghourCountWeekDay );
</code>```

Problem with this method is that for a different view of the timetable I have to call the other views with the same signature again.

```<code>FillWeeklyTimeTable( startingTimeWeekDay, workinghourCountWeekDay );
FillMonthlyTimeTable( startingTimeWeekDay, workinghourCountWeekDay );
</code>```

If the working hours change I or the poor bugger maintaining my code would have to alter them at different locations within the code and due to the way I organised my code they are not placed as neatly as here. So during refactoring I considered alternatives like a global variable, Singleton or an Object.

I read about objects, private members and constructors and decided that this might be the solution after reading up on Singleton Implementations and binning the global variables.

So currently I have the following code:

```<code>function Timetable( startingTimeWeekDay, workinghourCountWeekday) {
    this.startWeekday = startingTimeWeekDay;
    this.hoursWeekday = workinghourCountWeekday;
}

Timetable.prototype.startWeekday = function() {
    return this.startWeekday;
}

Timetable.prototype.hoursWeekday = function() {
    return this.hoursWeekday;
}

var myTimetable = new Timetable( 6, 8 );
</code>```

Everything is working fine so far, but myTimetable just seems  like a really fancy way of declaring a global variable to me.

Is this the case?

Did I just decide on the wrong strategy or is this the way to go or have I missed something essential to working with JavaScript?

答:
I suggest that you create an object to hold the work schedule information, then pass the object to your Timetable functions.

```<code>var companyXWorkSchedule = {
    "startingTimeWeekDay": 6,
    "workinghourCountWeekday": 8
};
</code>```

You don't need to create a global variable. companyXWorkSchedule could be a property on an object.

edit: added missing equals sign

Title: Refactored to a fancy global variable?

Body:
I suggest that you create an object to hold the work schedule information, then pass the object to your Timetable functions.

var companyXWorkSchedule = {
    "startingTimeWeekDay": 6,
    "workinghourCountWeekday": 8
};

You don't need to create a global variable. companyXWorkSchedule could be a property on an object.

edit: added missing equals sign


问:
Tracking changes to posts
I'm currently in the process of writing a support ticket system... Let's say it's a small forum application, or something like Uservoice.

Now I want my users to be able to edit their tickets, but still be able to see the old versions of them.

Which route should I take in terms of Database-Design?

I've thought of something like:

SupportTickets

Identifier

Author

Subject

SupportTicketContentId

SupportTicketContents

Identifier

Content

CreatedOn

Now when viewing a ticket, I'd simply query the most recent SupportTicketContent depending on the CreatedOn column...

But is there a better way? Or is there a better naming of these tables?

答:
Short Answer: Honestly, creating a new ticket tracking system from the scratch is tempting and cool! However, I would try stay away from re-inventing the wheel.

One of the good approaches would be clarifying all business requirements and look for available open-source alternatives. Here you are several alternatives to start with:

ASP.net based open source support ticket system

BugTracker.NET

Slick-ticket.com/

Ticket Desk

Title: Tracking changes to posts


问:
Safely fixing production database data
Bugs happen and sometimes data has to be fixed in production. What is the safest way to go about this from a big company standpoint? Are there tools that can help? Here are some considerations driving this requirement...

We need to log who ran the query and what they ran

Ideally we need to give the person access to only run queries against the tables of interest and only for a short time

Whatever is running the queries needs to have some smarts about it to not allow long running and locking SQL to run without explicit permission

This process needs to be DB agnostic or at least understand DB2, Oracle, and SQL Server.

We are trying to reduce the risk of ad-hoc prod fix-up queries from doing the "wrong thing" and at the same time add some security/audtis to the process. Thoughts or Ideas?

答:
There are times when you must fix data on Prod that doesn't exist on other servers. This isn't just from bugs but could be from an import of data from a file that a client sent that was incorrect or from a problem caused by someone hacking into your system. Or from a problem caused by bad data entry. If your database is large or time critical, you may not have the time to restore the latest backup and fix on dev.

Your first defense (and something no Enterprise database can afford to be without!) are audit tables.  You can use them to back out bad data changes. Further, you can write scripts to return data to the previous state and test them on other servers long before you need to revert audited data. Then the only risk is that you identified the correct records to revert.

Next all scripts to change data on production should include the following:

They should be in explicit transactions and have a TRY Catch block.

They should have a test mode that you can use to rollback the changes after you see what they would have been. You should have a select statment from before the change was made and one run after the change to ensure the change was correct. The script should make sure the number of rows processed is shown.  We have some of this pre-set up in a template which makes sure the pieces get done. Templates for changes, help save time in writing the fix too.

If there is a large amount of data to change or update, then consider writing the script to run in batches with commits for each batch.  You do not want to lock the whole system up while you fix a million records. If you have large anmounts of data to fix, make sure a dba or someone who is used to performance tuning reviews the script prior to running and run during off hours if at all possible.

Next all scripts to change anything on production are code reviewed and put into source control. All of them - without exception.

Finally devs should not run these scripts. They should be run by dbas or a configuration management group. If you have neither of those, then only people who are tech leads or higher should have the rights to run things on prod. The fewer people running things on prod, the easier it is to track down a problem. Scripts should be written so that they are simply run, no highlighting parts and running one step at a time. It is the highlighting stuff that often gets people in trouble when they forgot to highlight the where clause.

Title: Safely fixing production database data


答:
Working from Redmine and its database design you have a ticket, a journal item, and any details associated with that.

```<code> +--------------+     +----------------+   +----------------+
 | ticket       |     | journal        |   | journal_details|
 |--------------|     |----------------|   |----------------|
 | id           +-+   | id             +-+ | id             |
 | author       | +---+ ticket_id      | +-+ journal_id     |
 | subject      |     | author         |   | field          |
 | priority     |     | timestamp      |   | new_value      |
 | ...          |     | notes          |   | old_value      |
 |              |     |                |   |                |
 +--------------+     +----------------+   +----------------+
</code>```

You don't copy the entire issue each time, but rather you keep all of the 'header' and meta data information up to date in the ticket table.

Then, for updates to it (additional notes and any field changes) you create a row in the journal table.  If all you did was add notes, you just add a journal entry.  If, however, a field changed (like the priority) a journal entry row is added, and a journal_detail row for each row changed.

Say you have ticket #123 and you:

Add notes ('this is actually bar')

Change the subject from 'foo' to 'bar'

Change the priority from 'critical' to 'low'

The following things would happen:

Journal row is added with with the author as you, timestamp as now, ticket_id as 123, and the notes as 'this is actually bar'.  Lets say this row has an ID of 456.

A journal_detail row is added with jounral_id of 456, field of 'subject' new_value of 'bar', old_value of 'foo'

A journal_detail row is added with journal_id of 456, field of 'priority' new value of 'low', old value of 'critical'

Ticket is updated with subject of 'bar' and priority of 'low'

This way, if needed, one could reconstruct the past and see who did what when.  But few people want to see what it really looks like a month ago - they want fast queries and displays against current data.

Title: Tracking changes to posts

Body:
I'm currently in the process of writing a support ticket system... Let's say it's a small forum application, or something like Uservoice.

Now I want my users to be able to edit their tickets, but still be able to see the old versions of them.

Which route should I take in terms of Database-Design?

I've thought of something like:

SupportTickets

Identifier

Author

Subject

SupportTicketContentId

SupportTicketContents

Identifier

Content

CreatedOn

Now when viewing a ticket, I'd simply query the most recent SupportTicketContent depending on the CreatedOn column...

But is there a better way? Or is there a better naming of these tables?

Body:
Working from Redmine and its database design you have a ticket, a journal item, and any details associated with that.

 +--------------+     +----------------+   +----------------+
 | ticket       |     | journal        |   | journal_details|
 |--------------|     |----------------|   |----------------|
 | id           +-+   | id             +-+ | id             |
 | author       | +---+ ticket_id      | +-+ journal_id     |
 | subject      |     | author         |   | field          |
 | priority     |     | timestamp      |   | new_value      |
 | ...          |     | notes          |   | old_value      |
 |              |     |                |   |                |
 +--------------+     +----------------+   +----------------+

You don't copy the entire issue each time, but rather you keep all of the 'header' and meta data information up to date in the ticket table.

Then, for updates to it (additional notes and any field changes) you create a row in the journal table.  If all you did was add notes, you just add a journal entry.  If, however, a field changed (like the priority) a journal entry row is added, and a journal_detail row for each row changed.

Say you have ticket #123 and you:

Add notes ('this is actually bar')

Change the subject from 'foo' to 'bar'

Change the priority from 'critical' to 'low'

The following things would happen:

Journal row is added with with the author as you, timestamp as now, ticket_id as 123, and the notes as 'this is actually bar'.  Lets say this row has an ID of 456.

A journal_detail row is added with jounral_id of 456, field of 'subject' new_value of 'bar', old_value of 'foo'

A journal_detail row is added with journal_id of 456, field of 'priority' new value of 'low', old value of 'critical'

Ticket is updated with subject of 'bar' and priority of 'low'

This way, if needed, one could reconstruct the past and see who did what when.  But few people want to see what it really looks like a month ago - they want fast queries and displays against current data.


问:
MVVM ViewModel and Commands
I need a bit of help to understand the relationship between a viewmodel and a command, and the responsibility of the viewmodel.

I'll try to give an example (using Caliburn Micro).

I have a viewmodel class, a command class and a view with a Save button.

```<code>public class EditViewModel : Screen
{
    public bool CanSave
    {
        get { return IsDirty; }
    }

    public void Save()
    {
        var command = new SaveCommand(this); // command gets reference to VM
        command.Execute();
    }
}

public class SaveCommand
{
    private readonly EditViewModel _viewModel;

    public SaveCommand(EditViewModel viewModel)
    {
        _viewModel = viewModel;
    }

    public void Execute()
    {
       var work = _viewModel.Work;
       ..
       _viewModel.IsDirty = false;
    }
}
</code>```

When the user click Save. Save() method is called and spins up a command that saves the work.

Now my question is, should the command have a reference to the viewmodel?

No) The viewmodel will have to pass the work to the command, which will have to pass the save result back to the viewmodel, which will update itself.

Yes) The command needs a reference to the viewmodel and properties needs to be public set-able.

No seems like the cleanest way, but also requires extra work, when the work or result aren't a simple bool or similar.

I guess the root it all is. What is the relationship between a viewmodel and it's command and the responsibility of the viewmodel ?

Is there a strong 1:1 "friend" relationship between the view-model and it's command, where code has just been moved to another class. So there is nothing wrong with the command having direct access to the viewmodel.

Another understanding, the viewmodel is a very simple class, almost only with properties and contains little logic. So the logic should be in the command.

Or the viewmodel is pretty smart and should contain application-logic. Commands are really only needed when there are either too many in one viewmodel or they are a bit complicated otherwise the command code can stay in the viewmodel.

I'm just rambling I guess, please help me out to understand the viewmodel and what it's responsibility is?

答:
I'm going to reword what Mike Brown said.

The main point of commands is to allow easy databinding from DataContext to active controls, like buttons. So you create a command class, expose it as property and bind it to button. This button will then call Execute when pressed. This is simply because you cannot bind methods directly. And also allows you to have CanExecute in one place as what is executed.

But with Caliburn.Micro, it allows you to bind methods directly through convention. It actually creates a command internally for you. So with Caliburn.Micro, custom commands are practically unnecessary.

Title: MVVM ViewModel and Commands


答:
Most important is obviously to deliver a quality product.

Other imporant topics:

Honesty. Don't lie when the truth will come out sooner or later anyway.

Reliabilty. Adhere to deadlines.

Availability. Reply emails, pick up the phone.

Willingness to cooperate. If it means to work with your closest competitor to make what the customer needs, do it and do it professinally. No dirty tricks that hurt the customer first.

The last item on my list is probably what got MS such a bad reputation (though I think they are much better now in that respect); and it's even worse when small companies do that.


问:
How are new file formats constructed?
I've used a software suite that is installed in offices and on remote vessels. The installations communicate back and forth, and they do that by using a simple proprietary file format that looks something like this:

```<code>/SHIP:16
MILES=45213

/ORDER:22943
STATUS=OPEN
TOTAL=447.84
URGENCY=HIGH

/ORDERLINES:22943
ITEM=3544
QUANTITY=1
PRICE=299.99
ITEM=11269
QUANTITY=5
PRICE=29.57
</code>```

Recently, I've been writing a piece of software for a customer that saves information in the same kind of flat file format.

When the file is opened, the lines are iterated over, and "stuff happens" to the lines (i.e. they're inserted into a database, or whatever).

But it got to me on to thinking, how would this kind of file scale? (I like things being able to scale)

I could of course gzip it; but how does a file format evolve from being something basic like to this, to being monolithic? What typical practises are employed when making a file format for a new piece of software? How are they typically built?

Related: Is there a proper way to create a file format? and Should I encrypt files saved by my program

答:
It's not clear what "scale" means in this context, but if you're taking about the file becoming large, I'd suggest breaking it into multiple files that can be processed in parallel, and having some kind of association keyword (e.g., include 'file2') that permits multiple files to be grouped into a single unit.  Then you have the option of spawning off another thread or process to handle each file, possibly then merging all the results at the end.  If there's no way to perform any processing in parallel, then you'll never truly scale out.

It's good to think about such things, though.  The last large data files I worked with were from an engineering package, and they were an evil mishmash of fixed-field data embedded inside SGML-style markup tags...

Title: How are new file formats constructed?


问:
How to do logging in console application
I have a simple console application that will be deployed as a scheduled job. Below is its pseudo code

```<code>Main(string[] args)
{
    //get xml string from database
    Reports reports = ReportsDB.GetReport(args[0].ToString());

    //Generate xml file using xmwriter

    //post the file to sftp site
}
</code>```

I was wondering how to include logging functionality for this job. Also, will it be suffice to use a text writer to write to text file every time it is run or use libraries such as log4net

Edit

I should be able to log the execution of the job like start time, debug info, etc. that will be for my self.

答:
First, in general the answer is "the same way you'd do logging in any other application."

I would strongly recommend using something like log4net or nlog rather than rolling your own using a TextWriter for a number of reasons:

There are great, free options out there that will probably result in you writing and maintaining less code -- just making logging target a configuration option is worth the price of admission alone.

The great, free options are very performant -- logging is kind of easy until you get into "how do I log this without blocking the execution?"

The great, free options are very reliable -- logging is easy until you get into "how do I make sure this fatal exception that killed the program gets flushed to the log?"


问:
What's the best way to use requestAnimationFrame and fixed frame rates
I recently got into using the HTML5-requestAnimationFrame-API a lot on animation-heavy websites, especially after seeing the Jank Busters talk. This seems to work pretty well and really improve performance in many cases.

Yet one question still persists for me: When wanting to use an animation that is NOT entirely calculated (think spritesheets for example) you will have to aim for a fixed frame rate. Of course one could go back to use setInterval again, but maybe there are other ways to tackle this.

The two ways I could think of using requestAnimationFrame with a fixed frame rate are:

```<code>var fps = 25; //frames per second

function animate(){

   //actual drawing goes here
   setTimeout(function(){
      requestAnimationFrame(animate);
   }, 1000 / fps)

}

animate();
</code>```

or

```<code>var fps = 25; //frames per second

var lastExecution = new Date().getTime();

function animate(){

    var now = new Date().getTime();

    if ((now - lastExecution) > (1000 / fps)){
        //do actual drawing
        lastExecution = new Date().getTime();
    }

    requestAnimationFrame(animate);

}

animate();
</code>```

Personally, I'd opt for the second option (the first one feels like cheating), yet it seems to be more buggy in certain situations.

Is this approach really worth it (especially at low frame rates like 12.5)? Are there things to be improved? Is there another way to tackle this?

答:
Your animation should be calculated even if that calculation is entirely a function of time. And at any given time you should be able to draw() an [animated] image and know that you're getting the right frame. You want something like this, but not necessarily this:

```<code>// whatever your "attributes" looks like, the point is you've given enough
// information to the constructor to find ordered frames in the image and know
// the framerate
function SpriteAnimation(image, attributes) {

  // you probably want a SpriteFrame "class" to populate here, based on whatever
  // existing code you use to extract frames from the sprite
  this.frames = [ SpriteFrame, SpriteFrame, ... ];
                         // ... getFramesFromImageAndAttributes(image, attributes)

  // if the animation is running, this is the time it started
  this.startTime = 0;

  // whatever your framerate is ...
  this.fps = 25;         // getFPSFromAttributes(frame_attributes)

  // whether the animation loops infinitely
  this.loop = true;      // getLoopFlagFromAttributes(frame_attributes)

  // for canceling the animationframe request, if necessary
  this.animationFrameRequestId = null;

  // draw whichever frame should be visible *right now*
  this.draw = function() {

    // unconditionally show the first frame if the animation isn't running
    if (this.startTime == 0) {
      this.frames[0].draw();
      return;
    }

    // there may be a better and more accurate way to compute this ...
    var frame_duration = 1000 / this.fps;
    var now = (new Date()).getTime();
    var elapsed_time = now - this.startTime;
    var visible_frame = Math.floor(elapsed_time / frame_duration);

    if (visible_frame_number > frames.length) {
      if (!this.loop) {
        // we're past the end of the animation and we're not looping.
        // stop the animation.
        this.startTime = 0;
        visible_frame = 0;
      }
    }

    this.frames[visible_frame % frames.length].draw();

    if (this.startTime != 0) {
      var _t = this;
      requestAnimationFrame(_t.draw);
    }

  }

  this.animate = function() {
    this.startTime = (new Date()).getTime();
    var _t = this;
    requestAnimationFrame(_t.draw);
  }

  this.stop = function() {
    this.startTime = 0;
    if (this.animationFrameRequestId) {
      cancelAnimationFrame(this.animationFrameRequestId);
    }
  }

}

var a = new SpriteAnimation("/path/to/image.jpeg", {
  fps: 25,
  frame_width: 100,
  frame_height: 100,
  image_width: 1000,
  image_height: 10000
});
a.animate();
</code>```

... Or whatever.

Body:
Your animation should be calculated even if that calculation is entirely a function of time. And at any given time you should be able to draw() an [animated] image and know that you're getting the right frame. You want something like this, but not necessarily this:

// whatever your "attributes" looks like, the point is you've given enough
// information to the constructor to find ordered frames in the image and know
// the framerate
function SpriteAnimation(image, attributes) {

  // you probably want a SpriteFrame "class" to populate here, based on whatever
  // existing code you use to extract frames from the sprite
  this.frames = [ SpriteFrame, SpriteFrame, ... ];
                         // ... getFramesFromImageAndAttributes(image, attributes)

  // if the animation is running, this is the time it started
  this.startTime = 0;

  // whatever your framerate is ...
  this.fps = 25;         // getFPSFromAttributes(frame_attributes)

  // whether the animation loops infinitely
  this.loop = true;      // getLoopFlagFromAttributes(frame_attributes)

  // for canceling the animationframe request, if necessary
  this.animationFrameRequestId = null;

  // draw whichever frame should be visible *right now*
  this.draw = function() {

    // unconditionally show the first frame if the animation isn't running
    if (this.startTime == 0) {
      this.frames[0].draw();
      return;
    }

    // there may be a better and more accurate way to compute this ...
    var frame_duration = 1000 / this.fps;
    var now = (new Date()).getTime();
    var elapsed_time = now - this.startTime;
    var visible_frame = Math.floor(elapsed_time / frame_duration);

    if (visible_frame_number > frames.length) {
      if (!this.loop) {
        // we're past the end of the animation and we're not looping.
        // stop the animation.
        this.startTime = 0;
        visible_frame = 0;
      }
    }

    this.frames[visible_frame % frames.length].draw();

    if (this.startTime != 0) {
      var _t = this;
      requestAnimationFrame(_t.draw);
    }

  }

  this.animate = function() {
    this.startTime = (new Date()).getTime();
    var _t = this;
    requestAnimationFrame(_t.draw);
  }

  this.stop = function() {
    this.startTime = 0;
    if (this.animationFrameRequestId) {
      cancelAnimationFrame(this.animationFrameRequestId);
    }
  }

}

var a = new SpriteAnimation("/path/to/image.jpeg", {
  fps: 25,
  frame_width: 100,
  frame_height: 100,
  image_width: 1000,
  image_height: 10000
});
a.animate();

... Or whatever.


答:
Short Answer: There are different approaches to enable logging in C# .NET environment. For enterprise environment it is better to use a logging frameworks like Log4Net, NLog, logger, etc..

The quickest way would be logging through a simple method Logger to a plain text file. Like in a simple example provided  below:

```<code>private static void Logger(String lines)
{
 // Write the string to a file.append mode is enabled so that the log
 // lines get appended to  test.txt than wiping content and writing the log

  using (var sw = new StreamWriter("c:\\test.txt",true))
     {
       file.WriteLine(lines);
     }
}
</code>```

You may look for more details in  MSDN.

Note:  It is strongly recommended to use a more robust approach (Logging framework + DB) if you are trying to log issues of a commercial application.

References:

Log4Net tutorial

NLog - Github

loggr

Title: How to do logging in console application

Body:
I have a simple console application that will be deployed as a scheduled job. Below is its pseudo code

```<code>Main(string[] args)
{
    //get xml string from database
    Reports reports = ReportsDB.GetReport(args[0].ToString());

    //Generate xml file using xmwriter

    //post the file to sftp site
}
</code>```

I was wondering how to include logging functionality for this job. Also, will it be suffice to use a text writer to write to text file every time it is run or use libraries such as log4net

Edit

I should be able to log the execution of the job like start time, debug info, etc. that will be for my self.

Body:
Short Answer: There are different approaches to enable logging in C# .NET environment. For enterprise environment it is better to use a logging frameworks like Log4Net, NLog, logger, etc..

The quickest way would be logging through a simple method Logger to a plain text file. Like in a simple example provided  below:

private static void Logger(String lines)
{
 // Write the string to a file.append mode is enabled so that the log
 // lines get appended to  test.txt than wiping content and writing the log

  using (var sw = new StreamWriter("c:\\test.txt",true))
     {
       file.WriteLine(lines);
     }
}

You may look for more details in  MSDN.

Note:  It is strongly recommended to use a more robust approach (Logging framework + DB) if you are trying to log issues of a commercial application.

References:

Log4Net tutorial

NLog - Github

loggr


答:
If the application — or rather the instance of the application in a particular browser while it is hosting that page — has only one sense of “starting hour” and one sense of “total working hour count” that it shares throughout itself, it's not a wrong thing to have each of those things represented by a single variable in the script. Scattering it all over the place would be worse.

This in turn means that you're either going to naturally have global variables or a unique object that holds that state. From a pattern-theoretic sense, a unique object that is injected into the consumers of the object (either by setting a property on that object or via a construction argument) is best, but for small applications there's no need to get that complex; global variables or a “well-known” global holder object can do just as well. (If the code is small, refactoring it when it grows won't be a big chore. If the code is large, you use the fancier style to start with.)

Title: Refactored to a fancy global variable?

Body:
I am currently refactoring an application that i built in JavaScript.

The application uses a starting hour and a total working hour count in order to construct a timetable for daily, weekly and monthly views. The starting hour and total working hour count are the same for all timetables

I considered using a pattern to initialise the Timetable and started reading up on how to proceed in doing so in Javascript as I am not too familiar with the language. My orginal initialisation function for the Timetable had the following signature:

```<code>FillTimeTable( startingTimeWeekDay, workinghourCountWeekDay );
</code>```

Problem with this method is that for a different view of the timetable I have to call the other views with the same signature again.

```<code>FillWeeklyTimeTable( startingTimeWeekDay, workinghourCountWeekDay );
FillMonthlyTimeTable( startingTimeWeekDay, workinghourCountWeekDay );
</code>```

If the working hours change I or the poor bugger maintaining my code would have to alter them at different locations within the code and due to the way I organised my code they are not placed as neatly as here. So during refactoring I considered alternatives like a global variable, Singleton or an Object.

I read about objects, private members and constructors and decided that this might be the solution after reading up on Singleton Implementations and binning the global variables.

So currently I have the following code:

```<code>function Timetable( startingTimeWeekDay, workinghourCountWeekday) {
    this.startWeekday = startingTimeWeekDay;
    this.hoursWeekday = workinghourCountWeekday;
}

Timetable.prototype.startWeekday = function() {
    return this.startWeekday;
}

Timetable.prototype.hoursWeekday = function() {
    return this.hoursWeekday;
}

var myTimetable = new Timetable( 6, 8 );
</code>```

Everything is working fine so far, but myTimetable just seems  like a really fancy way of declaring a global variable to me.

Is this the case?

Did I just decide on the wrong strategy or is this the way to go or have I missed something essential to working with JavaScript?


问:
Java vs C#: What should a junior programmer (just finished degree) consider when entering the programming world?
I just want to hear some pro and con's - it's obvious that there is no right answer

So would Java be a better choice for a long term career? Or should I opt for .Net since it could be the platform having all the latest advances?

I just want to hear others point of view, so please don't close this question just because it's being subjective

答:
I'm a java guy by trade, but it does look that C# is the language/platform that people are migrating to.  This is just my observation from jobs advertised, and my previous and current employers.

However, I also think (and hope) that Java will be relevant for a good few years yet.

Also, I don't think they are mutually exclusive. I'd rather work with a decent C# programmer on a Java project, than a rubbish Java guy.

Lots of knowledge and skills are transferable.

OwnerDisplayName: oneWhoNeedGuidenss


问:
Am I doing events right?
My problem is with JavaScript in the browser but I guess it could apply to any event-driven environment.

I have coded up a widget in my app. The widget allows a user to select an item using 3 different sub-widgets (table, map & gallery). The sub-widgets display the same items and a selection can be made from whichever sub-widget the user prefers to use. Whenever a selection is made by the user or set in code a "selection-changed" event is fired by the sub-widget. The main widget listens for these "selection-changed" events.

This worked fine until I started getting further on with the project and realized that I needed to adjust the selection in the other 2 widgets when the selection changes (If the user selects an item on the map, it should highlight that same item in the table and gallery). The problem is that when I set the selection in the other 2 sub-widgets they in-turn fire the "selection-changed" event and that ends up getting pretty recursive. This also happens when I need to clear the selection in all of the sub-widgets (I get 3 "selection-changed" events with the same empty data). This leads to several redundant calls being made for external resources and gives me the feeling it will lead to further problems in future.

So my question is am I doing events right? The answer is obviously 'no' because I've got myself in to a pickle so early on but I wonder how other people use events without getting in to these problems - what kind of architecture would be better in this situation?

Maybe I could have a way of setting and clearing selections in the sub-widgets that doesn't go on to fire the event but this feels like a hack and may end up conflicting with the framework I'm using to handle my views/models.

答:
My preferred solution for this recursion problem (I have it a lot) is to have each action check to see if it really did something before triggering the next action.  In this case, the first subwidget changes and notifies the superwidget, which, noting that its (the superwidget's) condition really has changed, tells the other two subwidgets to change.  Each widget that does need to change (some may already be set correctly) does so and notifies the superwidget.  However, at this point the superwidget notices that the notifications haven't changed its status, it therefore doesn't tell anybody to do anything, and the recursion stops.

Otherwise I use Dan Pichelman's two-event solution.  It's less elegant, but sometimes faster.  But I usually prefer the elegant solution anyway--it works even in really complicated situations.

Title: Am I doing events right?


问:
"Everything is a Map", am I doing this right?
I watched Stuart Sierra's talk "Thinking In Data" and took one of the ideas from it as a design principle in this game I'm making. The difference is he's working in Clojure and I'm working in JavaScript.  I see some major differences between our languages in that:

Clojure is idiomatically functional programming

Most state is immutable

I took the idea from the slide "Everything is a Map" (From 11 minutes, 6 seconds to > 29 minutes in).  Some things he says are:

Whenever you see a function that takes 2-3 arguments, you can make a case for turning it into a map and just passing a map in.  There are a lot of advantages to that:

You don't have to worry about argument order

You don't have to worry about any additional information.  If there are extra keys, that's not really our concern.  They just flow through, they don't interfere.

You don't have to define a schema

As opposed to passing in an Object there's no data hiding.  But, he makes the case that data hiding can cause problems and is overrated:

Performance

Ease of implementation

As soon as you communicate over the network or across processes, you have to have both sides agree on the data representation anyway.  That's extra work you can skip if you just work on data.

Most relevant to my question. This is 29 minutes in: "Make your functions composable". Here's the code sample he uses to explain the concept:

```<code>;; Bad
(defn complex-process []
  (let [a (get-component @global-state)
        b (subprocess-one a)
        c (subprocess-two a b)
        d (subprocess-three a b c)]
    (reset! global-state d)))

;; Good
(defn complex-process [state]
  (-> state
    subprocess-one
    subprocess-two
    subprocess-three))
</code>```

I understand the majority of programmers aren't familiar with Clojure, so I'll rewrite this in imperative style:

```<code>;; Good
def complex-process(State state)
  state = subprocess-one(state)
  state = subprocess-two(state)
  state = subprocess-three(state)
  return state
</code>```

Here are the advantages:

Easy to test

Easy to look at those functions in isolation

Easy to comment out one line of this and see what the outcome is by removing a single step

Each subprocess could add more information on to the state.  If subprocess one needs to communicate something to subprocess three, it's as simple as adding a key/value.

No boilerplate to extract the data you need out of the state just so that you can save it back in.  Just pass in the whole state and let the subprocess assign what it needs.

Now, back to my situation:  I took this lesson and applied it to my game.  That is, almost all of my high level functions take and return a gameState object.  This object contains all the data of the game.  EG: A list of badGuys, a list of menus, the loot on the ground, etc.  Here's an example of my update function:

```<code>update(gameState)
  ...
  gameState = handleUnitCollision(gameState)
  ...
  gameState = handleLoot(gameState)
  ...
</code>```

What I'm here to ask about is, have I created some abomination that perverted an idea that is only practical in a functional programming language?  JavaScript isn't idiomatically functional (though it can be written that way) and it's really challenging to write immutable data structures.  One thing that concerns me is he assumes that each of those subprocesses are pure. Why does that assumption need to be made?  It's rare that any of my functions are pure (by that, I mean they often modify the gameState.  I don't have any other complicated side effects other than that).  Do these ideas fall apart if you don't have immutable data?

I'm worried that one day I'll wake up and realize this whole design is a sham and I've really just been implementing the Big Ball Of Mud anti-pattern.

Honestly, I've been working on this code for months and it's been great.  I feel like I'm getting all the advantages he's claimed.  My code is super easy for me to reason about.  But I'm a one man team so I have the curse of knowledge.

Update

I've been coding 6+ months with this pattern. Usually by this time I forget what I've done and that's where "did I write this in a clean way?" comes into play. If I haven't, I'd really struggle. So far, I'm not struggling at all.

I understand how another set of eyes would be necessary to validate its maintainability. All I can say is I care about maintainability first and foremost. I'm always the loudest evangelist for clean code no matter where I work.

I want to reply directly to those that already have a bad personal experience with this way of coding.  I didn't know it then, but I think we're really talking about two different ways of writing code.  The way I've done it appears to be more structured than what others have experienced.  When someone has a bad personal experience with "Everything is a map" they talk about how hard it is to maintain because:

You never know the structure of the map that the function requires

Any function can mutate the input in ways you'd never expect.  You have to look all over the code base to find out how a particular key got into the map or why it disappeared.

For those with such an experience, perhaps the code base was, "Everything takes 1 of N types of maps." Mine is, "Everything takes 1 of 1 type of map". If you know the structure of that 1 type, you know the structure of everything.  Of course, that structure usually grows over time.  That's why...

There's one place to look for the reference implementation (ie: the schema). This reference implementation is code the game uses so it can't get out of date.

As for the second point, I don't add/remove keys to the map outside of the reference implementation, I just mutate what's already there. I also have a large suite of automated tests.

If this architecture eventually collapses under its own weight, I'll add a second update.  Otherwise, assume everything is going well :)

答:
The main argument that I can think of against this practice is that it's very difficult to tell what data a function actually needs.

What that means is that future programmers in the codebase will have to know how the function being called works internally - and any nested function calls - in order to call it.

The more I think about it, the more your gameState object smells like a global. If that's how it's being used, why pass it around?


问:
Unused dependencies and constructor injection
I have a class that has 3 dependencies.

WritabbleDBConnection, ReadOnlyDBConnection and a QueryFilter utility object.

I want to do constructor Injection so my class would look something like this.

```<code>class PersonDataAccessObject {

    public function __construct($dbWrite, $dbRead, $queryFilter) {
        // sets to local vars
    }

    public function A() {} // uses $dbRead

    public function B() {} // uses $dbWrite

}
</code>```

This object would most likely be instantiated in a static factory, which knows how to retrieve the DB connections.

The problem I see is every time I build this object I need to pass all 3 dependencies although possibly only one of the will be used for the operations I will need to do.

I don't like hiding my dependencies inside a service locator class, since I want to keep my dependencies explicit.

Are there any solutions for this?  Or do I have to live with unused instances?

答:
Here are the three solutions I typically evaluate on a case-by-case basis:

Use a Container or service locator. This is the fastest because you can lazy-load the dependencies and only call what is needed. However, you lose a lot of testability and your code becomes dependent on something it shouldn't care about.

Pass all dependencies in. This is more proper than the above, but you lose a bit of efficiency for the sake of more-clear programming.

Split your class so each of your methods actually require all of the dependencies. In a lot of cases, this is the most pure way of doing things, but unfortunately it can easily get into overkill mode.  Not sure if this is measurable or relevant, but I'm typically the happiest when I'm able to go this route.

I typically go with #2 or #3, unless it's absolutely necessary I need access to a container. This is sometimes okay for framework-level code, but should be avoided in your application code.


问:
How to manage pair- programming code check in user identification?
How do you identify users when a programming pair checks in code? I heard a complaint that, often a junior dev will be at the keyboard, using his/her account, but is not going to be the best person to ask questions about the code being checked in (the more senior dev is likely to have the best answer).

Is this really a problem? Seems like a programming team could think of some way to identify pairs and get the necessary information in their version control software.

I also think they're not benefiting from this process if both programmers don't know what their code does.

答:
In the worst case scenario, the Jr Dev doesn't really understand the code and tells you to ask his partner about it.  This isn't really a world ending scenario.  It does, however, suggest that you're doing pair programming wrong.  One of the benefits of pair programming is to facilitate knowledge transfer between developers - if your seniors are telling the juniors to just write code without explaining it, you've lost this benefit.

To mitigate this, you could require meaningful commit messages that explain what a particular code change did & the reasoning behind it.  If you're afraid somebody might forget or leave the company, making a note of who they paired with in the message won't hurt.


答:
Personally, I wouldn't recommend that pattern in either paradigm.  It makes it easier to write initially at the expense of making it more difficult to reason about later.

For example, try to answer the following questions about each subprocess function:

Which fields of state does it require?

Which fields does it modify?

Which fields are unchanged?

Can you safely rearrange the order of the functions?

With this pattern, you can't answer those questions without reading the entire function.

In an object oriented language, the pattern makes even less sense, because tracking state is what objects do.

Title: "Everything is a Map", am I doing this right?

Body:
I watched Stuart Sierra's talk "Thinking In Data" and took one of the ideas from it as a design principle in this game I'm making. The difference is he's working in Clojure and I'm working in JavaScript.  I see some major differences between our languages in that:

Clojure is idiomatically functional programming

Most state is immutable

I took the idea from the slide "Everything is a Map" (From 11 minutes, 6 seconds to > 29 minutes in).  Some things he says are:

Whenever you see a function that takes 2-3 arguments, you can make a case for turning it into a map and just passing a map in.  There are a lot of advantages to that:

You don't have to worry about argument order

You don't have to worry about any additional information.  If there are extra keys, that's not really our concern.  They just flow through, they don't interfere.

You don't have to define a schema

As opposed to passing in an Object there's no data hiding.  But, he makes the case that data hiding can cause problems and is overrated:

Performance

Ease of implementation

As soon as you communicate over the network or across processes, you have to have both sides agree on the data representation anyway.  That's extra work you can skip if you just work on data.

Most relevant to my question. This is 29 minutes in: "Make your functions composable". Here's the code sample he uses to explain the concept:

```<code>;; Bad
(defn complex-process []
  (let [a (get-component @global-state)
        b (subprocess-one a)
        c (subprocess-two a b)
        d (subprocess-three a b c)]
    (reset! global-state d)))

;; Good
(defn complex-process [state]
  (-> state
    subprocess-one
    subprocess-two
    subprocess-three))
</code>```

I understand the majority of programmers aren't familiar with Clojure, so I'll rewrite this in imperative style:

```<code>;; Good
def complex-process(State state)
  state = subprocess-one(state)
  state = subprocess-two(state)
  state = subprocess-three(state)
  return state
</code>```

Here are the advantages:

Easy to test

Easy to look at those functions in isolation

Easy to comment out one line of this and see what the outcome is by removing a single step

Each subprocess could add more information on to the state.  If subprocess one needs to communicate something to subprocess three, it's as simple as adding a key/value.

No boilerplate to extract the data you need out of the state just so that you can save it back in.  Just pass in the whole state and let the subprocess assign what it needs.

Now, back to my situation:  I took this lesson and applied it to my game.  That is, almost all of my high level functions take and return a gameState object.  This object contains all the data of the game.  EG: A list of badGuys, a list of menus, the loot on the ground, etc.  Here's an example of my update function:

```<code>update(gameState)
  ...
  gameState = handleUnitCollision(gameState)
  ...
  gameState = handleLoot(gameState)
  ...
</code>```

What I'm here to ask about is, have I created some abomination that perverted an idea that is only practical in a functional programming language?  JavaScript isn't idiomatically functional (though it can be written that way) and it's really challenging to write immutable data structures.  One thing that concerns me is he assumes that each of those subprocesses are pure. Why does that assumption need to be made?  It's rare that any of my functions are pure (by that, I mean they often modify the gameState.  I don't have any other complicated side effects other than that).  Do these ideas fall apart if you don't have immutable data?

I'm worried that one day I'll wake up and realize this whole design is a sham and I've really just been implementing the Big Ball Of Mud anti-pattern.

Honestly, I've been working on this code for months and it's been great.  I feel like I'm getting all the advantages he's claimed.  My code is super easy for me to reason about.  But I'm a one man team so I have the curse of knowledge.

Update

I've been coding 6+ months with this pattern. Usually by this time I forget what I've done and that's where "did I write this in a clean way?" comes into play. If I haven't, I'd really struggle. So far, I'm not struggling at all.

I understand how another set of eyes would be necessary to validate its maintainability. All I can say is I care about maintainability first and foremost. I'm always the loudest evangelist for clean code no matter where I work.

I want to reply directly to those that already have a bad personal experience with this way of coding.  I didn't know it then, but I think we're really talking about two different ways of writing code.  The way I've done it appears to be more structured than what others have experienced.  When someone has a bad personal experience with "Everything is a map" they talk about how hard it is to maintain because:

You never know the structure of the map that the function requires

Any function can mutate the input in ways you'd never expect.  You have to look all over the code base to find out how a particular key got into the map or why it disappeared.

For those with such an experience, perhaps the code base was, "Everything takes 1 of N types of maps." Mine is, "Everything takes 1 of 1 type of map". If you know the structure of that 1 type, you know the structure of everything.  Of course, that structure usually grows over time.  That's why...

There's one place to look for the reference implementation (ie: the schema). This reference implementation is code the game uses so it can't get out of date.

As for the second point, I don't add/remove keys to the map outside of the reference implementation, I just mutate what's already there. I also have a large suite of automated tests.

If this architecture eventually collapses under its own weight, I'll add a second update.  Otherwise, assume everything is going well :)


答:
Start off simple: what's OOP all about?

You could start off by asking about the basic premises of OOP: abstraction, polymorphism, inheritance and encapsulation. Good food for thought to get them warmed up.

Give them a problem

Next, present them with a problem that is likely to involve patterns. It's not necessary to name or use patterns, but their approach will likely yield some if they've got experience in the area.

Perhaps dynamic text input validation. You'd like to be able to validate the input character by character to see if it's a valid date, time or date and time in ISO8601 format. You get a copy of the input string each time a key is pressed and you can return a
boolean to indicate if the text remains good in at least one of the formats. Ask them to talk through and sketch out a design using OO design principles.

By the time you've finished chatting about

Controller (that thing that fires the change events and evaluates the responses),

Observer (the validators respond to the change events),

Strategy (each validator represents a different way of determining if the input is valid),

then you'll have a pretty good idea if they understand OOD.

Give them the same problem again, but this time ask for a different design

Now, ask them to redesign the system without using an Observer pattern (if they mentioned it) - they may choose to go for a Chain of Responsibility approach or perhaps a Command pattern. You don't really care which, you know that they have a reasonable grasp of the principles involved.

Even if they don't go for a pattern based approach, just listening to the way they attempt to break the problem down into its related functionality will yield the results you're after.

Title: How would you evaluate object oriented design skills?

Body: what kind of insights or questions would lead you to determine a person's OOAD skills.</p>


问:
Is it possible to build software that interprets video in real time?
Say you had a live video stream of a popular boardwalk that had thousands of pedestrians walk down it each day. Could software be written to count the number of people that walk by a camera and collect data on things like how many of them were wearing red clothing or how many were over 6' tall?

I'm thinking the software would be a layer between the camera and the people. But I have no idea if that is even possible. If something like this already exists, I wasn't able to find it but please share if it does.

Thanks!

答:
Absolutely this is possible.

MathWorks has a Matlab toolbox for doing the basics of recognizing people.

Noticing red clothing or height over 6'0" will require you to do some more work.

What's amazing to me is that this kind of thing can be done on a good PC these days.