问:
Should my team use some common well-regarded coding standard as a basis for its own?
The R&D team I'm in has decided to adopt a coding standard. We have only recently formed, and have too little code and common coding time of our own to base our standards/conventions document on what has developed organically in our team, and on good examples from our own code etc.

Now, every one of us has some experience from past workplaces - although none of us is at a state of saying "let's adopt this here comprehensive document I have found to be fitting for the kind of work we do here" (*). Plus, some of us (including myself) only have experience from places with no official coding standard, or writing in different languages in a different setting (high-pressure weekly-release production environment as opposed to more research-oriented development work)

So, one of the options I've been thinking about is taking a relatively well-known and well-regarded document, snipping off what we don't care about/care for, and making some modifications based on our preferences.

Is this a common practice? Do you believe this is a good idea? If so, what would be a reasonable 'baseline' coding standard (don't tell me which is best, I don't want to start a religious conflict here; just point out what would be comprehensive or 'neutral' enough to build upon.)

Notes:

We are expecting to work with C, C++, OpenCL, CUDA, Python.

We are a team of 4 people + manager, expected to grow to about 5-6 within a year or so.

In our company, teams are almost entirely autonomous and usually don't interact at all (not even by using each other's code - the work is on entirely different projects); so - no company-wide considerations to make.

Regarding tools, at the moment what we know is that we're going to be using Eclipse, so its code formatter is going to be one tool at least. Ctrl+Shift+F has long been my friend

When I write Java, I've adopted the practice of adhering as strictly as possible to Bloch's Effective Java. Now, that's not quite a coding standard, but you could call some bricks, cement and mortar for a coding standard. I was thinking of possibly including something like that as part of the 'mix' (minding that we don't do Java).

I mean coding standards in the wider sense of the word, e.g. adopting suggestions made in the answers to this P.SE question.

I've found a big list of C++ coding standards documents; maybe I should mine that our baseline.

(*) That's not quite true, but I don't want to complicate this question with too many specifics.

答:
You can't even discuss this topic without making the distinction between a coding standard and a coding style standard.

A coding standard is a set of rules defining which language mechanisms you are allowed to use, which ones you are not allowed to use, and how to use them. In other words, you define a subset of the language used, and/or a superset, if the coding standard addresses certain non-standard extensions.

A coding style standard is only concerned with cosmetic issues: where to place braces and spaces, how to name identifiers, how to place comments etc.

These two different things might be located in the same document. However, the most serious of the coding standards don't concern themselves with style - the ones I recommend below do not. Most likely because coding style is very subjective and therefore causes a lot of friction when opinions collide.

For C/C++, the coding standards with the best reputation are those of MISRA. They are primary designed for safety/mission-critical applications, but since the key to making programs safer is to remove and avoid bugs, the MISRA standards apply to any programming branch where bugs are not desired.

The standards from CERT are also fairly well-known and more biased towards desktop programming and software security (rather than safety). CERT have standards for C, C++, Java and Perl, and the standards are free of charge.

I would start by looking at MISRA and CERT, rather than some random garage standard found on the web.


答:
Using an existing standard as a basis for your own has several advantages.  Your code will probably be more similar to external code, making it easier to read/integrate code.  Further, if you pick a good standard, it will have been examined by experts who have had good reasons for deciding on their particular rules.  As long as nobody on your team is particularly tied to a standard, there is little reason not to use an existing standard as a basis for your own.

If you're not sure which coding standards to use, there are some obvious ideal first choices.  In no particular order:

1. Whichever standard is already supported by your IDE. This is probably configurable.

2. Whichever standard is used/recommended by the author of your compiler.

3. Whichever standard is used/recommended by the author of your primary framework (if one exists).

4. Whichever standard is used/recommended by the author(s)/designer(s) of your programming language.

5. Whichever standard is used/recommended by a very large company.

I recommend someone with technical expertise read over whichever standard you are using as a basis for your own standard.  A good standard will often have a justification for each rule, which will help you in modifying the standard to best fit your needs.

ContentLicense: CC BY-SA 3.0

Title: Should my team use some common well-regarded coding standard as a basis for its own?

Body:
The R&D team I'm in has decided to adopt a coding standard. We have only recently formed, and have too little code and common coding time of our own to base our standards/conventions document on what has developed organically in our team, and on good examples from our own code etc.

Now, every one of us has some experience from past workplaces - although none of us is at a state of saying "let's adopt this here comprehensive document I have found to be fitting for the kind of work we do here" (*). Plus, some of us (including myself) only have experience from places with no official coding standard, or writing in different languages in a different setting (high-pressure weekly-release production environment as opposed to more research-oriented development work)

So, one of the options I've been thinking about is taking a relatively well-known and well-regarded document, snipping off what we don't care about/care for, and making some modifications based on our preferences.

Is this a common practice? Do you believe this is a good idea? If so, what would be a reasonable 'baseline' coding standard (don't tell me which is best, I don't want to start a religious conflict here; just point out what would be comprehensive or 'neutral' enough to build upon.)

Notes:

We are expecting to work with C, C++, OpenCL, CUDA, Python.

We are a team of 4 people + manager, expected to grow to about 5-6 within a year or so.

In our company, teams are almost entirely autonomous and usually don't interact at all (not even by using each other's code - the work is on entirely different projects); so - no company-wide considerations to make.

Regarding tools, at the moment what we know is that we're going to be using Eclipse, so its code formatter is going to be one tool at least. Ctrl+Shift+F has long been my friend

When I write Java, I've adopted the practice of adhering as strictly as possible to Bloch's Effective Java. Now, that's not quite a coding standard, but you could call some bricks, cement and mortar for a coding standard. I was thinking of possibly including something like that as part of the 'mix' (minding that we don't do Java).

I mean coding standards in the wider sense of the word, e.g. adopting suggestions made in the answers to this P.SE question.

I've found a big list of C++ coding standards documents; maybe I should mine that our baseline.

(*) That's not quite true, but I don't want to complicate this question with too many specifics.


问:
Why would I ever use delegates if I'm not doing events?
I am trying to learn how to do events in C#, and according to the MSDN Events tutorial,

Events are declared using delegates. If you have not yet studied the Delegates Tutorial, you should do so before continuing

so now I'm trying to understand Delegates first, and failing horribly. What are they for? What problem are you trying to solve where you delegate something?

I THINK they're for passing methods into other methods but what is the point of that? Why not just have a method that does whatever you're doing in the first place?

答:
Delegates are similar to interfaces. You are simply defining a contract which can be fulfilled by whatever is consuming the class that uses the delegate. The big difference between an interface and a delegate is an interface defines a contract for an entire class while a delegate defines a contract for a single method.

The best, most basic real world example of using delegates is the "Hole in the Middle" pattern. I don't need this pattern very often, but when I do, it's extremely valuable. You can accomplish this same pattern using inheritance and abstract methods, however, delegates allow you to accomplish this using composition.

```<code>public delegate void MyDelegate(string param1, string param2);

public void SomeMethod(string param1, string param2) {
    Console.WriteLine(param1);
    //do some more work
}

public void DoSomething(MyDelegate somemethod) {
    //do something here
    somemethod(param1, param2);
    //do something else here
}
</code>```

Body:
Delegates are similar to interfaces. You are simply defining a contract which can be fulfilled by whatever is consuming the class that uses the delegate. The big difference between an interface and a delegate is an interface defines a contract for an entire class while a delegate defines a contract for a single method.

The best, most basic real world example of using delegates is the "Hole in the Middle" pattern. I don't need this pattern very often, but when I do, it's extremely valuable. You can accomplish this same pattern using inheritance and abstract methods, however, delegates allow you to accomplish this using composition.

public delegate void MyDelegate(string param1, string param2);

public void SomeMethod(string param1, string param2) {
    Console.WriteLine(param1);
    //do some more work
}

public void DoSomething(MyDelegate somemethod) {
    //do something here
    somemethod(param1, param2);
    //do something else here
}


问:
Should an HTTP API always return a body?
Is there some sort of standard regarding HTTP API responses?

After reading this discourse thread I started to wonder.  We are developing our public HTTP JSON API at my work, and we do not return anything when it's not strictly needed (for example a PUT to /resource/{id} only returns 200 when OK or the corresponding 4XX or 5XX code, but no JSON body)

Should we return a generic {"success":true} like they discuss on that link above, or is it ok to return a "void" body and handle everything with http response codes?

答:
Regarding PUT,  but applies to  POST as well. The HTTP specification section 9 is a little empty on rules or even advice (SHOULD) when it comes to the scenario that you are describing. The line relevant to your question is most closely covered by:

If a new resource is created, the origin server MUST inform the user agent via the 201 (Created) response. If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate successful completion of the request.

I do not think I would lose any sleep over it, but I would ask, what do you gain by adding the chunk of JSON into the response? You've just bulked out (OK, bulked might be overkill!) the response repeating less accurately what the status code should already have told you. If your PUT resulted in a new object return 201 (as is the intention of PUT), if it updated an object return 204.

Incidentally, API aside, instead of 200, if you don't return anything use 204.

Assuming that you are developing a set of RESTful interfaces, there is no standard per se, so whatever you do, document it well,, provide examples and everything will be alright.

ContentLicense: CC BY-SA 4.0


问:
Python multithreading and utilizing modern processors - what is the downside?

CPython implementation detail: In CPython, due to the Global
  Interpreter Lock, only one thread can execute Python code at once
  (even though certain performance-oriented libraries might overcome
  this limitation). If you want your application to make better use of
  the computational resources of multi-core machines, you are advised to
  use multiprocessing. However, threading is still an appropriate model
  if you want to run multiple I/O-bound tasks simultaneously.

   -> threading

