问:
How bad is to have many directories where to save uploaded data instead of one?
I am using the following structure to save the images that users are uploading for their items:

Images

User_dir1

Item_dir1

Picture_file1

Picture_file2

User_dir2

Item_dir2

Picture_file3

Item_dir3

Picture_file4

Can I go on with this if I am going to have thousants of users and hundrets of items per user? Talking about performance will the Linux dedicated server have trouble in the future?

Thanks!

答:
Well, how much time does it take to create a thousand folders over the course of say a month?  I would argue not a lot.  It would take a lot of time if you were regularly removing and creating folders, but it seems to me the only files that will be changed regularly will be the picture files themselves (or at worst, the folders themselves initially as they won't exist at first, but that will diminish over time), which is the same as if you had lumped everything in a single folder to begin with.

Obviously keep an eye on space and state of defragmentation of your disk, but with a little maintenance, I wouldn't expect a lot of difficulty in your idea.


答: Unless you'll need more than 65534 folders per directory you should be okay (apparently this is the maximum for NTFS)</p>

ContentLicense: CC BY-SA 2.5

Title: How bad is to have many directories where to save uploaded data instead of one?

Body:
I am using the following structure to save the images that users are uploading for their items:

Images

User_dir1

Item_dir1

Picture_file1

Picture_file2

User_dir2

Item_dir2

Picture_file3

Item_dir3

Picture_file4

Can I go on with this if I am going to have thousants of users and hundrets of items per user? Talking about performance will the Linux dedicated server have trouble in the future?

Thanks!


答: It's most likely much better than putting all files into one large directory; some file systems do not really like having tens of thousands of files in on directory.</p>


问:
The number of years experience needed to be a contract developer
Suppose you are a programmer in your mid-20's who has had several years industrial experience working for both big tech and a few internet startups but now you'd like to try contracting in the hope you'll be able to choose more interesting and varied work and be able to have a few months off between jobs to focus on things like open source, travelling and developing your own startup ideas.

Now this is possibly one of those 'grass is greener' daydreams.. Even if in the workplace you manage to have the enthusiasm and skill to work equally alongside much more experienced co-workers, how realistic do you think it would be for someone with too few years of experience to appear 'specialist' or 'experienced' to compete for contracts and afford to live this lifestyle?

答:
You don't have to be specialist or experienced to get contracts as a freelance.

When I started my business as a freelance developer, I didn't have any professionnal experience in the field but small examples of websites I've built after work.

All you have to do is go for it.

NOW


答:
There are contract roles at all levels therefore for all levels and I've seen people contract with 12 months commercial experience (though that was in a good market).  That said you'll see more (and better paid) opportunities the more experience you have.  Ideally I'd suggest that you're either at or close to senior developer type experience (5 years +) but in most places it's really not impossible with less so long as the market is OK at the time.

In terms of the lifestyle though, some words of warning.

I know a lot of people who went into contracting with the intention of doing a bit of time on a bit of time off and it never worked out that way.

When things are going well the temptation is to keep working while the going is good because there might be a downturn on the way and you should make hay while the sun shines.

When things are going badly you're so nervous about being out of work that you're desperate to get back in a position.  Even if you don't need the money in a bad market contracting is a bit "you're only as good as your last role" so gaps on the CV aren't great.

You can make it work but you're going to need to be disciplined and budget for plenty of time out of work to give you the assurance that you're not going to leave yourself in trouble when it comes time to go back and can't find something immediately.

That financial security is the thing that's going to make your goal possible so it's critical to understand what your average wage over time working and not working will be rather than get carried away with what you're earning when things are good.

Title: The number of years experience needed to be a contract developer

Body:
Suppose you are a programmer in your mid-20's who has had several years industrial experience working for both big tech and a few internet startups but now you'd like to try contracting in the hope you'll be able to choose more interesting and varied work and be able to have a few months off between jobs to focus on things like open source, travelling and developing your own startup ideas.

Now this is possibly one of those 'grass is greener' daydreams.. Even if in the workplace you manage to have the enthusiasm and skill to work equally alongside much more experienced co-workers, how realistic do you think it would be for someone with too few years of experience to appear 'specialist' or 'experienced' to compete for contracts and afford to live this lifestyle?


问:
Why are cryptic short identifiers still so common in low-level programming?
There used to be very good reasons for keeping instruction / register names short. Those reasons no longer apply, but short cryptic names are still very common in low-level programming.

Why is this? Is it just because old habits are hard to break, or are there better reasons?

For example:

Atmel ATMEGA32U2 (2010?): TIFR1 (instead of TimerCounter1InterruptFlag), ICR1H (instead of InputCapture1High), DDRB (instead of DataDirectionPortB), etc.

.NET CLR instruction set (2002): bge.s (instead of branch-if-greater-or-equal.short), etc.

Aren't the longer, non-cryptic names easier to work with?

When answering and voting, please consider the following. Many of the possible explanations suggested here apply equally to high-level programming, and yet the consensus, by and large, is to use non-cryptic names consisting of a word or two (commonly understood acronyms excluded).

Also, if your main argument is about physical space on a paper diagram, please consider that this absolutely does not apply to assembly language or CIL, plus I would appreciate if you show me a diagram where terse names fit but readable ones make the diagram worse. From personal experience at a fabless semiconductor company, readable names fit just fine, and result in more readable diagrams.

What is the core thing that is different about low-level programming as opposed to high-level languages that makes the terse cryptic names desirable in low-level but not high-level programming?

答:
Summary

Initialism is a pervasive phenomenon in many technical and non-technical circles. As such it is not limited to low-level programming. For the general discussion, see the Wikipedia article on Acronym.  My answer is specific to low-level programming.

Causes of cryptic names:

Low-level instructions are strongly-typed

Need to pack a lot of type information into the name of a low-level instruction

Historically, single-character codes are favored for packing the type information.

Solutions and their drawbacks:

There are modern low-level naming schemes that are more consistent than historical ones.

LLVM

However, the need to pack a lot of type information still exists.

Thus, cryptic abbreviations can still be found everywhere.

Improved line-to-line readability will help a novice low-level programmer pick up the language faster, but will not help with comprehending large pieces of low-level code.

Full answer

(A) Longer names are possible. For example, the names of C++ SSE2
    intrinsics average 12 characters compared to the 7 characters
    in the assembly mnemonic.
    http://msdn.microsoft.com/en-us/library/c8c5hx3b(v=vs.80).aspx

(B) The question then moves on to: How long / non-cryptic does one need
    to get from low-level instructions?

(C) Now we analyze the composition of such naming schemes. The following are two naming schemes for the same low-level instruction:

Naming scheme #1:   CVTSI2SD

Naming scheme #2:   __m128d _mm_cvtsi32_sd (__m128d a, int b);

(C.1)  Low-level instructions are always strongly typed. There cannot be
       ambiguity, type inference, automatic type conversion, or
       overloading (reuse of instruction name to mean similar but non-equivalent operations).

(C.2)  Each low-level instruction must encode a lot of type informations
       into its name. Examples of information:

Architecture Family

Operation

Arguments (Inputs) and Outputs

Types (Signed Integer, Unsigned Integer, Float)

Precision (Bit Width)

(C.3)  If each piece of information is spelled out, the program will be
       more verbose.

(C.4)  The type-encoding schemes used by various vendors had long historical roots. As an example, in the x86 instruction set:

B means byte (8-bit)

W means word (16-bit)

D means dword "double-word" (32-bit)

Q means qword "quad-word" (64-bit)

DQ means dqword "double-quad-word" (128-bit)

These historical references had no modern meanings whatsoever, but still sticks around. A more consistent scheme would have put the bit-width value (8, 16, 32, 64, 128) into the name.

On the contrary, LLVM is a right step in the direction of consistency in low-level instructions:  http://llvm.org/docs/LangRef.html#functions

(D)  Regardless of instruction naming scheme, low-level programs are
     already verbose and hard to understand because they focus on the
     minute details of execution. Changing the instruction naming scheme
     will improve readability on a line-to-line level, but will not remove
     the difficulty of comprehending the operations of a large piece of
     code.

ContentLicense: CC BY-SA 3.0


问:
How to protect my php code running on a client server?
I'd like to ask how to protect my code that is running on a client server from being altered and/or copied.

It's running on Ubuntu Server with the standard Apache Php Mysql stack.

Any software needed would preferably be open-source.

I'd also like to terminate the application when there is a license problem.

Doing this using my code is possible but since it's php the client could alter the code to prevent this from happening.

答:
You have two options:-

Learn to trust your clients.

re-Factor your software in a compiled language (Java, C# will do but they can be reverse engineered with comparative ease, C,C++ are pretty much impossible to reverse engineer but are not very good for WEB applications).

You should also realize that any reasonably competent programmer could probably reproduce your system only by observing its behavior without ever looking at your code.


问:
When is Efferent / Afferent coupling good or bad
I have a software patterns exam this week and one of the topics we are to study is Efferent and Afferent coupling.

I understand a package has a high Ce (efferent coupling) if it depends on a number of other types.

For example:

```<code>class Car{
    Engine engine;
    Wheel wheel;
    Body body;
}
</code>```

This class would have a high efferent coupling because it depends on the Engine, Wheel and Body types.

Whereas the type "Wheel" would have a high Ca (afferent coupling) if several other packages depended on it (Car, Plane, Bicycle).

One of the possible questions on our exam is, when is Efferent / Afferent coupling good or bad? This seems odd to me because logically a program would need packages / classes with both high Efferent / Afferent coupling.

Does anybody have an example of when / where high efferent or afferent coupling is good / bad??

Thanks !

答:
Afferent coupling can most easily be assessed in terms of how much pain it causes/saves because of change necessity or likelihood.  For instance, take your wheel class and let's say that a lot of other modules use it to build various kinds of vehicles.  If the wheel class is extremely stable, then this afferent coupling is beneficial since vehicles need wheels and they're using a reliable one.  If, on the other hand, the wheel class is volatile in terms of maintenance, this afferent coupling is going to be a pain point as you introduce breaking changes repeatedly to lots of code.

Efferent coupling is similar in concept, but you're going to be looking at a slightly different value proposition.  If you have a car class that depends directly upon a lot of individual parts (as opposed to say "Engine" and "Chassis" only, and they consist of other sub-parts), the class probably does a lot and may thus be a maintenance bottleneck.  Changes to that class are likely to be difficult and risky because of its complexity.  On the other hand, if the efferent coupling is high, but it's actually pretty cohesive and clear, then you don't have a hierarchy of objects and relationships to worry about.

When it comes to architecture/design, what you really have to consider are pretty much endless tradeoffs and these metrics are no different.  If you want to figure out an example of something being good or bad, play the "what if" game.  Imagine an example and say "what if I wanted to do X -- how much would that suck?"  For X where the answer is "a lot," you have a disadvantage and for X where the answer is "that'd actually be really easy" you have an advantage.


问:
How to Release to the App Store as an Individual
I've written an iOS app, and I'd like to release it on to the App Store. I'm an individual so it's not being released via a company or anything, just me.

Is it typical to just release a free app under your own name? If so, what would be appropriate copyright information to submit?

答:
It is typical to release free/paid apps on AppStore as individual as you can see there are many individual submit apps in the AppStore. The verification process of registering or upgrading as organisation is long. Sometime we release app as individual and then upgrade to organisation because of this.

For the copyright, it is ok to set copyright as others in Version information in iTunes Connect,e.g., You created an account with Thomas Owen but you fill in the copyright as Owen Inc. The same could be apply in the launch screen or other information in you apps.


问:
Does Web Accessibility have something to do in server side languages?
I want to understand how web accessibility experts deals with websites if they want to confirm that those sites are compatible with accessibility guidelines. Do they have to understand any server-side language? or just HTML and CSS?

For example, if there is a company website which provides services for other sites to ensure the accessibility for them, do they have to have a look at the server side code or only the output HTML and CSS?

答:
Usually just the output. The only server-side issue I can think of now is how to ensure a site has pretty urls like, "/user/logins/all-time" instead of /index.php?item=users&lookup=logins&timeframe=all-time, which is not at the height of accessibility. (usually mod_rewrite magic in an .htaccess file, but so many other ways, too).

But, by far, the most important aspect of accessibility, IMHO, is the content; HTML markup is merely a sub-topic of that.


问:
What will be the better way to access information from another object
I have a page Object,
which has Paragraph and Image object Collections

And each paragraph has only image_id(s) that are assigned to a paragraph. All other information about image is stored in Page->Image

Now from the paragraph object I want to access the image information where paragraph has only image_id and all other information about the image is in Page->Image object.

What will be the better way to access this info?

Should I pass the page object in every paragraph constructor or something else?

I also can't change the class structure, as it is written by someone else.

答:
KISS is always the best approach:

```<code>foreach($page->paragraphs as $paragraph)
    foreach($paragraph->image_ids as $image_id)
        $image = $page->images[$image_id]
</code>```

But if you wanted something a little more special a delegate can assist in providing the "missing" functionality you require and for which php 5.3 has made things super easy by means of a little magic.

```<code><?php

class PageDelegate
{
    private $page;

    public function construct($page)
    {
        $this->page = $page;
    }

    /* The magic delegating methods __call, __set and __get */
    public  function __call($name, $args)
    {
        if (method_exists($this->page, $name))
            return call_user_func_array(array($this->page, $name), $args);
        // you may require some conversion to valid method name
        // like converting - to _ etc. this should be kept in mind.
        if (array_has_key($this->images, $name))
            return $this->images[$name]; // note how this becomes $this->page->images[$name]
        throw BadMethodCallException("Method $name does not exist");
    }
    public function __get($name)
    {
        if (property_exists($this->page, $name))
            return $this->page->{$name};
        throw InvalidArgumentException("Property $name does not exist");
    }
    public function __set($name, $value)
    {
        if (property_exists($this->page, $name))
            $this->page->{$name} = $value;
        else
            throw InvalidArgumentException("Property $name does not exist");
    }

    // And perhaps something to help out with common tasks
    public function images_in_paragraph($paragraph)
    {
        $images = array();
        foreach($paragraph->image_ids as $image_id)
            // Note how this becomes $this-page->images[$image_id];
            $images[] = $this->{$image_id}();
        // return the collection of image objects in the paragraph
        return $images;
    }
}
</code>```

Using just the 3 magic methods __call, __set and __get we are effectively delegating to all instance members of Page and you can now call for images using their image id as a method. If there are any Page functionality you want to overwrite, simply adding the function would see it being called instead of our magic __call method to do your bidding. Now it doesn't matter that you can't change their source, you can still do what you please. =)

The implementation would then look something like this perhaps

```<code>$page = new PageDelegate($page);
foreach($page->paragraphs as $paragraph)
    foreach($page->images_in_paragraph($paragraph) as $image)
        echo "<img title=\"$image->title\" src=\"$image->src\">";
</code>```

nJoy!

Body:
KISS is always the best approach:

foreach($page->paragraphs as $paragraph)
    foreach($paragraph->image_ids as $image_id)
        $image = $page->images[$image_id]

But if you wanted something a little more special a delegate can assist in providing the "missing" functionality you require and for which php 5.3 has made things super easy by means of a little magic.

<?php

class PageDelegate
{
    private $page;

    public function construct($page)
    {
        $this->page = $page;
    }

    /* The magic delegating methods __call, __set and __get */
    public  function __call($name, $args)
    {
        if (method_exists($this->page, $name))
            return call_user_func_array(array($this->page, $name), $args);
        // you may require some conversion to valid method name
        // like converting - to _ etc. this should be kept in mind.
        if (array_has_key($this->images, $name))
            return $this->images[$name]; // note how this becomes $this->page->images[$name]
        throw BadMethodCallException("Method $name does not exist");
    }
    public function __get($name)
    {
        if (property_exists($this->page, $name))
            return $this->page->{$name};
        throw InvalidArgumentException("Property $name does not exist");
    }
    public function __set($name, $value)
    {
        if (property_exists($this->page, $name))
            $this->page->{$name} = $value;
        else
            throw InvalidArgumentException("Property $name does not exist");
    }

    // And perhaps something to help out with common tasks
    public function images_in_paragraph($paragraph)
    {
        $images = array();
        foreach($paragraph->image_ids as $image_id)
            // Note how this becomes $this-page->images[$image_id];
            $images[] = $this->{$image_id}();
        // return the collection of image objects in the paragraph
        return $images;
    }
}

Using just the 3 magic methods __call, __set and __get we are effectively delegating to all instance members of Page and you can now call for images using their image id as a method. If there are any Page functionality you want to overwrite, simply adding the function would see it being called instead of our magic __call method to do your bidding. Now it doesn't matter that you can't change their source, you can still do what you please. =)