multiprocessing is a package that supports spawning processes using an
  API similar to the threading module.

   -> multiprocessing

All modern PC processors are multicore. What are the downsides to spawning new processes, instead of threads? If they are not significant enough, why does the threading module even exist?

答:
tl;dr

threads are fast, cheap and lightweight in principle, but achieving all 3 without sacrificing safety is hard work

processes are slower, costlier and heavyweight in principle, but in practice they're so much easier to use it often doesn't matter

Threads exist inside a process, sharing a common address space.

Thread pros:

it's generally cheaper (in time and memory) to create a thread than to fork a new process, because whatever book-keeping overhead your OS keeps per process (eg. page tables, file descriptor tables, process table entry) already exists and doesn't have to be copied

inter-thread communication is free in the sense that you don't have to send stuff through a socket or other kernel interface, so it is fast

Thread cons:

inter-thread communication is free in the sense that it's unregulated, so it's very easy to cause data races, deadlocks and livelocks. This means you need to carefully craft some synchronization regime for your application, which can easily eat all the notional benefits of sharing your address space: the GIL is a case in point.

because your OS probably manages resources at the process level, a fatal operation in one thread will kill the whole process

Processes are isolated from each other, with independent address spaces and OS resources.

Process cons:

it's generally more expensive to fork a new process than to create a new thread

inter-process communication (IPC) is relatively expensive, since you generally need a kernel mechanism to copy data from one process to another

Process pros:

IPC via the kernel means you have no race conditions, and there is no synchronization to design, implement, test and enforce. The simplicity is often worth more than the notional speed (and complexity) of copy-free access with threads.

because processes are isolated, one can't accidentally kill another (except by explicitly sending a signal) or damage another process' memory


问:
Hiding query strings logically?
I feel uncomfortable when using query string parameters as:

http://xyz.com/default.aspx?carId=1129&country=uk&uniqueId=98745DVF4563VVf1259

I would rather use something that should not make sense to anyone who is trying to make some sense from the URL:

?a=1129&b=uk&c=98745DVF4563VVf1259

(after all this query sting info is for my use only)

Firstly is this a good thing to do? (I mean to hide logic of you query string)

If it is, then is there a way, that internally developers can use carId, country and uniqueId in code, but externally the url uses a, b and c respectively?

So if someone goes to

?a=1129&b=uk&c=98745DVF4563VVf1259

when I do Request.QueryString["carId"]

I should get 1129.

Can this be done?

答:
It's good that you're thinking about the security of your server.

Obfuscating parameter names will only stop the most casual of attackers.

You might consider encrypting the entire parameter string, and sending the result to the server instead. This is a more complex means of security, and comes with its own set of pros and cons (programming effort, long and confusing URLs). Notably, since the encryption will be running on the end node, a determined attacker will likely be able to break it locally. But again--at higher effort.

In the end, you must make the determination about how dedicated you think the attackers will be--often determined by how valuable the prize is--and how disruptive their actions will be. Based on this, select an appropriately strong level of security.

In your example, how bad is it if someone sends a modified URL? Will they see nothing? an error message? a different result? a different result, one that was supposed to be private to someone else? can they crash your server? can they take over your server? can they hack into other users' accounts? The answer to this question will help guide you.

Title: Hiding query strings logically?


问:
When does it become overkill?
First off, I apologize cause I don't know how to make a community thread; so someone help me out please.

As a developer, across many platforms, technologies and even on an infrastructure level; I always find myself asking, when am I doing TOO much?!?

It's been a never ending learning process, since I started. One (1) thing I learned is that requirements are barely valid for an extended period of time, and as such a little foresight may go a long way.

But where is the balance, and how do you know when you're losing time, not gaining it?!

答:
For me I like the approach Kent Beck puts forward in XP (not sure if it's "his" idea or someone else's but that's where I first heard it):

It's hard enough to solve today's problems without trying to work out what tomorrow's problems are and solve them too.

Developers can spend a lot of time on solutions for requirements that don't exist, edge cases which will never occur or even genuine problems where the impact of the problem is significantly less than the cost of preventing it.

This is time that could be put into things users will really want and use, things which will give them benefits that will massively outweigh even the inconvenience that will be caused in the unlikely event that one of these things actually happens.

Beyond even this non-optimal outcome for the user, the impact on the developer of over engineering in this way tends to be over complex code that is harder to support and harder to enhance.

So for me if you know, or can be fairly certain, that something is a requirement or is going to cause a problem then address it, if not then don't.

You may have to come back and rework it when it turns out that there was a wider requirement than you originally implemented, but generally the total effort you put in across the project will still be lower because in most cases that won't happen.

ContentLicense: CC BY-SA 2.5

Title: When does it become overkill?


问:
Fields vs method arguments
I just started writing some new class and it occurred to me that I was adding a lot of method arguments that are not strictly needed. This is following a habit to avoid having state in classes that is specific to some method call, rather than being general configuration or dependencies of the class.

Doing so means that a lot of methods that could have no arguments end up with one, two or three.

I'd like to hear your opinions on what you think of this tradeoff, and how you go about deciding which approach to take in what situation?

Since code is often easier to understand than English when describing code, I created a little gist that has both variants in it: https://gist.github.com/JeroenDeDauw/6525656

答:
Don't use fields in the current case!  Two "threads" using the object at the same time will seriously confuse each other.  They don't have to be real, separate threads either (hence the quotes).  If you set up the object for one table, then call a method that uses it for another table, then try to use the original set up, you have a problem.  Stick with parameters for the moment.

What you want to do here is create a new updater class that is used in only one case.  The original class could have a method to create an instance whenever needed.  The new class would have fields.  You have the best of both worlds.  Sometimes it's simpler just to stick with the parameters, but in your example you're already getting to where a separate class would be better.

Title: Fields vs method arguments


答:
you could make some sort of intermediate class or just a method that maps your plain query string names to thier obfuscated names, like:

```<code>string ObfuscateQueryString(string myString)
{
     switch(myString)
     {
         case "CardId":
              return "a";
              break;
         case "Country":
              return "b";
              break;
     }
}
</code>```

then use it like this

```<code>Request.QueryString[Obfuscate("CardId")]
</code>```

this of course is a dumb design for the method, but you get the idea you can design a more smart one.

Title: Hiding query strings logically?

Body:
I feel uncomfortable when using query string parameters as:

http://xyz.com/default.aspx?carId=1129&country=uk&uniqueId=98745DVF4563VVf1259

I would rather use something that should not make sense to anyone who is trying to make some sense from the URL:

?a=1129&b=uk&c=98745DVF4563VVf1259

(after all this query sting info is for my use only)

Firstly is this a good thing to do? (I mean to hide logic of you query string)

If it is, then is there a way, that internally developers can use carId, country and uniqueId in code, but externally the url uses a, b and c respectively?

So if someone goes to

?a=1129&b=uk&c=98745DVF4563VVf1259

when I do Request.QueryString["carId"]

I should get 1129.

Can this be done?

Body:
you could make some sort of intermediate class or just a method that maps your plain query string names to thier obfuscated names, like:

string ObfuscateQueryString(string myString)
{
     switch(myString)
     {
         case "CardId":
              return "a";
              break;
         case "Country":
              return "b";
              break;
     }
}

then use it like this

Request.QueryString[Obfuscate("CardId")]

this of course is a dumb design for the method, but you get the idea you can design a more smart one.


答:
you could also use a method that get a hash for the query string name, then use that hash as the new query string name. this way it will be even more annoying to outsiders.

example:

```<code>string GetMD5Hash (sring myString)
{
     // here goes the MD5 hash generation code.

     return myHash;
}
</code>```

then use it like this

```<code>Request.QueryString[GetMD5Hash("CardId")]
</code>```

this way it will looks like this in the URL

?

25e262bf23ec0aebbcf81c545e1e7460 = 1129

&

e909c2d7067ea37437cf97fe11d91bd0 = uk

&

eed6e175b82da657ccbc6c2a1479c31f = 98745DVF4563VVf1259

i have broken the link into pieces to make it more clear.

Title: Hiding query strings logically?

Body:
you could also use a method that get a hash for the query string name, then use that hash as the new query string name. this way it will be even more annoying to outsiders.

example:

string GetMD5Hash (sring myString)
{
     // here goes the MD5 hash generation code.

     return myHash;
}

then use it like this

Request.QueryString[GetMD5Hash("CardId")]

this way it will looks like this in the URL

?

25e262bf23ec0aebbcf81c545e1e7460 = 1129

&

e909c2d7067ea37437cf97fe11d91bd0 = uk

&

eed6e175b82da657ccbc6c2a1479c31f = 98745DVF4563VVf1259

i have broken the link into pieces to make it more clear.


答:
You can obfuscate the query string by having a simple one-to-one mapping. You can put this into custom web config section or whatever suits your requirements. You can look into using URL rewrite module - it won't be pretty, but it should work. E.g. rewrite carId to foo.

Having said that, if the query string is for your use only, then don't use it. Find an alternative method. It's a matter of time before somebody figures it out and causes some damage.

Title: Hiding query strings logically?


问:
Automating database deployment using a CMS
My team are developing Umbraco websites and looking to improve the automation of our database deployment.  Currently we have automated builds and deployments of our source code using Kiln and Team City, but cannot work out how to handle the database deployment.

The challenge is applying changes made in the development environment, while keeping new database content that has been added in the live environment via the CMS.  Currently our changes are deployed using courier manually, but we aim to convert this into a '1 click deployment' which is what we desire for running our automated tests and ease of deployment.  How can we automate this without wiping new content added in the CMS?

答:
After further investigation, this is possible to do using Courier.  Courier contains 'revisions' which can be checked into source control and deployed.  They can be configured to move either only the data itself (from live back to dev) or to move only the structure (from dev to live).

The only limitation to this is Courier does not support Umbraco Members.


问:
How to solve "train wreck" properties problem that violates Law Of Demeter?
I've been reading about law of Demeter and I would like to know how to solve this traversing model properties problem that I see a lot on Objective-C. I know that there is a similar question but in this case I'm not calling a method from the last property that do some calculations, instead, I'm just setting values (Ok, I know that getter are methods but my intention here is just to get the value, not to change the state of some object).

For example:

```<code>self.priceLabel.text = self.media.ad.price.value;
</code>```

Should I change that for something like:

```<code>self.priceLabel.text = [self.media adPriceValue];
</code>```

and inside the Media.m

```<code>- (NSString *)adPriceValue {
    return [self.ad priceValue];
}
</code>```

and inside the Ad.m

```<code>- (NSString *)priceValue {
    return [self.price value];
}
</code>```

Is that a good solution? Or Am I creating unnecessary methods?

答:
After reading the very interesting article posted by Robert Harvey, I'd suggest that if you're still worried about the LoD you do this (forgive me for not using ObjC syntax here, I have no clue how that works):

```<code>/* Old code: */
void update() {
  this.priceLabel.text = this.media.ad.price.value;
}

/* New code: */
void update() {
  updateAdInfo(this.media.ad);
}
void updateAdInfo(Ad ad) {
  // Can dive a level deeper here if you want to.
  this.priceLabel.text = ad.price.value;
}
</code>```

Rationale: By introducing additional getters for sub-properties, you're flattening out your domain model, and that's just horrible: you lose all structure, and increase coupling. (What if you add a property to Ad? Do you now go to every single class that embeds an Ad and add getters for the new property?)

However, if you have a hierarchy of objects and a matching (partial) pseudo-hierarchy of view elements to display them, it makes sense to organize your update functions in a hierarchy as well.

Body:
After reading the very interesting article posted by Robert Harvey, I'd suggest that if you're still worried about the LoD you do this (forgive me for not using ObjC syntax here, I have no clue how that works):

/* Old code: */
void update() {
  this.priceLabel.text = this.media.ad.price.value;
}

/* New code: */
void update() {
  updateAdInfo(this.media.ad);
}
void updateAdInfo(Ad ad) {
  // Can dive a level deeper here if you want to.
  this.priceLabel.text = ad.price.value;
}

Rationale: By introducing additional getters for sub-properties, you're flattening out your domain model, and that's just horrible: you lose all structure, and increase coupling. (What if you add a property to Ad? Do you now go to every single class that embeds an Ad and add getters for the new property?)

However, if you have a hierarchy of objects and a matching (partial) pseudo-hierarchy of view elements to display them, it makes sense to organize your update functions in a hierarchy as well.


答:
You are doing too much when the average developer can't understand what you did by reading your code.

Do frequent code reviews with your team.

Discuss with the architectures, technologies or patterns you plan to use. (in daily stand-up meetings if you have them)

I fight all CV driven "architects" I encounter. I wish the dome existed! ;)

I believe the world is wasting a huge pile of money that we could use for improving our (programmer's) life instead.

Title: When does it become overkill?

Body:
First off, I apologize cause I don't know how to make a community thread; so someone help me out please.

As a developer, across many platforms, technologies and even on an infrastructure level; I always find myself asking, when am I doing TOO much?!?

It's been a never ending learning process, since I started. One (1) thing I learned is that requirements are barely valid for an extended period of time, and as such a little foresight may go a long way.

But where is the balance, and how do you know when you're losing time, not gaining it?!


答:
In my opinion if you are writing code that does something to something then it should take parameters that define what things it should do them to and its name should define as far as possible what it does to it.

If you are writing code that packages up an action to be performed on something then you should wrap the things it should be performed on in an object and pass them to your thing that does something.

This action then becomes a kind of meta-description of the calls to the methods of the first that you can then perhaps perform at a later date by queueing it up or even decide not to do it at all for some reason.

So your question translates into is it an Action or a Function? An Action could be postponed or cancelled and therefore should encapsulate that which it acts upon. A Function happens immediately so there is no need top preserve its parameters.

You can undo and Action but not a Function.

Title: Fields vs method arguments

Body:
I just started writing some new class and it occurred to me that I was adding a lot of method arguments that are not strictly needed. This is following a habit to avoid having state in classes that is specific to some method call, rather than being general configuration or dependencies of the class.

Doing so means that a lot of methods that could have no arguments end up with one, two or three.

I'd like to hear your opinions on what you think of this tradeoff, and how you go about deciding which approach to take in what situation?

Since code is often easier to understand than English when describing code, I created a little gist that has both variants in it: https://gist.github.com/JeroenDeDauw/6525656


问:
When is it okay to log filename/line information for errors?
We have a closed-source commercial C++ application. Some of our logged error messages are in plain English like "ERROR: could not read file 'foo'". While others use a macro to print filename/line information like ""SplineReticulator.cpp(423): out of bounds". This is not an assert or a crash, the application recovers fine, but it's an error we want to log.

What is a good rule of thumb when plain-English error message is appropriate vs. a filename/line one? Or are filename/line type errors even appropriate for closed-source commercial software? We've heard the argument they are unprofessional looking, but they are handy for debugging.

答: Our guideline is that technical details are only logged at debug level. All other messages are for customer consumption and must be worded appropriately with a minimum of technical jargon.(mere humans must be able to understand. :-)</p>


问:
Apps being portable
I haven't found much on this, but what I did find doesn't explain it well enough (at least for me).

What makes the application I make portable?

Or what defines a portable application?

Is there a specific difference that makes an app portable or not?

I always thought if I just made an executable file and some images I could just copy that folder and take it to another computer on a flash drive.  But, if you could what is the purpose of having "portable" apps?

I know I have asked a range of questions, but I suspect an answer that addresses one of the questions will cover them all.

答:
The Wikipedia definition is clear enough.

A portable app is one that can run in a compatible computer without having to install it. This app can be run from a external storage and writes its data and configuration files to this device, as opossed to in the machine hardrive.

The concept of portable app is distinct from software portability which is the ability to compile software into different platform excutables or be run in different platform virtual machines.

Title: Apps being portable


答:
In the past when working on web applications using ids from querystrings to look up potentially sensitive data, I've used two fields combined to improve the security, e.g. user id and user email address, then in server side code checking the id passed in is correct for that email address.

```<code>userId = Request.Querystring("userId")
userEmail = Request.Querystring("userEmail")

userObj = db.getUser(userId)
if(userObj.email == userEmail)
    //all good
else
   //someone's made a mistake / being naughty with the querystring
</code>```

I've no doubt dedicated hackers could get around this (and most security measures), but it seemed appropriate to the level of security required at the time, and prevents simple editing of the userId to view other people's data.

Hope this is of use / vaguely relevant for your situation.

Title: Hiding query strings logically?

Body:
In the past when working on web applications using ids from querystrings to look up potentially sensitive data, I've used two fields combined to improve the security, e.g. user id and user email address, then in server side code checking the id passed in is correct for that email address.

userId = Request.Querystring("userId")
userEmail = Request.Querystring("userEmail")

userObj = db.getUser(userId)
if(userObj.email == userEmail)
    //all good
else
   //someone's made a mistake / being naughty with the querystring

I've no doubt dedicated hackers could get around this (and most security measures), but it seemed appropriate to the level of security required at the time, and prevents simple editing of the userId to view other people's data.

Hope this is of use / vaguely relevant for your situation.


问:
Placing images into Git for a CRM
I have built this CMS that has the option to add entries to the database.  Each entry that is created has about 5 to 10 new images showing the product for sale. Each image is about 150Kb in size.

I already know that images should always be stored in Git however my problem is that the sales team users that add new entries in the CMS are obviously working on the production server using the master branch.

Our normal development is development code in your "dev environment" on a branch, then push those changes to the "staging environment" for QA and lastly if all the tests pass, push those changes to "production/live server".

What will be the best way to get those new images that are uploaded on a daily basis into our repository seeing as those images are already on the live server?

答: I've faced the same problem before. We had to bring live database back into development. It was a manual process and it was carried out on QA lead's request. The more frequently you do this, the better. As the gap (difference) increases, it'll become harder to sync changes.</p>

Title: Placing images into Git for a CRM


答:
Who and what are you trying to guard against?

If you are trying to shield values of the query string from an attacker who is trying to intercept traffic between you and a valid user, then use HTTPS.  In this case, securing the transport layer will give you most bang for your buck and be the easiest, most straightforward way to implement it.  Hackers won't be able to make sense of anything you're sending back and forth, much less the individual parameters passed in your query string.

If you're trying to shield values of your query string from a malicious user of your application, then I think you're probably going about it the wrong way.  First off, you have to consider the fact that in order for the client to send you an encrypted query string, they will have to first build an encrypted query string.  How can they do this without knowing specifically which parameters and values to ecrypt?  In the case of a web app, preventing a user from being able to see what logic you're using to build and encrypt a query string would be near impossible.

Secondly, you have to ask yourself WHY it is so dangerous for a user to be able to manipulate this query string however they see fit?  One reason may be that they are able to see information they're not authorized for.  For example, I might modify carId to some arbitrary value 123, and then get illegal access to info about that car.  Rather than avoid me sending you that number, you inspect the request when it comes in, and validate whether or not I am actually allowed to see that data.  If not, don't send it, it's that simple.

If a user is able to pass in values that would somehow break the app, then the answer is to validate and sanitize your input.  If me passing carId=-1 or carId=DROP+TABLE+[Cars] blows up your database, then simply make sure that you don't accept those values!  If carId <=0 throw new ArgumentException("carId") for example.

Title: Hiding query strings logically?


答:
When the processes overtake the results.

Too many times have we seen that if the developers are focusing more on the process rather than the results (as in quality, making the deadline, etc.) bad things commence.

This is why it should be never forgotten that the purpose of code reviews, design patterns, etc. is to make the code better, but they are not the target themselves.

Title: When does it become overkill?


答:
I suggest you consider the following.

Does self need a reference to media and ad, or does self only use price? If you only use price, you don't need to go through the entire chain.

If media.ad.price is primarily a data structure (little or no behavior/methods), you probably don't need to worry about Demeter.

If self does use media, ad, and price, self might be complex enough to justify dividing self into smaller classes.

There are trade-offs to hiding or exposing delegates. You should pick what you think works best for you, and it is possible to change your implementation later.

Hiding the delegate forces you to write delegation methods, but it encapsulates changes to the structure. For example, if you add another layer, like media.ad.timeSlot.price, you would only have to change the delegate method, not all of the classes that use the delegate. On the other hand, as mentioned by Sebastian, if you want to add a new property or method for price, you have to write a delegation method.

You can choose a middle-ground solution. For example, it might make sense for self to get a reference to ad, but add a method to ad to return the price value, so that self doesn't have to navigate the rest of the structure.

Title: How to solve "train wreck" properties problem that violates Law Of Demeter?

Body:
I've been reading about law of Demeter and I would like to know how to solve this traversing model properties problem that I see a lot on Objective-C. I know that there is a similar question but in this case I'm not calling a method from the last property that do some calculations, instead, I'm just setting values (Ok, I know that getter are methods but my intention here is just to get the value, not to change the state of some object).

For example:

```<code>self.priceLabel.text = self.media.ad.price.value;
</code>```

Should I change that for something like:

```<code>self.priceLabel.text = [self.media adPriceValue];
</code>```

and inside the Media.m

```<code>- (NSString *)adPriceValue {
    return [self.ad priceValue];
}
</code>```

and inside the Ad.m

```<code>- (NSString *)priceValue {
    return [self.price value];
}
</code>```

Is that a good solution? Or Am I creating unnecessary methods?


问:
Excessive use “this” keyword in Java
The this keyword is primarily used in three situations.

The first and most common is in setter methods to disambiguate variable references.

The second is when there is a need to pass the current class instance as an argument to a method of another object.

The third is as a way to call alternate constructors from within a constructor.

However someone at work decided too put a PMD/Checkstyle rules at work that force us to put "this" in front of all the variable and method.
 Is it really viable to do that or it's just to verbose ?

Related:
What is the accepted style for using the `this` keyword in Java?

答:
This question straddles the boundary of opinion-based vs. factual information; nevertheless I consider it valuable enough to leave open because I find the usual answers of "this is a style question, do what you like" too simplistic. So here's my pointed opinion:

Using this to refer to attributes of a class within the class is redundant, and so increases code verbosity with no clear benefit. Not only can you almost always look up the status of a variable via the tools you use; more importantly, if you have to look it up, then your class is too big in the first place. Just like a method that requires you to scroll up to find the declaration of a local variable is too long, if you have to look up a member field while writing code within a class, then that class does too much.

In other words, using this.fieldName except for disambiguation is unnecessary cruft, and if you need it for the reason commonly given, you have greater problems than scope issues.

Title: Excessive use “this” keyword in Java


答:
It doesn't seem like this is a task for your source control - this is end-user data that needs to be backed up, but otherwise has nothing to do with the product as an entity itself.

For example, if you decided to sell your CMS to another customer, would they expect to see all your products contained in the DB, or would they expect a (mostly) blank database that they would fill with their own product data?

Git is not a backup solution BTW, you need something that can back up your production system and restore it correctly (though any SCM can be used for this task, its not a primary role for it, and you'd still need to backup the SCM repository).

Title: Placing images into Git for a CRM

Body:
I have built this CMS that has the option to add entries to the database.  Each entry that is created has about 5 to 10 new images showing the product for sale. Each image is about 150Kb in size.

I already know that images should always be stored in Git however my problem is that the sales team users that add new entries in the CMS are obviously working on the production server using the master branch.

Our normal development is development code in your "dev environment" on a branch, then push those changes to the "staging environment" for QA and lastly if all the tests pass, push those changes to "production/live server".

What will be the best way to get those new images that are uploaded on a daily basis into our repository seeing as those images are already on the live server?


答:
Just considering Java: too verbose IHMO.

However, if you're in an environment where you are switching frequently between Java and Javascript, having consistency in the usage of 'this.' might have benefits. (I'd still consider it too verbose, but I can see the case being made).

Title: Excessive use “this” keyword in Java

Body:
The this keyword is primarily used in three situations.

The first and most common is in setter methods to disambiguate variable references.

The second is when there is a need to pass the current class instance as an argument to a method of another object.

The third is as a way to call alternate constructors from within a constructor.

However someone at work decided too put a PMD/Checkstyle rules at work that force us to put "this" in front of all the variable and method.
 Is it really viable to do that or it's just to verbose ?

Related:
What is the accepted style for using the `this` keyword in Java?


问:
Documentation in OOP should avoid specifying whether or not a "getter" performs any computation?
My school's CS program avoids any mention of object oriented programming, so I've been doing some reading on my own to supplement it -- specifically, Object Oriented Software Construction by Bertrand Meyer.

Meyer makes the point repeatedly that classes should hide as much information about their implementation as possible, which makes sense. In particular, he argues repeatedly that attributes (i.e., static, non-computed properties of classes) and routines (properties of classes that correspond to function/procedure calls) should be indistinguishable from each other.

For example, if a class Person has the attribute age, he asserts that it should be impossible to tell, from the notation, whether Person.age corresponds internally to something like return current_year - self.birth_date or simply return self.age, where self.age has been defined as a constant attribute. This makes sense to me. However, he goes on to claim the following:

The standard client documentation for a class, known as the short form of the class, will be devised so as not to reveal whether a given feature is an attribute or a function (in cases for which it could be either).

i.e., he claims that even the documentation for the class should avoid specifying whether or not a "getter" performs any computation.

This, I don't follow. Isn't the documentation the one place where it would be important to inform users of this distinction? If I were to design a database filled with Person objects, wouldn't it be important to know whether or not Person.age is an expensive call, so I could decide whether or not to implement some sort of cache for it? Have I misunderstood what he's saying, or is he just a particularly extreme example of OOP design philosophy?

答:
As the accepted answer comes to the conclusion:

So: document performance issues.

and self-documented code is considered to be better than documentation it follows that the method name should state any unusual performance results.

So still Person.age for return current_year - self.birth_date but if the method uses a loop to calculate the age (yes): Person.calculateAge()


答:
The purpose of passing a method to another method is to separate the purposes of those two methods. This is in keeping with accepted principles of object-oriented design, specifically the Single Responsibility Principle: "a code object should do one thing, and be the only code object in the codebase that does that thing".

Case in point, let's say you have a method that reads a file in a certain format (let's say pipe-delimited text), and a method that digests the information in that file in a specific way to extract some information. You say you should put these together in one method. Well, what happens when the program needs to start reading from CSV files? What happens when you need a different subset of the data contained in it? You need to change the method. But the program still needs to handle pipe-delimited text and pull the older set of data. Now you have one method that reads from two different file types and produces two different sets of data. This method is rapidly on its way to becoming unmaintainable.