The implementation would then look something like this perhaps

$page = new PageDelegate($page);
foreach($page->paragraphs as $paragraph)
    foreach($page->images_in_paragraph($paragraph) as $image)
        echo "<img title=\"$image->title\" src=\"$image->src\">";

nJoy!


问:
OO Design related questions in technical interviews
I've been attending quite a few interviews recently and have been asked by companies to answer "design a [insert model]" questions more than a few times.

Is this normal in the industry nowadays? I've been in the software world for more than two  decades and have attended my share of interviews, but I am seeing this pattern in interviews emerge only recently.

I feel the question is very open ended. For example: I was asked to draw a class diagram to "Design a parking lot". I am not sure what level of detail the interviewer is expecting. This was in an online test where I was expected to attach a visio diagram, so I couldn't ask them what their expectations were.

Do you use these kind of questions in your interview process? Are they related to only class diagrams or do you also ask sequence, flowcharts and ERDs (ofcourse based on the nature of the position) Have they been effective in your hiring process?

* Edit for Kevin's response *

For example: A complete question could be "Design a parking lot management system that can be used to find vacant slots"

I can be done with 2 classes, ParkingLot and Slot or I could go on to add IVehicle and Vehicle and Car and Motorcycle classes. Where do I draw the line?

```<code>public class ParkingLot
{
   IVehicle Vehicle {set; get;}

   List<Slot> GetEmptySlots() { };
}

public class Vehicle : IVehicle
{
  Slot SlotNum {set; get;}
}

public class Slot
{
  int Row {set; get;}
  int Column {set; get; }
}
</code>```

答:
I find these questions rather silly.  The true answer is "what are the use cases?"  Without a use case, there is no need for any design.  For example, here is a perfectly reasonable answer to the parking lot question:

```<code>class ParkingLot {
 boolean isFull();
 void carEntered();
 void carExited();
}
</code>```

It satisfies one obvious use case.

Body:
I find these questions rather silly.  The true answer is "what are the use cases?"  Without a use case, there is no need for any design.  For example, here is a perfectly reasonable answer to the parking lot question:

class ParkingLot {
 boolean isFull();
 void carEntered();
 void carExited();
}

It satisfies one obvious use case.


问:
How does a priority_queue maintain a heap on a deque efficiently?
In the C++ STL, priority_queue (heap) can be used with any underlying container, such as a deque. How does the implementation stay O(log n) if deques don't swap an item in index a with index b in constant time?

答: You are right that it would not be possible to make an efficient heap implementation on top of a doubly linked list. However, deques aren't doubly linked lists; they are random access containers. deques are able to swap an item in index a with index b in constant time. See the SGI documentation for deques.


答:
I'm an individual that has an app on the App Store, you can of course submit it as individual (Apple has different developer accounts for companies & "solo programmers").

For sure the copyright of the material is yours, just add a simple message (not really needed, indeed) like "© 2012 John Smith" somewhere in your app to be sure.

Please also consider that anybody can copy your material and/or ideas on the App Store, lots of people clones successful apps there. If your idea is so valuable consider also to apply for a registered trademark or similar.

P.S.

Your app is free as you said, but if you're trying to get some money from that just be sure to check what taxes you have to pay in your country.

Title: How to Release to the App Store as an Individual

Body:
I've written an iOS app, and I'd like to release it on to the App Store. I'm an individual so it's not being released via a company or anything, just me.

Is it typical to just release a free app under your own name? If so, what would be appropriate copyright information to submit?


问:
While learning is it better to use other's plugins or develop my own?
As I have been learning to program, be it in my intern-ship or school, I have often come across situations where an extra piece of software is needed (from fairly basic to quite complex) and I am almost always told that I shouldn't waste my time developing a solution and use something someone else has already done.

Does it make sense to do this or should I take the time to research and develop my own? At the moment I'm doing my final project which I have 15 weeks to complete, but the tutor and my classmates tell me not to bother. I can't help but think I am letting opportunities pass me by.

答:
If you need to get a job done (and your final project probably counts as "a job" in that context) then the approach I tend to use is to write the code that is crucial to the problem at hand and use libraries where it saves me time and isn't core to the problem.

For example importing a CSV file can be a surprisingly complex problem to solve properly, if you have to deal with all the subtleties of character encoding, embedded line breaks, nested quotation marks, badly formatted data etc. It's also (usually) not something that is of special business importance, it's just "something that needs to be done".

In that case I'd find a library, use it and move on to something more important rather than waste my time reinventing the wheel.

That's not to say that it might not be interesting, or instructive, or just plain fun to do those "non-core" things yourself and you'll probably learn a lot by doing them but you have to learn to pick your battles. Prioritising what is important will help you determine what you need to write yourself, and what you can bring in from other sources.


答:
Reuse existing code if and whenever possible.

Reading and understanding other people's code is important part of learning to be a programmer.

Other people's code is a great source of idioms you can use in your own work. If you just try to solve the problem yourself, you'll no doubt get it working, and you'll get more proficient with the techniques you already know, but you are unlikely to learn new techniques. And textbooks usually limit themselves to short examples and thus limited set of idioms.

By trying to understand other people's code you'll also see what is easy to understand. The assignments you get when learning generally don't include maintenance, so you don't get to look at the code you wrote a year later to see whether you can still understand it, but in practice you'll need that rather often. So other people's code can give you some sense about what to use and what to avoid to keep the code understandable.

It is also an important skill of it's own, since when you start doing programming for living, you'll most of the time work in a team and most of the time work on application that at least in part existed before you came, so you'll have to understand lot of existing code.

Therefore I suggest using existing code, unless it contradicts the assignment, of course. And taking time to understand first how to use it properly and than also trying to understand how it works.

Title: While learning is it better to use other's plugins or develop my own?

Body:
As I have been learning to program, be it in my intern-ship or school, I have often come across situations where an extra piece of software is needed (from fairly basic to quite complex) and I am almost always told that I shouldn't waste my time developing a solution and use something someone else has already done.

Does it make sense to do this or should I take the time to research and develop my own? At the moment I'm doing my final project which I have 15 weeks to complete, but the tutor and my classmates tell me not to bother. I can't help but think I am letting opportunities pass me by.


问:
What are the advantages of a client/server architecture in webapplications as opposed to a server generated frontend application
In our company, we need to build a web interface onto an embedded Linux platform. I kind of see 2 options: You use a technology where the HTML and JavaScript is generated on the server side (Think JSP, Grails, but is is something that is using C++ and generates HTML/JavaScript) or you create a HTML5 'client' application that talks to a JSON or XML generating backend.

I have the feeling that web applications currently tend to go with the latter, but what are the advantages of doing so (The developers on the project choose the former, mainly based on the fact that they know C++ much better then HTML and Javascript)

答:
The latter has the advantage that it makes your "back end" a generic "data service" (whatever that may mean in your context).

Your HTML client is then just one of the many possible consumers of that data. Think iOS app, Andriod app, Windows 8 app, APIs, etc. -- as other consumers.


答:
Priorities. Focus on what you want to achieve and in how much time. Yes, I'ts natural to have thoughts that certain building block could have been better, if I do it myself. But keep in mind that'd take you away from primary goal and project demands.

Re-use what's available and popular. Popular available components are used, tested and contributed to, by many-many developers (probably smarter than us). You can contribute too, a lot of It can be better opportunities are there. If it doesn't exists, create and share.

Finally, don't just re-use without knowing it. If you use external code, take some time to peek inside and see how stuff works. You'd learn a lot.


答:
A growing common way of a web application is a mix of both, tending one or other side.

The first approach is more traditional, has been there for years and its well documented, (although c++ is not generally a language popular for that).

The second option is more modern, and is  present in the development blogs and forums nowadays. One of the reasons for that, is the growing need to serve the same application to other interfaces, mobile and services API.  The second approach tends towards a client richer and more responsive.

All in all, that depends of other constraints, like the team familiarity, and business case.

Some questions that can help you assess your options:

Does the team have experience in the language and platform?

Is the team willing to learn new approach and technologies?

Does the application takes advantages of being more easily programmable for other devices (iPhone, android, windows 8, etc)

Will other, internal or external app integrated with services or data availble to application?

Title: What are the advantages of a client/server architecture in webapplications as opposed to a server generated frontend application

Body:
In our company, we need to build a web interface onto an embedded Linux platform. I kind of see 2 options: You use a technology where the HTML and JavaScript is generated on the server side (Think JSP, Grails, but is is something that is using C++ and generates HTML/JavaScript) or you create a HTML5 'client' application that talks to a JSON or XML generating backend.

I have the feeling that web applications currently tend to go with the latter, but what are the advantages of doing so (The developers on the project choose the former, mainly based on the fact that they know C++ much better then HTML and Javascript)


答:
For such "intranet" applications I use the fat-client (JavaScript/HTML5-app + JSON) approach with ExtJS4.

For normal "internet" websites I would use a more "classical" approach.

The clients have to render the site anyway, so why not charging them with the whole process and just give them the data to fill in. It simplyfies the server code for generating responses (just plain JSON or XML), which saves performance. Also the since there are always more clients than servers, the whole system scales much better if more of the work gets done by clients.

The client-code gets delivered with HTTP, you can still easily send new versions to the users without any obscure update mechanism. (Just replace the HMTL/JS/CSS)

The only reason I would prefere a classical approach on normal websites, are search engines.


问:
Shared Cache - Invalidation Best Practice
I'd like to know what would be a better approach to invalidate/update cache objects.

Prerequisites

Having remote memcached server (serving as cache for multiple applications)

All servers are hosted by azure (affinity regions, same data centers)

Cache object size ranges from 200 bytes up to a 50 kilobytes

Approach 1 (store in cache asap)

Object A is created -> store in database and store in cache

Object A requested by client -> check cache for existence, otherwise fetch from database and store in cache

Object A gets updated -> store in database, store in cache

Approach 1 seems to be more straightforward. If something is created, put in the cache asap. Regardless of someone will need it.

Approach 2 (lazy cache store)

Object A is created -> store in database

Object A requested by client -> check cache for existence, otherwise fetch from database and store in cache

Object A gets updated -> store in database, delete key in cache

Approach 2 seems to be more memory-aware. In this approach only requested items go to cache.

Question 1: In mind of performance, what would be a better approach? Memory nor CPU do not count yet.

Question 2: Are my thoughts a kind of premature optimization?

Question 3: Any other thoughts? Other approaches?

答:
Is unanswerable, except to say it depends. There are a lot of factors which will determine which approach is going to be the best in your case, e.g.: Is it normal for created objects to be retrieved shortly after they are created? What's the ratio of updates to accesses?

Re. deciding you need a cache: If you're optimising without data then yes, it's technically premature optimisation. I say technically since experience/conventional wisdom may tell you you're going to need a cache of some sort. Re. deciding how the cache will best work: yes, it's definitely premature optimisation.

Optimisation often isn't about finding the best/most optimal solution. It should go as follows:

Find the bottlenecks in the system.

Find where you can make the biggest difference with the least amount of work.

Do the least amount of work!

Is it fast enough yet? If not, go to #1.

Done!

Honestly, neither of the approaches you describe sound complicated. Why not implement both and see which works best?

Step 3 in approach #2 could be changed to "Object A gets updated -> store in database, update entry in cache".


答:
Wow that's a really tough question and to be honest there is no right or wrong answer. Almost every programmer has their own way of programming and therefore learning/improving their skills. I would say there are mainly four different stages in learning how to code and when/why you have to use modules/plugins/frameworks:

If you are at the very beginning of your programming career you have to learn to write code yourself. You have to play with the language to get a feeling of what is possible and what is not and also to get a glimpse of what patterns are, where they occur and how to use them.

At a certain stage after you discovered the basics of what programming means you are ready to use existing modules/plugins/frameworks. It's a necessity to learn how to read and use other peoples' code. Learn where and how patterns were applied to code others have written. Main goal of this stage is to learn that modules/plugins/frameworks can ease your daily work but also that not every module/plugin/framework is worth using.

At the same time you are mastering the second stage you are about to enter the third one. Reproduction! You will not only use modules/plugins/frameworks, you have to understand/reproduce them in order to use them or even alter them to contribute back. Almost every time you will use other peoples' code you will extract and reproduce the details you are interested in.

Never ever fully rely on frameworks others have written. From time to time you will recognize anti-patterns or just poorly written code (not to mention errors). Even if you do not expect it almost every module/plugin/framework has errors and/or misbehavior (sometimes the documentation is not matching the actual code).

So the last stage of learning how to program and use modules/plugins/frameworks is to write them on your own. You can see it as a good exercise to do some of the things a module/plugin/framework could provide on your own. Sometimes this will help you to fully understand code others wrote.

To answer your question you have to clarify for yourself at which stage you are with your programming skills and, as it seems, what the goal of your final project is. Is it about creating a functional application than uses "as many" modules/plugins/frameworks as there are to ease your work. However if this is an educational task most often it is not about creating an application but rather learning the way to do the job. The question what your tutor expects can only be answered by him, so go and ask.

PS: Good luck.


问:
Relationship between user story, feature, and epic?
As someone who's still new to agile, I'm not sure I completely understand the relationship or difference between user story, feature, and epic.

According to this question, a feature is a collection of stories.  One of the answers suggests that a feature is actually an epic. So are features and epics considered the same thing, that is basically a collection of related user stories?

Our project manager insists that there's a hierarchical structure:

Epic -> Features -> User stories

And that basically all user stories must fall within this structure.  Therefore all user stories must fall under an umbrella feature and all features must fall under an epic.

To me, that sounds awkward.  Can someone please clarify how user stories, features, and epics are related?  Or is there an article that clearly outlines the differences?

答:
I agree like many responses that there are really no right answers since these are just terms which can be varied depending on which Agile camp you are based on and you can definitely make up your own camp as long as everyone in your team including the external stakeholders understand what they mean. It is just a way of organizing your requirement.

The answer I like is from Mike Cohn's camp and it is fairly simple.

http://www.mountaingoatsoftware.com/blog/stories-epics-and-themes

Epic is just a big Story (hierarchical)

Theme is just a group of Stories (pretty much like tag)

He actually avoids the term "Feature". I assume that it is mainly because it was a common term in the traditional waterfall world. Many Agile camp tends to use different terms to emphasize the differences.

So in your PM's definition, Feature is somewhere in the middle of the Epic-Story hierarchy.

Here is my info-graphic of this definition from my InfoQ article http://www.infoq.com/articles/visualize-big-picture-agile ;-)


问:
How to write stories for internal projects
I'm working on a project which runs as a process, on a regular basis. The results of the projects daily run are used by other projects. This brings me to question how our team writes stories.

The normal format, As a [role] I want [goal/desire] so that [reason] does not seem to apply, but at the same time I'm doubting that.

This is what we do now: The system shall execute after process ABC has finished successfully.

Should we be using the other projects (that utilize the data from our process) as the role portion of the stories? What we do now just seems too much like requirements..

答:
The key of the As-a-So-That-I-want story template is simply to remind you that you need to know WHO, WHAT and most importantly WHY of your user story. You can pretty much use any format you like as long as you can capture those elements.

For internal project, if all of your WHO is the same person for whatever reason, it might be silly to just keep writing the same thing over and over so if I were you I will just omit it.

However, the typical system-shall-do-this format mostly capture WHAT and not WHY. Make sure you do not omit that.


问:
Job hopping, is it a problem?
How would you, as someone involved in the hiring process (manager,interviewer, etc) feel about a candidate that has changed jobs every 1-2 years?

update
Thanks for all the input everybody, some really great responses, and good info in every post.  I asked it because I'm currently at my 3 job in the last 5 years and I'm feeling like my position is going nowhere (like the position should have been contract in the first place, not full-time).

My only options here seem like transition to a different team doing something I'm not really interested in or look for new work, but I'm a little afraid my recent job history is all short stints.

答:
The problem with saying "is two years OK" is that if your CV reads (roughly) two years, two years, two years, that will be read that there is a pretty good chance that you will move on after two years.

You need to look at both the average time (I'd say two years is the minimum, three to four is better) but also what the longest job on there is (ideally four or five years at least) as the employer has to think that if they treat you right you're going to stick around for a decent period.

Title: Job hopping, is it a problem?


答:
If we're talking about a school project, I generally think that most of the code should be your own. I think that productivity is not the most important think in this stage.

I'd decide for each problem individually depending on the scale of the problem and how the problem is related to your assignment.

For example when I was making a game as a school project (Breakout clone with more complicated physics) I did write the physics engine myself, because it was essential part of the assignment and I've learned something from it. However I didn't write the XML Serializer because it could be a project on its own and it isn't related to the assignment much.


问:
Is Prolog professionally useful?
I learned Prolog many years ago in University. During my professional life, I have never needed to use Prolog. Have I missed something special?

As far as I remember Prolog requires completely different mindset comparing to prominent programming languages.

Is Prolog really ever used to implement something professionally useful?

答:
Try writing a sudoku solver in your favorite language, then check how it is done in Prolog. In general any CLP problem suits nice with a declarative language like Prolog.

It is also used extensively in formal verification of hardware and software (academically and probably professionally but I don't have any references to companies).

Finally, Erlang is deeply influenced by Prolog, with fault tolerance and concurrency in mind.

Title: Is Prolog professionally useful?


答:
I'll try to give a slightly different angle to the answers already given.

My main claim, and this is what takes some getting used to, conceptually, is that in most cases writing code is not the goal. Writing code is the means to an end. In most cases, the end is to get a software product out, getting it out with good quality, and getting it out in time. If writing your own code will get in the way of that (and it will. For practically all non-trivial cases, your own code will take longer to write and will be less well tested), than use existing libraries, because writing code is not the goal.

There are, of course, always secondary goals. Learning and improving as a developer is one of them. Developing in-house expertise in a problem domain or a technology may be another. These must all be considered when deciding whether to use existing code or write new code.

If your project is writing a new tool for market trend analysis, it doesn't make sense to use existing data-analysis code, since that's where you want your designers and coders to give the edge over the competition. But it does't make sense to write your own UI controls, since that's not what your users will be choosing you for.

But if you're writing a new eCommerce platform, it makes sense to use existing components for user management, data access and payment gateways, since these are commodities, and probably not the deciding factors - but do write your own UI, since the ease of use for customers and sellers is the main advantage you can offer.

And finally, the school project. You have two goals here: the first is to learn. The second is to pass and get a good grade. These two are related, but not identical, and occasionaly even contradictory. If you spend your 15 weeks developing your own tools and plugins, you will likely not be spending them doing the actual tasks you were charged with. Always remember that it's the product requirements, not the elegance of your code, that matter to those who order the project.


问:
How to refactor "nested" view classes to avoid deep method calls?
Lets say I'm displaying a bunch of data (model) using a View class for rendering. However, a lot of the data has sub-data (models) complicated enough to require separate rendering classes.

In my design, a View class has a model which it is rendering, and has many children Views which display the sub-data. In some cases, A View, while containing a model, may not have anything to render and serves more as a wrapper for it children.

However, if you have very complex data and your sub-views have subviews,this design results in deeply nested method calls. Some methods are simply passing information to view classes who may do nothing with it except pass it to their children. This seems inefficient, so I figured there might to be a pattern or something that solves this more elegantly.

答:
Assuming you have a sufficient templating language that allows for mixing and matching your templates, you should break out each relevant piece of your model into its own template which can be used to make a composite view.

For instance, you may have a Book model, which in turn has data for Bookmarks, perhaps some Highlights, and maybe PageNotes. Now each of these should have their own template that renders the content in a meaningful way, and this should be achieved by passed in only the relevant data into the template.

Why would one want to take this approach? It allows you to separate your concerns. You model should be used to marshal your data and move it from point A to point B, and your view should simply render it for consumption.


答:
memcached manages objects with its own policy, which cached object would expire if no one accesses it or the memcached run out of memory. Therefore, your first approach is not a good idea as your object in memcached would keep being invalidated due to out-of-memory when you are creating objects.

Q1. Approach 2 would be better in terms of performance because it doesn't send object to memcached, although the performance improvement is very little.

Q2. It is hard to say. Assume you know the bottleneck and draft the approaches it would not be a premature.

Q3. There are other approach such as cache in memcached only.

Title: Shared Cache - Invalidation Best Practice

Body:
I'd like to know what would be a better approach to invalidate/update cache objects.

Prerequisites

Having remote memcached server (serving as cache for multiple applications)

All servers are hosted by azure (affinity regions, same data centers)

Cache object size ranges from 200 bytes up to a 50 kilobytes

Approach 1 (store in cache asap)

Object A is created -> store in database and store in cache

Object A requested by client -> check cache for existence, otherwise fetch from database and store in cache

Object A gets updated -> store in database, store in cache

Approach 1 seems to be more straightforward. If something is created, put in the cache asap. Regardless of someone will need it.

Approach 2 (lazy cache store)

Object A is created -> store in database

Object A requested by client -> check cache for existence, otherwise fetch from database and store in cache

Object A gets updated -> store in database, delete key in cache

Approach 2 seems to be more memory-aware. In this approach only requested items go to cache.

Question 1: In mind of performance, what would be a better approach? Memory nor CPU do not count yet.

Question 2: Are my thoughts a kind of premature optimization?

Question 3: Any other thoughts? Other approaches?


问:
Pictures from iPhone to clients FTP server - Directly (iPhone->FTP) or Cloud (iPhone->Amazon->FTP)
My clients wants to take pictures with their iPhone's and place them collectible on their server, suggested by FTP.

I can see there is two solutions:

Directly upload from the iPhone to the FTP server. My colleague can make so the get the ActiveDirectery username and password, so they do not use the same password all of them.

Upload them directly to Amazon S3, where I then have a worker which takes the image and puts it on the ftp server. I can do this easily with Python. I will use Kinvey to manage users.

Is nr. 2 overkill on short terms? Or is the downsides with creating a FTP connection on a iPhone?

My boss thinks it makes it unnecessary more complicated with that extra link. I can easily see what my boss mean, and think he is right. The problem is that I have not tried FTP'ing in Obj-C and do not know how hard or difficult it can might be. I know phonegap, which could easily upload to Amazon.

答:
As you know phonegap and python, no. 2 is not an overkill.

Working with FTP in Objective C is not that difficult, but username and password could be captured if they sent in plain-text.


问:
Why are cryptic short identifiers still so common in low-level programming?
There used to be very good reasons for keeping instruction / register names short. Those reasons no longer apply, but short cryptic names are still very common in low-level programming.

Why is this? Is it just because old habits are hard to break, or are there better reasons?

For example:

Atmel ATMEGA32U2 (2010?): TIFR1 (instead of TimerCounter1InterruptFlag), ICR1H (instead of InputCapture1High), DDRB (instead of DataDirectionPortB), etc.

.NET CLR instruction set (2002): bge.s (instead of branch-if-greater-or-equal.short), etc.

Aren't the longer, non-cryptic names easier to work with?

When answering and voting, please consider the following. Many of the possible explanations suggested here apply equally to high-level programming, and yet the consensus, by and large, is to use non-cryptic names consisting of a word or two (commonly understood acronyms excluded).

Also, if your main argument is about physical space on a paper diagram, please consider that this absolutely does not apply to assembly language or CIL, plus I would appreciate if you show me a diagram where terse names fit but readable ones make the diagram worse. From personal experience at a fabless semiconductor company, readable names fit just fine, and result in more readable diagrams.

What is the core thing that is different about low-level programming as opposed to high-level languages that makes the terse cryptic names desirable in low-level but not high-level programming?

答:
I'm going to toss my hat into this mess.

High level coding conventions and standards are not the same as low level coding standards and practices. Unfortunately, most of those are holdovers from legacy code and old thought processes.

Some, however, do serve a purpose.  Sure BranchGreaterThan would be much more readable than BGT, but there's a convention there now, it's an instruction and as such has gained some bit of traction in the last 30 years of use as a standard.  Why'd they start with it, probably some arbitrary character width limit for instructions, variables and such; why do they keep it, it's a standard.  This standard is the same as using int as an identifier, it would be more legible to use Integer in all cases, but is it necessary for anyone that's been programming more than a few weeks... no. Why? Because it's a standard practice.

Second, as I said in my comment, many of the interrupts are named INTG1 and other cryptic names, these serve a purpose as well.  In circuit diagrams it is NOT good convention to name your lines and such verbosely it clutters the diagram and hurts legibility.  All verboseness is handled in documentation.  And since all of the wiring/circuit diagrams have these short names for interrupt lines, the interrupts themselves also get the same name as to keep consistency for the embedded designer from the circuit diagram all the way up to the code to program it.

A designer has some control over this, but like any field/new language there is conventions that follow from hardware to hardware, and as such should stay similar across each assembly language.  I can look at a snippet of assembly and be able to get the gist of the code without ever using that instruction set because they stick to a convention, LDA or some relation to it is probably loading a register MV is probably moving something from somewhere to somewhere else, it isn't about what you think is nice or is a high level practice, it's a language unto itself and as such has its own standards and means that you as the designer should follow, these are often not nearly as arbitrary as they seem.

I'll leave you with this: Asking the embedded community to use verbose high level practices is like asking chemists to always write out chemical compounds.  The chemist writes them short for themselves and anyone else in the field will understand it, but it may take a new comer a little time to adjust.


答:
I think rvcoutinho's comment is in line with the correct answer. Either the page class or a 3rd class (decorator/mediator) should be responsible for providing the image to the paragraph. Any images that the paragraph requires should be passed to the paragraph.

If you don't like either of those options, I would think that passing the Image Collection to the paragraph is far preferable than passing the page class. After all, if you just think about the problem conceptually, pages contain paragraphs. Paragraphs don't contain or know about pages.

Title: What will be the better way to access information from another object

Body:
I have a page Object,
which has Paragraph and Image object Collections

And each paragraph has only image_id(s) that are assigned to a paragraph. All other information about image is stored in Page->Image

Now from the paragraph object I want to access the image information where paragraph has only image_id and all other information about the image is in Page->Image object.

What will be the better way to access this info?

Should I pass the page object in every paragraph constructor or something else?

I also can't change the class structure, as it is written by someone else.


答:
Looks to me like you're not really separating the model and the view, while being in a situation where such a separation is exactly what you need.

If "a View class has a model which it is rendering" then there's really no separation between them, you can just make one class for that. I'm not saying that there's anything inherently wrong with that, for example the Spring (Web) MVC framework has a ModelAndView class which can contain references to a (composite) model and a view. I'm just thinking that in your case it would be better if you'd externalize the relation between model and view: have your Model classes completely separated from your View classes, and then have some sort of manager that decides what View is used to display what Model at a given time.

Then make each of these as granular as needed to be able to reuse them, i.e. if you have some piece of model and a certain way to display it which is repeated as part of multiple views (but at the same time that piece of Model is also needed to be displayed differently in other views) then make Model and View classes for each of these situations, and have a manager decide with what view that model should go depending on the current context (parent view, request, etc).

Title: How to refactor "nested" view classes to avoid deep method calls?

Body:
Lets say I'm displaying a bunch of data (model) using a View class for rendering. However, a lot of the data has sub-data (models) complicated enough to require separate rendering classes.

In my design, a View class has a model which it is rendering, and has many children Views which display the sub-data. In some cases, A View, while containing a model, may not have anything to render and serves more as a wrapper for it children.

However, if you have very complex data and your sub-views have subviews,this design results in deeply nested method calls. Some methods are simply passing information to view classes who may do nothing with it except pass it to their children. This seems inefficient, so I figured there might to be a pattern or something that solves this more elegantly.


问:
How do I get feedback about whether escape analysis had any affect on my code or not?
One problem I have with compiler optimization is, that I actually never know what the compiler (or in this particular case the Jit) does with my code. So is there any possibility for me to know whether a particular compiler optimization took place or not? I just want to be sure about that some objects (math vectors) are created on the stack and not on the heap.</p>

答:
See related Q&A here which suggests you can download a debug JDK and use command line options:
-XX:+UnlockDiagnosticVMOptions -XX:+PrintEscapeAnalysis -XX:+PrintEliminateAllocations

to print out the escape analysis events as they happen.


答:
AJAX

I think your question boils down to, "Should my web application generate HTML on the client side or on the server side?"  Client-side generation communicates to the server using AJAX, although the X (XML) has generally been replaced with JSON, but most people still call it AJAX because it sounds better.  Server-side, the server just makes HTML on the server.

I have a lot of experience with XML and almost none with JSON.  Everything I know about XML makes me suggest that you use JSON if at all possible.

AJAX Pros:

Send less data over HTTP(S) so they can run faster.

The server is essentially a web service so that other people (or you) can write their own clients.  This may help when creating a mobile version of your site.  Also, many inventions become popular for reasons their creator never intended.  Services are friendlier to people finding new uses for your code.

Looks like a newer application

AJAX Cons:

Debugging JavaScript

Complexity?

The stuff you can do with JavaScript is often completely impossible for blind or handicapped people to use.

May require more code total (bigger overall storage on your embedded device)

Client/Server

All web applications use client-server architecture.  The HTTP protocol forces web applications to behave that way.  AJAX uses a work-around for that design limitation, but the basic underlying model of HTTP is still client-server.  I wouldn't get hung up on the whole thing about the best way to apply MVC to web applications.  If you have to do MVC for political reasons, look at how Ruby/Rails does it.  Actually, Rails is a great architecture to copy (or use).

Service vs. App.

A good service is almost always better than an application.  But making a good service is hard!  You may need to make the application before you can write a well-enough designed spec for a service.  Don't make your job more difficult than it needs to be.  For version 1, focus on making a great application.  Until your application is relatively stable and you are sure it meets your user's requirements, having a service probably won't do you any good anyway.  Designing the wrong service too early is a waste of time that keeps on wasting as you try to fix your service interface, and deal with the massive refactoring of both server and client code that will follow.

C/Web

Wow.  I worked in C and Assembly for 3 years before I switched to web development.  I cannot think of a worse language to write a web application in - especially from a security point of view.  Input validation and output escaping are so critical...  SANS releases a list of the most common errors every year.  Buffer overflows, injections, cross-site issues (improper output encoding)...  All of these errors are really easy to make in C or assembly.  At least a language like Java has a String which is immune to overflows and an exception handling mechanism that generally prevents off-by-one errors from allowing malicious code to access system memory.  Not to mention handling international character sets (use UTF-8 when possible).

If you need to use C for memory or firmware reasons, then that's what you have to do.  Just be careful!

Browser Support

The first step to making a web application is discovering which browsers will be used by your clients?  W3Schools and Wikipedia are both good sources of general statistics, but YMMV.

Where I work now we currently validate that our application only creates valid XHTML 1.0 transitional HTML.  We also use the specific Doctype and formatting necessary to avoid Quirks Mode in IE, which makes cross-browser HTML easier to write (see tips on my blog).  We test on the latest 3 versions of IE, plus Firefox and Chrome on Windows and Linux (Safari uses the same rendering engine as Chrome).  With that validation and testing, our application pretty much works everywhere (Windows, Mac, Linux, iPhone, Android, etc.) except the BlackBerry.

The BlackBerry has never had a real browser with JavaScript, so we don't support it.  BlackBerry users are used to not having a real web browser, so they don't complain.  Maybe that's changing?  I would try to ask a few clients what browsers they are using and make sure to test with those browsers.

Summary

All web sites are built on HTML and HTTP.  Have a good reference for these technologies at hand while you are making your application.  In the course of making an application, even with a toolkit, you will run across issues that require a basic understanding these technologies in order to solve them.

You probably also need to be comfortable with CSS, and image compression in order to make something that looks decent and responds quickly.  JavaScript, web-servers, and browsers are additional areas of knowledge that you will ultimately need.

If you build your HTML on the server-side, your code base will probably be smaller and you may not need to learn JavaScript.  The server-side model means your programmers will be writing (C?) code that generates HTML that they can look at directly before it is sent to the client.  The AJAX model means your programmers will be writing JavaScript that generates HTML.  I'm not aware of a lot of tools for validating or even viewing the HTML code generated by JavaScript within a browser, making it more difficult to program correctly.

Where I work now, we use a hybrid approach which occasionally involves Java code that generates JavaScript that generates HTML.  If you guys are new to web development, that's not the place to start.  I guess I would have to say that unless you have compelling reasons to use an AJAX model, I'd start with the older server-side-HTML-generation model and see how far it gets you.


问:
Formalizing a requirements spec written in narrative English
I have a fairly technical functionality requirements spec, expressed in English prose, produced by my project manager. It is structured as a collection of UI tabs, where the requirements for each tab are expressed as a lit of UI fields and a list of business rules for the tab.

Most business rules are for UI fields on a tab, e.g:

Must be alphanumeric, max length 20.

Must be a dropdown, with values from table x.

Is mandatory.

Is mandatory under certain conditions, e.g. another field is just populated, or has a specific value.

Then other business rules get a little more complex. The spec is for a job application, so the central business object (table) is the Applicant, and we have several other tables with one-to-many relationships with applicant, such as Degree, HighSchool, PreviousEmployer, Diploma, etc.

One such complex rule says a status field can only be assigned a certain value if a many-side record exists in at least one of the many-side tables. E.g. the Applicant has at least one HighSchool or at least one Diploma record.

I am looking for advice on how to codify these requirements into a more structured specification defined in terms of tables, fields, and relationships, especially for the conditional rules for fields and for the presence of related records. Any suggestions and advice will be most welcome, but I would be overjoyed if i could find an already defined system or structure for expressing things like this.

答:
You could formalize these requirements using Gherkin syntax, for example:

```<code>Scenario: Entering nothing into the name field
    Given I am on the main data entry tab
    And I have not entered a value into the name field
    When I click OK
    Then I should be prompted to input a value into the name field

Screnario: Name field input too small
    Given I am on the main data entry tab
    And I have entered a value into the name field that is less than 10 characters in length
    When I click OK
    Then I should be warned the name field must be at least 10 characters long
</code>```

The idea behind gherkin is that requirements (somtimes called "Given, When, Then") are split into features, and each feature is split into one or more scenarios. Each scenario is codified with preconditions (Given some context which sets up the scenario into a known state), actions (When I [the user] take some action) and assertions (Then some observable side effect or goal should be achieved).

There's a lot of information on the net about Gherkin style specs and how they help to formalize and codify requirements, improving communication and understandment* between developers and domain experts.

* yes this is a made up word :)

Body:
You could formalize these requirements using Gherkin syntax, for example:

Scenario: Entering nothing into the name field
    Given I am on the main data entry tab
    And I have not entered a value into the name field
    When I click OK
    Then I should be prompted to input a value into the name field

Screnario: Name field input too small
    Given I am on the main data entry tab
    And I have entered a value into the name field that is less than 10 characters in length
    When I click OK
    Then I should be warned the name field must be at least 10 characters long

The idea behind gherkin is that requirements (somtimes called "Given, When, Then") are split into features, and each feature is split into one or more scenarios. Each scenario is codified with preconditions (Given some context which sets up the scenario into a known state), actions (When I [the user] take some action) and assertions (Then some observable side effect or goal should be achieved).

There's a lot of information on the net about Gherkin style specs and how they help to formalize and codify requirements, improving communication and understandment* between developers and domain experts.

* yes this is a made up word :)