Instead, you can create a method that reads pipe-delimited text, and another that reads CSVs. You can create a method that extracts one data set, and another that extracts the second. Then, you can give the file-reading method as a delegate to the data extraction method, or vice versa. Or, you can give them both to a third class of method that will simply execute them in order, giving the data from the file to the dataset-extracting method.

By dong this, you increase the number of methods you're writing, but each method has one and only one purpose. Any change you need to make so that the method works properly won't affect the purpose or execution of any other. The resulting code is easier to understand, easier to maintain, and thus will require less testing in order to ensure its correctness.

Title: Why would I ever use delegates if I'm not doing events?

Body:
I am trying to learn how to do events in C#, and according to the MSDN Events tutorial,

Events are declared using delegates. If you have not yet studied the Delegates Tutorial, you should do so before continuing

so now I'm trying to understand Delegates first, and failing horribly. What are they for? What problem are you trying to solve where you delegate something?

I THINK they're for passing methods into other methods but what is the point of that? Why not just have a method that does whatever you're doing in the first place?


问:
Automated builds, build tools and Embedded systems
I come from an embedded world where we use C/C++ for programming, and use an IDE to generate a binary file, which is then programmed into a Hardware Board, which can then be tested.

With this background, what is a better workflow for automated builds than the current workflow of -build(using IDE)->Flash into the hardware->test. In other words, is there a way I can benefit from the advantages of CI in the domain that I operate in?