答:
Zipf's Law

You yourself can observe by looking at this very text that word length and frequency of usage are, in general, inversely related. Words that are used very frequently, like it, a, but, you, and and are very short, while words that are used less often like observe, comprehension, and verbosity are longer. This observed relationship between frequency and length is called Zipf's Law.

The number of instructions in the instruction set for a given microprocessor usually numbers in the dozens or hundreds. For example, the Atmel AVR instruction set appears to contain about a hundred distinct instructions (I didn't count), but many of those are variations on a common theme and have very similar mnemonics. For example, the multiplication instructions include MUL, MULS, MULSU, FMUL, FMULS, and FMULSU. You don't have to look at the list of instructions for very long before you get the general idea that instructions that start with "BR" are branches, instructions that start with "LD" are loads, etc. The same applies to variables: even complex processors provide only a limited number of places to store values: condition registers, general purpose registers, etc.

Because there are so few instructions, and because long names take longer to read, it makes sense to give them short names. By contrast, higher level languages allow programmers to create a huge number of functions, methods, classes, variables, and so on. Each of these will be used far less frequently than most assembly instructions, and longer, more descriptive names are increasingly important to give readers (and writers) enough information to understand what they are and what they do.

Additionally, instruction sets for different processors often use similar names for similar operations. Most instruction sets include operations for ADD, MUL, SUB, LD, ST, BR, NOP, and if they don't use those exact names they usually use names that are very close. Once you've learned the mnemonics for one instruction set, it doesn't take long to adapt to the instruction sets for other devices. So names that might seem "cryptic" to you are about as familiar as words like and, or, and not to programmers who are skilled in the art of low level programming. I think that most people who work at the assembly level would tell you that learning to read the code is not one of the greater challenges in low level programming.

Title: Why are cryptic short identifiers still so common in low-level programming?

Body:
There used to be very good reasons for keeping instruction / register names short. Those reasons no longer apply, but short cryptic names are still very common in low-level programming.

Why is this? Is it just because old habits are hard to break, or are there better reasons?

For example:

Atmel ATMEGA32U2 (2010?): TIFR1 (instead of TimerCounter1InterruptFlag), ICR1H (instead of InputCapture1High), DDRB (instead of DataDirectionPortB), etc.

.NET CLR instruction set (2002): bge.s (instead of branch-if-greater-or-equal.short), etc.

Aren't the longer, non-cryptic names easier to work with?

When answering and voting, please consider the following. Many of the possible explanations suggested here apply equally to high-level programming, and yet the consensus, by and large, is to use non-cryptic names consisting of a word or two (commonly understood acronyms excluded).

Also, if your main argument is about physical space on a paper diagram, please consider that this absolutely does not apply to assembly language or CIL, plus I would appreciate if you show me a diagram where terse names fit but readable ones make the diagram worse. From personal experience at a fabless semiconductor company, readable names fit just fine, and result in more readable diagrams.

What is the core thing that is different about low-level programming as opposed to high-level languages that makes the terse cryptic names desirable in low-level but not high-level programming?


问:
The number of years experience needed to be a contract developer
Suppose you are a programmer in your mid-20's who has had several years industrial experience working for both big tech and a few internet startups but now you'd like to try contracting in the hope you'll be able to choose more interesting and varied work and be able to have a few months off between jobs to focus on things like open source, travelling and developing your own startup ideas.

Now this is possibly one of those 'grass is greener' daydreams.. Even if in the workplace you manage to have the enthusiasm and skill to work equally alongside much more experienced co-workers, how realistic do you think it would be for someone with too few years of experience to appear 'specialist' or 'experienced' to compete for contracts and afford to live this lifestyle?

答: A few years of industrial experience should do. But you also need some non-technical skills, e.g. self-marketing, (business-)networking, negotiating, self-management, accounting.</p>


问:
async+await == sync?
Stumbled upon this post that talks about making async web requests.

Now simplicity aside, if in real world, all you do is make an async request and wait for it in the very next line, isn't that the same as making a sync call in the first place?

答:
No it's not the same.

Your async code block is waiting for the await call to return to continue, however the rest of your application isn't waiting and can still continue like normal.

In contrast, a synchronous call would make your entire application or thread wait until the code finished executing to continue on with anything else.

Title: async+await == sync?


答: With a traditional compiler you can usually look at the assembly language it emits and determine whether or not certain optimizations have taken place (not entirely, as multiple optimizations may wind up producing the same code, but what you're looking for is the effect, not the cause).  For JITs, not so much, unless you've got a "chatty" one that emits a log or trace message when it performs its optimizations.  I know that with some JVMs you can see whether specific methods have been JITted, but not when or why (although often the criteria the JIT uses are documented).</p>

Title: How do I get feedback about whether escape analysis had any affect on my code or not?

Body: One problem I have with compiler optimization is, that I actually never know what the compiler (or in this particular case the Jit) does with my code. So is there any possibility for me to know whether a particular compiler optimization took place or not? I just want to be sure about that some objects (math vectors) are created on the stack and not on the heap.</p>


答:
No, async + await != sync, because of continuation

From MSDN 'Asynchronous Programming with Async and Await (C# and Visual Basic)'

Async methods are intended to be non-blocking operations. An await
expression in an async method doesn’t block the current thread while
the awaited task is running. Instead, the expression signs up the rest
of the method as a continuation and returns control to the caller of
the async method.

For example async execution will not block UI thread, and Some TextBox.Text will be updated after download has finished

```<code>private async void OnButtonClick()
{
   SomeTextBox.Text = await new WebClient().DownloadStringTaskAsync("http://stackoverflow.com/");
}
</code>```

Title: async+await == sync?

Body:
Stumbled upon this post that talks about making async web requests.

Now simplicity aside, if in real world, all you do is make an async request and wait for it in the very next line, isn't that the same as making a sync call in the first place?

Body:
No, async + await != sync, because of continuation

From MSDN 'Asynchronous Programming with Async and Await (C# and Visual Basic)'

Async methods are intended to be non-blocking operations. An await
expression in an async method doesn’t block the current thread while
the awaited task is running. Instead, the expression signs up the rest
of the method as a continuation and returns control to the caller of
the async method.

For example async execution will not block UI thread, and Some TextBox.Text will be updated after download has finished

private async void OnButtonClick()
{
   SomeTextBox.Text = await new WebClient().DownloadStringTaskAsync("http://stackoverflow.com/");
}

ContentLicense: CC BY-SA 4.0


问:
How much to test in TDD?
I am newbie to TDD (writing first project following TDD practices).

I have fairly basic interface IProfiler and an implementation Profiler.

```<code>interface IProfiler
{
  bool IsBusy {get;}
  long Elapsed {get;}
}
</code>```

A Simple Test

```<code>    IProfiler profiler = default(Profiler);
    [TestInitialize]
    public void Initialize()
    {
        profiler = new Profiler();
    }

    [TestMethod]
    public void ProfilerInitializationTest()
    {
        Assert.AreEqual(false, profiler.IsBusy);
        Assert.AreEqual(true, profiler.ElapsedMilliSeconds == default(long));
    }
</code>```

The question is : As I will have more state, Number of asserts will increase. Should I keep separate Assert to test each field or should i include all here, or should I group into 3-4 similar asserts?

答: isn't TDD for Test Driven Development, where you write test to get requirement described as tests. If you are talking about same TDD then you should write enough tests to cover all your requirements and don't mix them with unit test, where you test small code unit, but not requirement (that doesn't mean you can, or should not have both, unit tests are very helpful in development).</p>

Title: How much to test in TDD?


问:
Why does PHP have interfaces?
I noticed that as of PHP5, interfaces have been added to the language. However, since PHP is so loosely typed, it seems that most of the benefits of using interfaces is lost. Why is this included in the language?</p>

答:
PHP is not loosely or strongly, but dynamically typed.

About interfaces, the first thing you should ask yourself is: what are most of the benefits of interfaces?

In OOP, interfaces are not just about types, but about behaviour as well.

Since PHP also has a type hint feature, you can use interfaces just as you would in a pure oo language, such as Java.

```<code>interface File
{
    public function getLines();
}

CSVFile implements File
{
    public function getLines()
    {}
}

XMLFile implements File
{
    public function getLines()
    {}
}

JSONFile implements File
{
    public function getLines()
    {}
}

class FileReader
{
    public function read(File $file)
    {
        foreach($file->getLines() as $line)
        {
            // do something
        }
    }
}
</code>```

With PHP interface implementation, you cal also create mocks for abstract classes using PHPUnit - and this is a hell of a feature:

```<code>public function testSomething()
{
    $mock = $this->getMockForAbstractClass('File');

    $mock->expects($this->once())
         ->method('getLines')
         ->will($this->returnValue(array()));

    // do your assertions
}
</code>```

So, basically, you can have a SOLID compatible application in PHP by using the language features, one of them being interfaces.

Title: Why does PHP have interfaces?

Body:
PHP is not loosely or strongly, but dynamically typed.

About interfaces, the first thing you should ask yourself is: what are most of the benefits of interfaces?

In OOP, interfaces are not just about types, but about behaviour as well.

Since PHP also has a type hint feature, you can use interfaces just as you would in a pure oo language, such as Java.

interface File
{
    public function getLines();
}

CSVFile implements File
{
    public function getLines()
    {}
}

XMLFile implements File
{
    public function getLines()
    {}
}

JSONFile implements File
{
    public function getLines()
    {}
}

class FileReader
{
    public function read(File $file)
    {
        foreach($file->getLines() as $line)
        {
            // do something
        }
    }
}

With PHP interface implementation, you cal also create mocks for abstract classes using PHPUnit - and this is a hell of a feature:

public function testSomething()
{
    $mock = $this->getMockForAbstractClass('File');

    $mock->expects($this->once())
         ->method('getLines')
         ->will($this->returnValue(array()));

    // do your assertions
}

So, basically, you can have a SOLID compatible application in PHP by using the language features, one of them being interfaces.


问:
What are the drawbacks of Python?
Python seems all the rage these days, and not undeservingly - for it is truly a language with which one almost enjoys being given a new problem to solve. But, as a wise man once said (calling him a wise man only because I've no idea as to who actually said it; not sure whether he was that wise at all), to really know a language one does not only know its syntax, design, etc., advantages but also its drawbacks. No language is perfect, some are just better than others.

So, what would be in your opinion, objective drawbacks of Python.

Note: I'm not asking for a language comparison here (i.e. C# is better than Python because ... yadda yadda yadda) - more of an objective (to some level) opinion which language features are badly designed, whether, what are maybe some you're missing in it and so on. If must use another language as a comparison, but only to illustrate a point which would be hard to elaborate on otherwise (i.e. for ease of understanding)

答:
My gripes about Python:

Bolted-on OOP (See @mipadi's answer for elaboration on this)

Broken implementation of lambdas

Scope issues

No persistent collections in the standard library

Poor amenability to embedded DSLs

Title: What are the drawbacks of Python?


问:
Can a common interface be defined for Cartesian and Polar coordinate data?
I'm rewriting a set of file readers that a former-colleague of mine created that read raw-point data of XYZ (Cartesian) coordinates or RTZ (Polar) coordinates. Currently the data is stored directly in the reader, making everything rely on the state of those objects. I'd like to separate the reader from the collected data it reads by creating some data objects.

Each of the coordinate systems is nearly identical from a purely data-driven point of view.

```<code>Cartesian Coordinates
  X (List of doubles)
  Y (List of doubles)
  Z (Multidimensional array of doubles at [X,Y])

Polar Coordinates
  R (List of doubles)
  T (List of doubles)
  Z (Multidimensional array of doubles at [R,T])
</code>```

I'm trying to determine if I can, in good conscience, define a common interface for both of these. The data is the same, even though what it represents is subtly different. Each has two opposing axes of a 3D coordinate system, and a table of Z values at various combinations of those axes. But an X coordinate doesn't necessarily map to R. And I'm not sure what I would call the properties on a common interface - Axis1, Axis2, and Z?

Or am I trying to consolidate something here that really needs to remain separate? Should there be a separate (albeit similar) interface for each data object representing coordinates from each system?

答:
You can convert from one coordinate to another.  So you could choose to work internally with only one representation and create methods to get either representation from your class (i.e. getX, getY, getR, and getT) along with functions like rotate.

The problem with doing that, however, is that converting between coordinate systems is relatively expensive.  If you have an application that needs to deal with polar coordinates while your class operates using Cartesian coordinates, you could easily chew up a bunch of CPU constantly converting back and forth.  For many applications, that's not a performance hit that would be acceptable.

Personally, I would tend to prefer a Coordinate type with PolarCoordinate and CartesianCoordinate subtypes.  Some operations like rotate would be more efficient when using the PolarCoordinate class while other operations like move would be more efficient when using the CartesianCoordinate class but you wouldn't incur the overhead of constantly converting between coordinate systems and your application could choose whichever representation would likely be more efficient for whatever tasks it was going to do.


问:
OO Design, how to model Tonal Harmony?
I have started to write a program in C++ 11 that would analyse chords, scales, and harmony.
The biggest problem I am having in my design phase, is that the note 'C' is a note, a type of chord (Cmaj, Cmin, C7, etc), and a type of key (the key of Cmajor, Cminor). The same issue arises with intervals (minor 3rd, major 3rd).

I am using a base class, Token, that is the base class for all 'symbols' in the program. so for example:

```<code>class Token {
public:
    typedef shared_ptr<Token> pointer_type;
    Token() {}
    virtual ~Token() {}
};

class Command : public Token {
public:
    Command() {}
    pointer_type execute();
}

class Note : public Token;

class Triad : public Token; class MajorTriad : public Triad; // CMajorTriad, etc

class Key : public Token; class MinorKey : public Key; // Natural Minor, Harmonic minor,etc

class Scale : public Token;
</code>```

As you can see, to create all the derived classes (CMajorTriad, C, CMajorScale, CMajorKey, etc) would quickly become ridiculously complex including all the other notes, as well as enharmonics. multiple inheritance would not work, ie:

```<code>class C : public Note, Triad, Key, Scale
</code>```

class C, cannot be all of these things at the same time. It is contextual, also polymorphing with this will not work (how to determine which super methods to perform? calling every super class constructors should not happen here)

Are there any design ideas or suggestions that people have to offer? I have not been able to find anything on google in regards to modelling tonal harmony from an OO perspective. There are just far too many relationships between all the concepts here.

答:
Thank you for all the suggestions, somehow I managed to miss the extra responses. So far my classes have been designed like so:

```<code>Note
enum Qualities - { DFLAT = -2, FLAT, NATURAL, SHARP, DSHARP }
char letter[1] // 1 char letter
string name // real name of note
int value // absolute value, the position on the keyboard for a real note (ie. c is always 0)
int position // relative position on keyboard, when adding sharp/flat, position is modified
Qualities quality // the quality of the note ie sharp flat
</code>```

To solve my interval and chord calculation problems, I decided to use the circular buffer, which allows me to traverse the buffer from any point, going forward, until i find the next note that matches.

To find the interpreted interval- traverse the real notes buffer, stop when the letters match (just the letter, not actual note or position) so c - g# = 5

To find the real distance- traverse another buffer of 12 integers, stop when the top note position is the same as the buffer's value at the index, again this is moving forward only. But the offset can be anywhere (ie. buffer.at(-10))

now I know both the interpreted interval, and the physical distance between the two. so interval name is already half complete.

now I am able to interpret the interval, ie. if the interval is 5, and distance is 8, then it is an augmented 5th.

So far note and interval are working as expected, now I only have to tackle the chord identifier.

Thanks again, I shall reread some of these responses and incorporate some ideas here.

Title: OO Design, how to model Tonal Harmony?

Body:
Thank you for all the suggestions, somehow I managed to miss the extra responses. So far my classes have been designed like so:

Note
enum Qualities - { DFLAT = -2, FLAT, NATURAL, SHARP, DSHARP }
char letter[1] // 1 char letter
string name // real name of note
int value // absolute value, the position on the keyboard for a real note (ie. c is always 0)
int position // relative position on keyboard, when adding sharp/flat, position is modified
Qualities quality // the quality of the note ie sharp flat

To solve my interval and chord calculation problems, I decided to use the circular buffer, which allows me to traverse the buffer from any point, going forward, until i find the next note that matches.

To find the interpreted interval- traverse the real notes buffer, stop when the letters match (just the letter, not actual note or position) so c - g# = 5

To find the real distance- traverse another buffer of 12 integers, stop when the top note position is the same as the buffer's value at the index, again this is moving forward only. But the offset can be anywhere (ie. buffer.at(-10))

now I know both the interpreted interval, and the physical distance between the two. so interval name is already half complete.

now I am able to interpret the interval, ie. if the interval is 5, and distance is 8, then it is an augmented 5th.

So far note and interval are working as expected, now I only have to tackle the chord identifier.

Thanks again, I shall reread some of these responses and incorporate some ideas here.


问:
Is this an example of recursion?
I am implementing inheritance of something called Contexts. Each Context holds a link to its parent context. If that Context is the root Context, its parent is null.

In order to walk up the inheritance tree and get the data from each Context, I want to do this (in pseudocode)

```<code>private Hashtable getDataAsMap() {
    Hashtable map  =  this.parent != null  ?
                          this.parent.getDataAsMap()  :
                          new Hashtable();

    // add my data

    return map;

}
</code>```

Is this recursion? I'm calling the same method, but on a different object. Does that still count? If not, what would you call it?

答:
Yes.  This satisfies the two criteria for a recursive algorithm:

An algorithm that takes 1 or more parameters and calls itself with a simplified version of the parameter(s) and

A base case that tells the algorithm where to stop recursing.

However, this looks like an odd way to do this.  It keeps looking up the tree until finding a root node (a node with no parent), and then returns a new object that's not actually associated with any of the nodes.  The end result will be identical to saying return new Hashtable();, but slower.  Are you sure that's what you intended?

Title: Is this an example of recursion?


答:
Basically, musical notes are frequencies and musical intervals are frequency ratios.

Everything else can be built upon that.

A chord is a list of intervals. A scale is a fundamental note and a tuning system. A tuning system is also a list of intervals.

How you name them is just a cultural artefact.

Wikipedia's Music theory article is a nice starting point.

Title: OO Design, how to model Tonal Harmony?

Body:
I have started to write a program in C++ 11 that would analyse chords, scales, and harmony.
The biggest problem I am having in my design phase, is that the note 'C' is a note, a type of chord (Cmaj, Cmin, C7, etc), and a type of key (the key of Cmajor, Cminor). The same issue arises with intervals (minor 3rd, major 3rd).

I am using a base class, Token, that is the base class for all 'symbols' in the program. so for example:

```<code>class Token {
public:
    typedef shared_ptr<Token> pointer_type;
    Token() {}
    virtual ~Token() {}
};

class Command : public Token {
public:
    Command() {}
    pointer_type execute();
}

class Note : public Token;

class Triad : public Token; class MajorTriad : public Triad; // CMajorTriad, etc

class Key : public Token; class MinorKey : public Key; // Natural Minor, Harmonic minor,etc

class Scale : public Token;
</code>```

As you can see, to create all the derived classes (CMajorTriad, C, CMajorScale, CMajorKey, etc) would quickly become ridiculously complex including all the other notes, as well as enharmonics. multiple inheritance would not work, ie:

```<code>class C : public Note, Triad, Key, Scale
</code>```

class C, cannot be all of these things at the same time. It is contextual, also polymorphing with this will not work (how to determine which super methods to perform? calling every super class constructors should not happen here)

Are there any design ideas or suggestions that people have to offer? I have not been able to find anything on google in regards to modelling tonal harmony from an OO perspective. There are just far too many relationships between all the concepts here.


问:
What should every programmer know about programming?
Please, stay on technical issues, avoid behavior, cultural, career or political issues.

答: Every programmer should know how to use the debugger, and know how to use it well.


答:
Not sure how long of breaks you plan on taking, but you better look real good on paper and in the interview to explain why a quality programmer has been out of work. It happens especially in these economic times. Working on an open source project may be you best answer.

Sometimes we worry about a contract not lasting long enough. In your case you may find they want to hire you longer than you wish. Putting your limits on the length of the contract may hinder your changes of getting hired. The offer may be for 6 months, but the client will prefer it to be open-ended in case they want you to continue working. This is the luxury of hiring contract labor.

I say start looking for contract jobs. Then you'll know if you're qualified. You don't have to accept an offer if you don't like it.

Body:
Suppose you are a programmer in your mid-20's who has had several years industrial experience working for both big tech and a few internet startups but now you'd like to try contracting in the hope you'll be able to choose more interesting and varied work and be able to have a few months off between jobs to focus on things like open source, travelling and developing your own startup ideas.

Now this is possibly one of those 'grass is greener' daydreams.. Even if in the workplace you manage to have the enthusiasm and skill to work equally alongside much more experienced co-workers, how realistic do you think it would be for someone with too few years of experience to appear 'specialist' or 'experienced' to compete for contracts and afford to live this lifestyle?


问:
C++ on Windows vs Linux - common issues?
So far all my development in C++ has been targeted to Windows, however I have always had it in the back of my mind that I will someday be targeting Linux. I am aware therefore of the need to select cross-platform libraries, and to keep my code as portable as possible (or provide alternative implementations for code which isn't portable). This question therefore does not relate to issues of code compilation.

I would like to know, what are some common issues that a developer will face when targeting both Linux and Windows? In particular, but not limited to:

Best practices for handling configuration files. On Windows it seems this is fairly arbitrary - I've seen software store their configuration inside the program folder, in the user's folder (under appData), and in the registry. On Linux it seems much more heavily weighted towards dedicated configuration folders (/etc). How should I handle these differences in my code? Do I hard code the locations, or is there some system-defined function I can consult?

Same as (1) but for logging.

How do I go about keeping my project files in sync? E.g. if I update something in a Visual Studio project file, do I generally need to manually update the equivalent thing in whatever Linux environment I'm working in, or is there a commonly used method of avoiding this?

What is the best way to handle platform implementation differences in my code? Should I use #ifdefs, or should I keep the platform-specific code in separate files and have the project specify which files are included?

Anything else I haven't thought of which I should start considering / researching?

答:
Emplacement of things.  See the Filesystem Hierarchy Standard.  Quick summary for configuration: machine configuration under /etc/opt/<package>, user configuration under $HOME/.<package>.

Logging, it means different things for different people.  For a system tool, look syslog

That's the job of you VCS and shouldn't be very different from keeping several Windows machines in sync.

Find a library which provides an abstraction (starting with boost for instance)

Build such a library.

Use #ifdef for minor differences, for bigger things, see 2 if you can't find 1.

It is common to install server applications with their own user as a security measure. Look also for chroot.