答:
There are a gazillion good reasons to use CI in an embedded team (if you are working alone in your IDE, advantages of CI are less obvious, I in CI is integration and you aren't integrating with anyone when you are working alone)

It forces you to have a repeatable, scripted, automated build process. The output from your CI system is the output that gets tested and will be consistent. No matter what developpers install on their machine, the build will be unaffected.

The big advantage of CI is the ability to run automated unit tests. These test can be cross compiled to the CI machine platform. This has the architectural side effect of decoupling your hardware dependant logic from the rest, easing an eventual port to another platform and easing reuse of platform independent code to another project.

It will make sure that what everyone's commit into source control builds, and quickly give feedback when it doesn't. It really speeds up things to know which commit broke the build.

It will give the testing team a common place to get the latest version without any burden on the dev team. Or to quickly bissect a newfound bug that appeared since 2 weeks ago...

Automated code inspection, metrics and analysis tools can trigger warning on code that got checked in.

The usual workflow is usually to have the build products available on the server to be flashed on the board. In your everyday development, you use your IDE's build/flash workflow.
I do not know about your project, but it is also possible to have an automated script to flash the new firmware on the actual board and then start/stop tests automatically on the board via a serial interface, for example.


问:
Why can static methods only use static data?
I don't understand why a static method can't use non-static data. Can anybody explain what the problems are and why we can't do it?</p>

答:
The other answers pretty much say it all, however, there is some "detail" I'd like to add.

Static methods (say those in Java) just don't have an implicit object associated to them (accessible through this) whose members you can access usually directly by name.

That doesn't mean they cannot access non-static data.
```class MyClass {
  public static void foo(MyOtherClass object) {
    System.out.println(object.member);
  }
}<br>
class MyOtherClass {
  public int member = 10;
}```

I know this is just a detail, but I found your question strange when I read it. "Can use only static data" is too much restrictive.

By the way, I didn't test the code, I just wrote it here in order to exemplify what I was saying.

Body:
The other answers pretty much say it all, however, there is some "detail" I'd like to add.

Static methods (say those in Java) just don't have an implicit object associated to them (accessible through this) whose members you can access usually directly by name.

That doesn't mean they cannot access non-static data.

class MyClass {
  public static void foo(MyOtherClass object) {
    System.out.println(object.member);
  }
}

class MyOtherClass {
  public int member = 10;
}

I know this is just a detail, but I found your question strange when I read it. "Can use only static data" is too much restrictive.

By the way, I didn't test the code, I just wrote it here in order to exemplify what I was saying.


问:
How to deal with pointers from child to parent?
I have a class that represents a file in specific binary format on disk (the parent in the title) and another class that represents an object inside that file (child). When the object changes, it sometimes needs to relocate to a new position in the file and the file class has to be notified about this new position.

To do this, I have added a weak_ptr field to object, which points to the file. Except that means there has to be a shared_ptr for file, so I'm using a static factory method instead of public constructor for it. And object now can't be initialized in the constructor, so I'm using unique_ptr for it.

In code, it looks something like this:

```<code>class File;

class Object
{
private:
    std::weak_ptr<File> file;

public:
    Object(std::weak_ptr<File> file)
        : file(file)
    {}

    void modify();
};

class File
{
private:
    std::unique_ptr<Object> object;
    std::shared_ptr<File> self;

    File()
    {}

public:
    void setObjectPosition(std::uint64_t newPosition);

    static std::shared_ptr<File> create();
};

void Object::modify()
{
    std::uint64_t newPosition = …;

    file.lock()->setObjectPosition(newPosition);
}

void File::setObjectPosition(std::uint64_t objectPosition)
{
    // store objectPosition
}

std::shared_ptr<File> File::create()
{
    auto file = std::shared_ptr<File>(new File());

    file->self = file;
    file->object = std::unique_ptr<Object>(new Object(file));

    return file;
}
</code>```

Is this this the right approach to do this? Or is there a better/more idiomatic solution? I feel like I'm using *_ptr too much, but I can't think of anything better.

答:
If all you need is a non-owning pointer to an object, just use a raw pointer. Here's a smaller example:

```<code>template <typename T> struct binary_tree_node
{
    std::unique_ptr<binary_tree_node> left_child_;
    std::unique_ptr<binary_tree_node> right_child_;
    binary_tree_node* parent_ = nullptr;
    T data_;
};
</code>```

shared_ptr and unique_ptr imply some kind of ownership, which child->parent does not have, since the parent owns the child. Therefore a raw pointer is totally okay in this situation(just don't delete it!)

Body:
If all you need is a non-owning pointer to an object, just use a raw pointer. Here's a smaller example:

template <typename T> struct binary_tree_node
{
    std::unique_ptr<binary_tree_node> left_child_;
    std::unique_ptr<binary_tree_node> right_child_;
    binary_tree_node* parent_ = nullptr;
    T data_;
};

shared_ptr and unique_ptr imply some kind of ownership, which child->parent does not have, since the parent owns the child. Therefore a raw pointer is totally okay in this situation(just don't delete it!)


问:
What is your favorite whiteboard interview problem?
Just as the title says, what is your favorite whiteboard interview problem, and why has it proven effective for you?

Junior, senior, Java, C, Javascript, PHP, SQL, pseudo-code, etc.

答:
Two questions that have elicited interesting whiteboard discussions for me are

"Please can you explain in as much detail as you like how a web browser gets a generated page"

"Please explain how Java Hibernate works"

They start off simple and then get progressivly more complex.


问:
Why would I use code contracts
I recently stumbled upon Microsoft's framework for code contracts.

I read a bit of documentation and found myself constantly asking: "Why would I ever want to do this, as it does not and often cannot perform a static analysis."

Now, I have a kind of defensive programming style already, with guarding exceptions like this:

```<code>if(var == null) { throw new NullArgumentException(); }
</code>```

I'm also using NullObject Pattern alot and have rarely any problems. Add Unit Tests to it and you're all set up.

I have never used asserts and never missed them. Quite the contrary. I really hate code that has lots of meaningless asserts in it, which is just noise to me and distracts me from what I really want to see. Code contracts, at least the Microsoft way are much the same - and even worse. They add lots of noise and complexity to the code. In 99% an exception will be thrown anyway - so I don't care whether it's from the assert/contract or the actual problem. Just very, very few cases remain in which the program states really becomes corrupted.

So frankly, what is the benefit of using code contracts? Is there any at all? If you already use unit tests and code defensively I feel that introducing contracts is just not worth the cost and puts noise in your code that a maintainer will curse when he's updating that method, much like I do when I cannot see what the code is doing due to useless asserts. I have yet to see a good reason to pay that price.

答:
You might just as well have asked when static typing is better than dynamic typing. A debate that has been raging for years with no end in sight.
So have a look at questions like
Dynamically vs Statically typed languages studies

But the basic argument would be the potential to discover and fix issues at compile time that might otherwise have slipped into production.

Contracts vs. Guards

Even with guards and exceptions you are still faced with the issue that the system will fail to perform it's intended task in some instance. Possibly an instance that will be quite critical and costly to fail at.

Contracts vs. Unit tests

The usual argument on this one is that tests prove the presence of bugs, while types (contracts) prove the absence. F.ex. using a type you know that no path in the program could possibly supply invalid input, while a test could only tell you that the covered path did supply the correct input.

Contracts vs. Null Object pattern

Now this is at least in the same ball park. Languages like Scala and Haskell has had great success with this approach to eliminating null references entirely from programs. (Even if Scala formally allows nulls the convention is to never use them)

If you already employ this pattern to eliminate NREs you've basically removed the largest source of runtime failures there is in basically the manner contracts allow you to do it.

The difference might be that contracts has an option to automatically require all your code to avoid null, and thus force you to use this pattern in more places to pass compilation.

On top of that contracts also give you the flexibility to target things beyond null. So if you no longer see any NRE in your bugs you might want to use contracts to strangle the next most common issue you might have. Off by one? Index out of range?

But...

All that being said. I do agree that the syntactic noise (and even structural noise) contracts add to the code is quite substantial and the impact the analysis has on your buildtime should not be underestimated.
So if you decide to add contracts to your system it would probably be wise to do so very carefully with a narrow focus on which class of bugs one tries to address.

Title: Why would I use code contracts


问:
In an optimal software design, would you ever need to throw InvalidOperationException?
.NET defines the InvalidOperationException as

The exception that is thrown when a method call is invalid for the
  object's current state.

In an optimal software design, would it ever make sense to throw this exception? I would argue that the 'optimal' API prevents any misuse, including, never allowing a method to be called when its state is invalid.

答:
I generally agree with your statement, but when designing an API, this type of exception would be useful to a developer who is interfacing with that API.  Whereby the developer would be informed by this exception that his/her code is structured incorrectly.

It would also be best practice to define a verbose message back with the exception indicating what the issue is in plain English (or whatever language is your primary).


问:
Should an HTTP API always return a body?
Is there some sort of standard regarding HTTP API responses?

After reading this discourse thread I started to wonder.  We are developing our public HTTP JSON API at my work, and we do not return anything when it's not strictly needed (for example a PUT to /resource/{id} only returns 200 when OK or the corresponding 4XX or 5XX code, but no JSON body)

Should we return a generic {"success":true} like they discuss on that link above, or is it ok to return a "void" body and handle everything with http response codes?

答:
No for example, for 204 responses we must not include message body. {success|status|isSuccessful: true} is redundant.

In practice (or should I say in later version of jquery), empty response for application/json content type raises error. I kind of understand the argument that because it's application/json it must have a valid json body. So, empty response for application/json content type would be 'null' or '{}' which are valid json.

There's another way which should work for jquery, that is not returning application/json for empty responses. Just use text/plain or something and make sure client can handle that type.

Note I can only remember 204 for explicitly forbid returning message body. What we've found is we can't always use 204. The problem is MSIE drop response header for 204 responses, so there's no content and headers, which is bad. Since many are using MSIE, we had to change it to 200 status.


问:
"Open source" proprietary software licenses?
I am writing some software that (for once - usually I open source stuff on sourceforge/github/etc.) I plan on selling. To each source file, I want to attach a proprietary software license that doesn't allow anyone to use, modify, derive, etc. the software (and source code) without my express permission.

I have been looking at the Microsoft Reference Source Licensing and would be happy to use that, however I'm not sure if I can (legally).

So I ask: in the same way that there are well-known an regarded open source software licenses (ASL, GNU, etc.), are there well-know proprietary licenses that are "open" in the sense that I could use them to protect my product? Thanks in advance!

答:
No, there are none that are particularly well regarded, mostly because there aren't very many at all.

Companies that don't free their products are usually VERY wary of letting ANYONE see the source under any circumstances. When they do, they usually want a pile of legal paperwork.

I do have to ask what you hope to accomplish by using such a license. I can envision very few circumstances where anyone who buys your software is going to care about the source code to a product they aren't allowed to modify.

If I were going to sell a product, then I'd simply keep the source to myself. If someone has a really good reason and need, you can negotiate a look at the source on an individual basis.


答:
Two things really:

Tooling support, VS can make contract data apart of intellisence so that it is part of auto complete help.

When a subclass overrides a method you lose all your checks (which should still be valid if you follow the LSP) with contracts they follow their child classes automatically.

Title: Why would I use code contracts

Body:
I recently stumbled upon Microsoft's framework for code contracts.

I read a bit of documentation and found myself constantly asking: "Why would I ever want to do this, as it does not and often cannot perform a static analysis."

Now, I have a kind of defensive programming style already, with guarding exceptions like this:

```<code>if(var == null) { throw new NullArgumentException(); }
</code>```

I'm also using NullObject Pattern alot and have rarely any problems. Add Unit Tests to it and you're all set up.

I have never used asserts and never missed them. Quite the contrary. I really hate code that has lots of meaningless asserts in it, which is just noise to me and distracts me from what I really want to see. Code contracts, at least the Microsoft way are much the same - and even worse. They add lots of noise and complexity to the code. In 99% an exception will be thrown anyway - so I don't care whether it's from the assert/contract or the actual problem. Just very, very few cases remain in which the program states really becomes corrupted.

So frankly, what is the benefit of using code contracts? Is there any at all? If you already use unit tests and code defensively I feel that introducing contracts is just not worth the cost and puts noise in your code that a maintainer will curse when he's updating that method, much like I do when I cannot see what the code is doing due to useless asserts. I have yet to see a good reason to pay that price.


问:
Do I need a database to implement AJAX functionality for my app?
I am new to the construction and design of a web app so I'd like some advice please (Django is my framework).  I'm trying to code up a "how-to" website instructing users the step-by-step process for doing a certain task.  I'd like the navigation of the website to be something like this...

http://technet.microsoft.com/en-us/library/aa991542.aspx

...in which there is a tree-like navigation on the left-pane that lists each step (e.g. Step 1, Step 2, etc...) that expands and loads the instructions for each step into the right-pane.            I don't want to reload the page each time so that leads me into AJAX.  At this point, I'm not sure how to implement this.  Do I store the HTML/CSS into a database to be pulled when the user clicks on certain links?  Or do I write the HTML/CSS into my template files with display: hidden to be changed to display: block when corresponding links are clicked?

答:
What I think you our looking for:

Framework page:  all links point to this page

Includes hardcoded sidebar and a div with all CSS for instructions.

The sidebar:

The sidebar will contain links to each of the steps, but each href=step1/2/3/...

You will then need JavaScript code that will need to get the href, and make a query to a static page (can be dynamic, but unnecessary) URL = "http://URL.com/path/file/" + href. Then set the instructions div to request.response.

http://URL.com/path/file/[href]

A text file with HTML code that is equivalent to what would go inside the instructions div.

Sample Code:

HTML:

```<code><!DOCTYPE html>
<html>
 <head>
  <jquery></jquery>
  <title></title>
 </head>
 <body>
  <div id="sidebar">
   <a href="step1" class="sidebarLink">step1</a>
   <a href="step2" class="sidebarLink">step2</a>
   ...
  </div>
  <div id="instructions">
   loading
  </div>
  <script>
   $(document).ready(function(){
    $(".sidebarLink a").click(function(event) {
     event.preventDefault()
     var step = $(this).attr("href")
     request=new XMLHttpRequest()
     request.open('GET',"http://URL.com/path/file/" + step,false)
     request.send()
     document.getElementById('instructions').innerHtml = request.response
    })
   })
  <script>
 </body>
</html>
</code>```

http://URL.com/path/file/[href]

there will need to be one of these files in for each step.  The file would contain something like the following:

```<code><p>this is instructions</p>
<p>this is more instructional text</p>
</code>```

I can't remember the javascript syntax for changing the url of the browser without a refresh, if you need that feature.

Body:
What I think you our looking for:

Framework page:  all links point to this page

Includes hardcoded sidebar and a div with all CSS for instructions.

The sidebar:

The sidebar will contain links to each of the steps, but each href=step1/2/3/...

You will then need JavaScript code that will need to get the href, and make a query to a static page (can be dynamic, but unnecessary) URL = "http://URL.com/path/file/" + href. Then set the instructions div to request.response.

http://URL.com/path/file/[href]

A text file with HTML code that is equivalent to what would go inside the instructions div.

Sample Code:

HTML:

<!DOCTYPE html>
<html>
 <head>
  <jquery></jquery>
  <title></title>
 </head>
 <body>
  <div id="sidebar">
   <a href="step1" class="sidebarLink">step1</a>
   <a href="step2" class="sidebarLink">step2</a>
   ...
  </div>
  <div id="instructions">
   loading
  </div>
  <script>
   $(document).ready(function(){
    $(".sidebarLink a").click(function(event) {
     event.preventDefault()
     var step = $(this).attr("href")
     request=new XMLHttpRequest()
     request.open('GET',"http://URL.com/path/file/" + step,false)
     request.send()
     document.getElementById('instructions').innerHtml = request.response
    })
   })
  <script>
 </body>
</html>

http://URL.com/path/file/[href]

there will need to be one of these files in for each step.  The file would contain something like the following:

<p>this is instructions</p>
<p>this is more instructional text</p>

I can't remember the javascript syntax for changing the url of the browser without a refresh, if you need that feature.


问:
Distributing a proprietary application together with GPL software
First, there are many similar questions here, but I found none with direct answers about this specific scenario. If you find a duplicate, please be kind enough to link to the specific answer(s). Also, to avoid question being too broad, consider this specific scenario only.

Assume a proprietary Linux application, which links against LGPL libraries dynamically, and does not link against GPL libraries. It also executes GPL'ed binaries from the file system through standard OS APIs though, to perform some actions.

Then assume a customized mainstream Linux distribution, with visible trademarked logos etc removed.

Then assume a self-contained product, which includes hardware, let's say Raspberry Pi with a bootable SD card with this customized OS. Then it has the proprietary software, which ultimately needs to start when device is switched on.

How to distribute this combination legally?

More specifically, I see (at least) three separate concerns:

In general, how to distribute just the customized Linux distro legally? For example, are there tools, or which distros have tools, to download all used default source packages, ready to be included with distribution or archived locally?

I think it's sometimes thought, that if you distribute a derivative of a mainstream Linux distro, you do not need to distribute the sources of default packages yourself, or that you can just point to the distro source repositories if someone asks for them, but I'm not sure if this is legally valid way to fulfill GPL obligations.

How to legally include the proprietary software with the distribution? For example, is it ok to have the proprietary software already installed in the above mentioned SD? Is it ok to have it uninstalled on the same media, and prompt user for it's installation on first boot? Is it required to have it on separate media or downloaded from the net, and installed from that? What are the limits of "certainly OK" and "certainly not OK", is there any consensus or even legal precedent?

Is executing GPL programs with hard-coded command strings from a proprietary application OK? My understanding is, this is OK and does not create a derived work. But if this is an issue, would working around it be as simple as creating an LGPL-licensed wrapper? Or just having the commands in modifiable configuration file (a good idea anyway, regardless of licensing issues)?

Note: Except for the techincal aspects of first bullet point, I understand that answers here are not any kind of legal counsel, but answers need to be backed up somehow, this site is not for opinion polls.

答:
So, after some research, here's my own answer. NOT LEGAL ADVICE, and even as layman advice, I am not an expert in the subject.

If you are creating a product to be sold, it's best to play it safe. Downloading all source packages for all installed packages is so simple, and with current storage capacities it takes so little space, that there is just no reason to not do it. A shell script like this should do it, example commands for Debian-based distros, script untested:

```<code># use dpkg to get list of current packages,
# then download source package for each using apt-get
for pkg in $(dpkg --get-selections) ; do
    apt-get source --download-only $pkg
done
</code>```

This should probably be done for each physically distributed release, to have correct versions of sources. It's not much effort after it's set up once, and a negligible expense, so why settle for less... For rolling online releases, a different approach might be appropriate, such as having a proper package repository including source packages.

and 3. are covered by these entries in FSF GPL FAQ:

What is the difference between an “aggregate” and other kinds of “modified versions”?

I'd like to incorporate GPL-covered software in my proprietary system. Can I do this?

What is tivoization? How does GPLv3 prevent it? (Because every modern distro has GPLv3 and LGPLv3 software in it.)

Basically, as far as I understand these, as long as you make it clear there is a GPL/LGPL part in your product, do not try to prevent user from modifying the GPL part ("tivoization"), and only access GPL programs through the interfaces normally used between programs, such as execution parameters and pipes, you're fine.

Additionally, I think these FAQ entries might have some weight in a courtroom in most jurisdictions, if it comes to that, as they are written by authors of GPL, and explain intent of the license text, in case the court case boils down to disagreement on interpretation of GPL and LGPL.

Repeat disclaimer: I am not a lawyer, or even a layman expert in the subject.

Body:
So, after some research, here's my own answer. NOT LEGAL ADVICE, and even as layman advice, I am not an expert in the subject.

If you are creating a product to be sold, it's best to play it safe. Downloading all source packages for all installed packages is so simple, and with current storage capacities it takes so little space, that there is just no reason to not do it. A shell script like this should do it, example commands for Debian-based distros, script untested:

# use dpkg to get list of current packages,
# then download source package for each using apt-get
for pkg in $(dpkg --get-selections) ; do
    apt-get source --download-only $pkg
done

This should probably be done for each physically distributed release, to have correct versions of sources. It's not much effort after it's set up once, and a negligible expense, so why settle for less... For rolling online releases, a different approach might be appropriate, such as having a proper package repository including source packages.

and 3. are covered by these entries in FSF GPL FAQ:

What is the difference between an “aggregate” and other kinds of “modified versions”?

I'd like to incorporate GPL-covered software in my proprietary system. Can I do this?

What is tivoization? How does GPLv3 prevent it? (Because every modern distro has GPLv3 and LGPLv3 software in it.)

Basically, as far as I understand these, as long as you make it clear there is a GPL/LGPL part in your product, do not try to prevent user from modifying the GPL part ("tivoization"), and only access GPL programs through the interfaces normally used between programs, such as execution parameters and pipes, you're fine.

Additionally, I think these FAQ entries might have some weight in a courtroom in most jurisdictions, if it comes to that, as they are written by authors of GPL, and explain intent of the license text, in case the court case boils down to disagreement on interpretation of GPL and LGPL.

Repeat disclaimer: I am not a lawyer, or even a layman expert in the subject.


问:
How to write "good" unit tests?
Triggered by this thread, I (again) am thinking about finally using unit tests in my projects. A few posters there say something like "Tests are cool, if they are good tests". My question now: What are "good" tests?

In my applications, the main part often is some kind of numerical analysis, depending on large amounts of observed data, and resulting in a fit function that can be used to model this data. I found it especially hard to construct tests for these methods, since the number of possible inputs and results are too large to just test every case, and the methods themselves are often quite longish and can not be easily be refactored without sacrificing performance. I am especially interested in "good" tests for this kind of method.

答: Create tests for corner cases, like an test set containing only the minimum number of inputs (possible 1 or 0) and a few standard cases. Those unit tests are not a replacement for thorough acceptance tests, nor should they be.</p>

Title: How to write "good" unit tests?


答:
I don't know where the assertion that "it does not and often cannot perform a static analysis" comes from. The first part of the assertion is plainly wrong. The second one depends of what you mean by "often". I would rather say that often, it performs static analysis, and rarely, it fails at it. In ordinary business application, rarely becomes much closer to never.

So here it comes, the first benefit:

Benefit 1: static analysis

Ordinary assertions and argument checking have a drawback: they are postponed until the code is executed. On the other hand, code contracts manifest themselves at a much earlier level, either at the coding step or while compiling the application. The earlier you catch an error, the less expensive it is to fix it.

Benefit 2: sort of always up to date documentation

Code contracts also provide a sort of documentation which is always up to date. If the XML comment of the method SetProductPrice(int newPrice) tells that newPrice should be superior or equal to zero, you may hope that the documentation is up to date, but you may also discover that somebody changed the method so that newPrice = 0 throws an ArgumentOutOfRangeException, but never changed the corresponding documentation. Given the correlation between code contracts and the code itself, you don't have the out-of-sync documentation problem.

The sort of documentation provided by code contracts is also precious in a way that often, XML comments don't explain the acceptable values well. How many times was I wondering if null or string.Empty or \r\n is an authorized value for a method, and XML comments were silent on that!

In conclusion, without code contracts, lots of pieces of code are like that:

I'll accept some values but not others, but you'll have to guess or read the documentation, if any. Actually, don't read the documentation: it's outdated. Simply loop through all values and you'll see the ones which make me throw exceptions. You also have to guess the range of values which may be returned, because even if I would tell a bit more to you about them, it may not be true, given the hundreds of changes made to me for the last years.

With code contracts, it becomes:

The title argument can be a non-null string with a length of 0..500. The integer which follows is a positive value, which can be zero only when the string is empty. Finally, I'll return a IDefinition object, never null.

Benefit 3: contracts of interfaces

A third benefit is that code contracts empower interfaces. Let's say you have something like:

```<code>public interface ICommittable
{
    public ICollection<AtomicChange> PendingChanges { get; }

    public void CommitChanges();

    ...
}
</code>```

How would you, using only asserts and exceptions, guarantee that CommitChanges can be called only when PendingChanges is not empty? How would you guarantee that PendingChanges is never null?

Benefit 4: enforce the results of a method

Finally, the fourth benefit is to be able to Contract.Ensure the results. What if, when writing a method which returns an integer, I want to be sure that the value is never inferior or equal to zero? Including five years later, after suffering from lots of changes from lots of developers? As soon as a method has multiple return points, Asserts become a maintenance nightmare for that.

Consider code contracts not only as a mean of correctness of your code, but a stricter way to write code. In a similar way, a person who used exclusively dynamic languages may ask why would you enforce types at language level, while you can do the same thing in assertions when needed. You can, but static typing is easier to use, less error-prone compared to a bunch of assertions, and self-documenting.

The difference between dynamic typing and static typing is extremely close to the difference between ordinary programming and programming by contracts.

Title: Why would I use code contracts

Body:
I don't know where the assertion that "it does not and often cannot perform a static analysis" comes from. The first part of the assertion is plainly wrong. The second one depends of what you mean by "often". I would rather say that often, it performs static analysis, and rarely, it fails at it. In ordinary business application, rarely becomes much closer to never.

So here it comes, the first benefit:

Benefit 1: static analysis

Ordinary assertions and argument checking have a drawback: they are postponed until the code is executed. On the other hand, code contracts manifest themselves at a much earlier level, either at the coding step or while compiling the application. The earlier you catch an error, the less expensive it is to fix it.

Benefit 2: sort of always up to date documentation

Code contracts also provide a sort of documentation which is always up to date. If the XML comment of the method SetProductPrice(int newPrice) tells that newPrice should be superior or equal to zero, you may hope that the documentation is up to date, but you may also discover that somebody changed the method so that newPrice = 0 throws an ArgumentOutOfRangeException, but never changed the corresponding documentation. Given the correlation between code contracts and the code itself, you don't have the out-of-sync documentation problem.

The sort of documentation provided by code contracts is also precious in a way that often, XML comments don't explain the acceptable values well. How many times was I wondering if null or string.Empty or \r\n is an authorized value for a method, and XML comments were silent on that!

In conclusion, without code contracts, lots of pieces of code are like that:

I'll accept some values but not others, but you'll have to guess or read the documentation, if any. Actually, don't read the documentation: it's outdated. Simply loop through all values and you'll see the ones which make me throw exceptions. You also have to guess the range of values which may be returned, because even if I would tell a bit more to you about them, it may not be true, given the hundreds of changes made to me for the last years.

With code contracts, it becomes:

The title argument can be a non-null string with a length of 0..500. The integer which follows is a positive value, which can be zero only when the string is empty. Finally, I'll return a IDefinition object, never null.

Benefit 3: contracts of interfaces

A third benefit is that code contracts empower interfaces. Let's say you have something like:

public interface ICommittable
{
    public ICollection<AtomicChange> PendingChanges { get; }

    public void CommitChanges();

    ...
}

How would you, using only asserts and exceptions, guarantee that CommitChanges can be called only when PendingChanges is not empty? How would you guarantee that PendingChanges is never null?

Benefit 4: enforce the results of a method

Finally, the fourth benefit is to be able to Contract.Ensure the results. What if, when writing a method which returns an integer, I want to be sure that the value is never inferior or equal to zero? Including five years later, after suffering from lots of changes from lots of developers? As soon as a method has multiple return points, Asserts become a maintenance nightmare for that.

Consider code contracts not only as a mean of correctness of your code, but a stricter way to write code. In a similar way, a person who used exclusively dynamic languages may ask why would you enforce types at language level, while you can do the same thing in assertions when needed. You can, but static typing is easier to use, less error-prone compared to a bunch of assertions, and self-documenting.

The difference between dynamic typing and static typing is extremely close to the difference between ordinary programming and programming by contracts.


问:
raw aql query in framework with Active Record pattern based ORM
I use yii framework that implements Active Record pattern as ORM base. It has CActiveRecord class that is a table wrapper class with attributes reflecting table columns. So each object of this class represents a database row.

Wiki says about Active Record pattern:

Active record is an approach to accessing data in a database

and

A database table or view is wrapped into a class. Thus, an object instance is tied to a single row in the table.

So far so good.

But where should I put complex raw sql query that retrieves statistics data for example?

And, more generally, where should I put methods that retrieve some data that can not be an active record object (like data retrieved with aggregation queries) or if I knowing do not want to retrieve an object but an array instead for example?

答:
The active record pattern doesn't cover the usage of complex SQL queries. To allow that the active record pattern should be combined with a pattern that provides access to the database tables like the repository pattern. An example of that would be Doctrine 1.x that has two different classes for representing a row and a table.

Since Yii provides only one model class I can assume that these method should be implemented in the CActiveRecord class. It already implements a bunch of find methods, so I think it's totally acceptable.


问:
Until what point should I refactor?
What do you think until what point should a programmer refactor the code?

Basically having

```
def method
  do_something
end
```

Pieces of code would be handy, but they increase spaghetti code until the point where you have to remember the path of more than 8-10 methods. So wouldn't be easier to have no more than 3 methods spaghetti code, despite the fact that the method is longer than it suppose to be

答:
Refactoring for me is primarily to (1) reduce code duplication and (2) make the code easier to read and understand.

Strive to have zero (or reasonably close to zero) duplicates. That's step one. Step two is to keep refactoring until you feel the code is readable enough.

For instance replacing comments with methods is often a good candidate for refactoring, like this:

```<code>// Is order valid for purchase?
if (order.age < 10 && order.customer.isActive()) {
  // ...
}
</code>```

Could be refactored into:

```<code>if (isOrderValidForPurchase(order) {
  // ...
}
</code>```

Title: Until what point should I refactor?

Body:
Refactoring for me is primarily to (1) reduce code duplication and (2) make the code easier to read and understand.

Strive to have zero (or reasonably close to zero) duplicates. That's step one. Step two is to keep refactoring until you feel the code is readable enough.

For instance replacing comments with methods is often a good candidate for refactoring, like this:

// Is order valid for purchase?
if (order.age < 10 && order.customer.isActive()) {
  // ...
}

Could be refactored into:

if (isOrderValidForPurchase(order) {
  // ...
}


问:
C# Delegates are immutable - but why does that matter?
This is a followup question to this other question.

Background

Working from the MSDN Delegates Tutorial (C#), I see the following:

Note that once a delegate is created, the method it is associated with never changes — delegate objects are immutable.

And then, in the code sample, I see this (Spread out a little througout the code):

```<code>public delegate void ProcessBookDelegate(Book book);

bookDB.ProcessPaperbackBooks(new ProcessBookDelegate(PrintTitle));
bookDB.ProcessPaperbackBooks(new ProcessBookDelegate(totaller.AddBookToTotal));
</code>```

The Question

Now obviously, the way the code is written here a new delegate is created for each
process. I am guessing the immutability is relevant if you try to do stuff like

```<code>ProcessBookDelegate thisIsATest = new ProcessBookDelegate(PrintTitle);
ProcessBookDelegate thisIsATest = new ProcessBookDelegate(totaller.AddBookToTotal);
</code>```

which should... still compile when thisIsATest is immutable? So what problem has Microsoft solved by making it immutable? What problems would we run into if C# 6 made delegates mutable?

EDIT

I believe the immutability will prevent this:

```<code>ProcessBookDelegate thisIsATest = new ProcessBookDelegate(PrintTitle);

thisIsATest.ChangeTheDelegateInABadFashion();

someFunction(thisIsATest); //This function works as normal
                           //because the delegate is unchanged
                           //due to immutability
</code>```

but the immutability will NOT prevent this:

```<code>ProcessBookDelegate thisIsATest = new ProcessBookDelegate(PrintTitle);

thisIsATest = new ProcessBookDelegate(ChangeTheDelegateInABadFashion());

someFunction(thisIsATest); //This function works weird now because
                           //it expected the unchanged delegate
</code>```

Am I correct in this understanding?

答:
standard thread safety I believe; if you know a delegate will never change then you can make some assumptions about it

in particular you can be assured that a evil piece of code can't change the delegate you are passing to several functions (even by accident)

this could cause hard to trace bugs and leave the programmer wondering why his delegate wasn't called


答:
Only refactor when there is an absolute need for it - refactoring is a bit of a smell, in theory you shouldn't need to refactor at all, your code should be good from the start as you designed it well... but of course, in practice this isn't always going to be the case. Nevertheless, you should be writing code that you think is good from the start, trying to achieve this impossible perfection.

If you refactor continually, you will simply shuffle the existing code around forever, never satisfied with it. You'll spend all your time refactoring and never adding any new functionality, you'll be missing the point of coding - which is not to write nice code, but to create a nice product.

The other problem with refactoring is that you can end up refactoring into the kind of code that no-one else could love, getting so caught up in the need to refactor that you screw maintainability. Your example of refactoring methods to 1 line could end up with a million tiny methods if you took it to the extreme, and worrying about how much refactoring you're doing suggests you're already going down the route of getting too caught up in it.

Title: Until what point should I refactor?

Body:
What do you think until what point should a programmer refactor the code?

Basically having

```
def method
  do_something
end
```

Pieces of code would be handy, but they increase spaghetti code until the point where you have to remember the path of more than 8-10 methods. So wouldn't be easier to have no more than 3 methods spaghetti code, despite the fact that the method is longer than it suppose to be


答:
According to Martin Fowler, refactoring is

"A change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior."

Martin Fowler. Refactoring: Improving the Design of Existing Code. Boston, MA: Addison-Wesley, 2000.

This means, it is primarily up to you and your team to decide for the granularity of methods (method lenght vs. number of methods). The prime objective is to generate code that is easy to understand and cheap to modify.

Some authors tend to overplay the need for refactoring. E.g. Unkle Bob gives some examples in his book Clean Code, that are absolutely unreadable in my opinion. He's following his own guides so strictly that he does not leave room for compromises.

If three longer methods are easier to understand and cheaper to modify, stick to it.

Title: Until what point should I refactor?


问:
What is the gain from 64-bit architecture?
I played with 8-bit machines (C64), I used 16-bit machines (Win 3.1), I enjoyed flat 32-bit address space (Linux).

Every time as a user (which was also means being a developer for fun or profit) I felt the need for more bits and welcomed the next wider bit architecture. Accessing to bigger memory space got easier, graphics got better and sound was a bliss after 8-bit.

However when marketing drums started to kick in for 64-bit some years ago I thought, "ok, this is Internet age, they can use this kind of power to do more calculations easier and commodity hardware manufacturers want to spread their portfolio for this kind of market".

Professionally I became a "system programmer" working for mobile devices which some what means being an "embedded programmer" as well. Working mostly on 32-bit from the start ARM architecture based products, it was a while I forgot about different architectures other than being 32-bit.

Also when ARM announced a new 64-bit architecture towards end of 2011, I read it as ARM wants to go into server market, increasing their portfolio. Which makes sense.

Now with new iPhone 5S claiming to be the first 64-bit processor ever used on a smartphone, thoughts became a little bit unsettled in my head again. Mobile devices, being the ultimate personal devices are becoming 64-bit.

So I wonder, is there something I'm missing? What does being 64-bit offers to the users including programmers?

答:
One major benefit of having a huge address space is that you can represent all storage simply as an address. For example, my laptop has 16 GiByte of RAM and 1 TiByte HDD. With 64 bit addresses, you can easily address all that storage using a unified API. 32 bit wouldn't be enough. I could even individually address all of my USB key fobs, SD cards, microSD cards, external HDDs, NAS, DropBox, Google Drive etc.

Even my phone has 1 GiByte RAM, 4 GiByte internal flash and a 32 GiByte microSD card.

Unfortunately, no operating system does this yet (with the exception of OS/400, which has been doing exactly this since 1989, although it actually has 128 bit addressing), but that would be one benefit.

Even without such futuristic changes, there is a rather simple reason: at the rate RAM capacity in smartphones is growing, we're going to hit the "4 GiByte wall" real soon now.


问:
Correctly value a development?
I started a discussion on StackOverflow earlier this week about one of my work project and how to lead it correctly.

But it seems that this stack is a more appropriate place to ask those sort of questions, so here is my last question about my project:

How do you value your work? / How do you rate it in a financial way?

I'm working on a quite cool project with two other friends and people that we know ask us for an earlier access and how many it would cost per month for us to access it.

Unfortunately, I was not able to answer this simple question due to the fact that I'm not agree with my friends on this specific topic.

For me a bill of 80$/month/contract seems to be reasonable and appropriate for our targeted market (Institutions and Corporations) but my partner would rather count a charge of 500$/month/contract.

Our project is an asset manager in SAAS mode, and I don't really think that our potential clients would be ready to pay more than 90$/month/contract even if they have a lot of money due to their situation.

So, I would really like to have some opinions and advices on this kind of question.

PS: If my post is not on the appropriate stack, feel free to tell me.
PS2: I'm quite sorry if I'm not totally crystal clear, I'm not a native english, if you do not understand something, as above, feel free to notice me and I'll rephrase.

答:
This is a tricky issue. If you go with $80 a month and get a 100 customers but each of these would have paid $250 then you have lost  $17,000 a month in revenue.

On other hand if you ask for $500 you may only get 20 users which again leads to loss in revenue from customers who may have signed up at $250 but didn't at $500 due to the cost.

As you are a start up I would suggest talking to this potential customer and asking them how much a month they feel the service is worth to them.

If they answer $80 then charge them the $80.

On other hand if they answer $250 I would be tempted to offer them a 6-12 month price of $100 with the understanding that they provide feedback on the application during that time.

What ever price you select your should try and aim to have a price that is easily divisible by 12 or one that supports yearly discounts i.e. hae a $50 per month cost but you pay $500 if you sign up for the year.

Title: Correctly value a development?


问:
What is the benefit of 64 bit A7 in iPhone
I'm trying to figure out why going to 64 bit processors is such a big deal in an iPhone. I understand that there will be twice as many registers so the processor can work with twice as much data which should increase performance.

However I don't see many phones going to more than 4GB of memory any time soon. It seems like overkill and it would negatively impact battery life.

Another problem that I see is that most variables now need twice as much memory. This will create problems in a mobile environment with small amounts of memory.

I believe that the folks at Apple are intelligent and they probably have great reasons for doing this, I'm just trying to understand them.

EDIT

Don't know much about GPU's but I was told that with 64 bit registers 2 pixels can be loaded into each register and operations can be performed on them individually. Is there a graphical advantage regarding 64 bit?

答:
Focusing solely on A7 being ARMv8 there is one obvious gain. ARM is rebooting their instruction set and architecture.

Being backwards compability with ARMv7, next version also claims

New instruction set (A64)

Revised exception handling for exceptions in AArch64 state

Fewer banked registers and modes

So ARMv8 challenges ARMv7 on architectural differences, providing a cleaner interface for system developers which would probably remove legacy features leading to a better platform. Which means you should expect a better performance/energy instead of negative impact on battery.

See more on ARM Architecture Preview.