问:
If we could get a file's binary form, would this method of file compression work?
I'm not quite sure how easy it is to fetch the binary composition of a file, but suppose we have some file with this representation:

010011

We could make 2 arrays.

One which stores the position of the 0s:
['x', '', 'x', 'x', '', '']

And another which stores the position of the 1s (which is simply the opposite of the previous array):
['', 'x', '', '', 'x', 'x']

Then we can persist these two arrays into a file, and voila?

I don't know, is there something i'm not realizing?

I'm not an expert in compression, was just wondering if this would work.

答:
The most compact possible representation of your arrays would be 1 bit per entry. You have two arrays, each of length 6. I.e. your compressed file is 6+6 bits long, while your original file is 6 bits long. This is an increase of 100%.

Also, as @jk pointed out in his comment: your second array is identical to your input data. The first array is identical to the inverse of your input data.

```<code>       010011  # original
101100 010011  # 'compressed'
</code>```

So, not only is your compressed data twice as long, it also contains an exact copy of the original data.

Body:
The most compact possible representation of your arrays would be 1 bit per entry. You have two arrays, each of length 6. I.e. your compressed file is 6+6 bits long, while your original file is 6 bits long. This is an increase of 100%.

Also, as @jk pointed out in his comment: your second array is identical to your input data. The first array is identical to the inverse of your input data.

       010011  # original
101100 010011  # 'compressed'

So, not only is your compressed data twice as long, it also contains an exact copy of the original data.


问:
Why use getters only as opposed to marking things final?
I'm working in a java role after working a couple years in functional programming. Our company was bought by google and I took a java role after the acquisition.

Coming back to java as a polyglot developer, I'm generating getters for immutable objects and I'm seeing it's a total hogwash.

Are there any reasons why the 'getField' convention should be used so prolifically? To me it seems almost horrifying at this point that so many libraries expect public getter methods to work with their functionality when simply making a field public and final would have the same effect as making only a getter on a public mutable field.

Why isn't it more of a common practice to ditch the setters and just expose a final field?

答:
I'd like to add something people haven't mentioned:

You can override getters and setters and you can specify them in your interfaces. You cannot do this with fields.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Why is DRY important?
Quite simple, why would I want to write code that works for all cases and scalable data when all I need to do is repeat the same process a few times with a few minor tweaks?

I'm unlikely to need to edit this again any time soon.

It looks like a lot of less work to just go...

```<code>function doStuff1(){/*.a.*/}
function doStuff2(){/*.b.*/}
function doStuff3(){/*.c.*/}
</code>```

And if I ever need to add something...

```<code>function doStuff4(){/*.d.*/}
</code>```

And if I need to remove it, I remove it.

It's harder to figure out how to make all of those into one straight-forward pattern that I can just feed data into and deal with all the cases, and make a bunch of changes I don't feel like I'm ever going to have to do.

Why be DRY when it looks like a quick cut+paste is going to be so much less work?

答:
<tl;dr>

I could not read all the repeated answers so I may have missed something (and will repeat it myself <= see what I did here?).

Here is the list of things that are awesome about preventing code duplication!

Easier to test: you only need to test one ‘copy’ of the code.

Easier to fix: you only need to find the bug in one ‘copy’ of the code and fix it once.

Easier to update (same as above): needed changes, can often be handled by modifying code in very few places because you took the time to properly reuse code and did not copy the same lines to hundreds or thousands of different places in the source.

Easier to reuse: when (isn’t duplicated in a few places) and is kept in generic aptly named methods, it is easy to find them and use them instead of writing your own.

Easier to read: duplicated code is hard to read because it’s unnecessarily verbose; it contains a lot of lines that are not part of the logic and the specific intended functionality (for instance generic commands used to set up the stage for the action to take place or generic simple repeated tasks that are needed in many places). Clean code makes the logic and functionality pop-out because there is no repetition littering up the code-space.

Easier to debug because of (1) and (5).

Saves you time & money and do more fun things in the future; specifically create better more robust code. This is the bottom line and it’s a summation of pretty much all of the above. If a lot of people use the same function doFoo1(a, b), there is a better chance that many of its annoying faults & edge cases will be uncovered and resolved. If everyone copy the code and create doFoo2(specialA) ... doFuu2^n(a, b, c) then they duplicated the problems in doFoo1 and concretely created a lot more work.

</tl;dr>

Long version:

The issue with code duplication is that it "grows exponentially" (in other words, it expands rapidly) cause when you duplicate code you unknowingly grant others the permission to (for one, you’re no longer in a position to judge them) and you encourage them to do the same. You also make it harder not to because it's harder to spot and reuse useful code when there is a lot of confusing redundant repetition in the source. Especially if the code is not already extracted into an aptly named function. So if you face a common simple to solve problem you will likely write a piece of code yourself that solves it… And you will probably fail to check for a few edge cases, adding more buggy untested code.

Another thing is that to a novice this may sound like an issue that will only affect large companies but I found it afflict tiny startups just a badly (as in 10,000 lines of duplicated server-side code). It is a state of mind. You should not only master DRY but strive to encourage others to do the same; because otherwise you will doom yourself to mostly duplicate code. When the means of DRY are at hand and enforced, it is much easier to apply them. When there is lots of duplicated code, it is much easier to apply copy paste solutions.

Things I find harmful in code duplication:

Is this function usable? Let’s say you find a function that does (or appears to do what you need), how do you know if it's even supposed to work correctly or if it's just code that has been duplicated and abandoned.

Redundant code. Sometimes people duplicate code, use it and forget it (they can always duplicate it again in the future). At some point someone removes the calls to the duplicated function in some places in an effort to refactor but the unused function remains even if it is not being actively used.

Hard to find what you are looking for. Duplicated code takes up space and makes finding useful and needed things (using tools like grep) a harder task than it has to be as you get dozens or thousands of results where you should have gotten only a handful.

(Has been mentioned before): Hard to maintain but also hard to use for maintainance and regression purposes. If testing code is duplicated and not properly extracted into functions, others will duplicate it. Will anyone bother with writing an easy to use, easy to read API to make QoL better? In my experience, no, there is often something people deem more pressing matter until it gets out of hand.

Code duplication is harder to read because it makes the code verbose where it doesn't have to be, in places where the verbosity doesn't add information about the intended functionality: for instance generic method calls that are used [over and over] to set the ground for multiple kinds of intended functionality, makes it harder for this actual functionality to pop out.

This has been mentioned a lot. If the code is wrong, some poor gal or guy will need to search and change each use of that code. For instance if someone used a SQL injection unsafe call to mysql_query in very few places in an organized Class where it's needed, it would be easy to fix it and use PHP PDO instead but if they used it in over a thousand places copying the call over and over, fixing it will practically need to be outsourced or sometimes more dangerously, the code will need to be rewritten from scratch.

Duplicating code is a bad habit. If you practice something it slowly becomes a second nature and it affects people around you. Junior devs see you do it and do it also. You should practice what you preach and make a habit of doing the right thing. You learn more. Writing non-duplicated code is harder and more challenging. It is a rewarding habit.

Last notes about overzealous code duplication prevention & summing things up:

This has also been said before but sometimes avoiding duplication causes you to "bend over backwards" and do things that are too sophisticated (or unimportant) for others to understand. Writing unreadable code (or as we jokingly call it “job preserving” code) is an issue in itself even when preventing code duplication is not involved. However, I find that if the right infrastructure and best practices are instilled from the beginning it is much easier to prevent code duplication and people often can avoid doing unintuitive things so it can prevent future unnecessary and unreadable heaps of work done for code duplication prevention if you do thing right from that start.

What is doing things right? Well that is a hard question to answer but one thing is to define which methods are needed for the project and see what has already been implemented by others (outside and) inside the company and reuse that when possible; documenting everything you do add to the codebase and attempting to make it one notch more generic than it has to be but that's it. Don't overdo design patterns just to make the code flexible where it doesn't need to be.

Title: Why is DRY important?


问:
How restrictive are the GPL's linking restrictions really?
To my basic understanding, software licenses only apply when redistributing software. Even if I am wrong about this in general, the GPL states that you need not agree to the GPL in order to receive or run a GPL-covered program.

Say there is Program X. Program X requires Library L to run. Program X is covered by a GPL-incompatible license (e.g. the Eclipse Public License, or a proprietary license). Library L is covered by the GPLv3.

Program X cannot be distributed alongside Library L - the combination would need to be covered by the GPL, which would violate the EPL.

What prevents users from separately installing Program X and Library L, and then using Program X?

Perhaps more relevantly in the modern world of auto-updaters, what prevents Program X from including a wrapper which downloads Library L from the Internet (say, from Library L's official website) and then executing Program X?

In both of these cases, nothing from Library L is distributed by the authors of Program X, so Library L's license should not apply.

What, if anything, changes if Program X instead requires Library L', a fork of Library L by the authors of Program X, which is only available from the same website as Program X and is only usable with Program X, but is never distributed in the same package as Program X?

What if this is all in a dynamic language, and no part of Library L is required to compile Program X?

What if Program X is distributed in source code form, so that the distribution was not compiled from Library L's headers?

答:
From the standpoint of the FSF, program X can not be distributed at all. The reasoning here is that if Program X needs Library L to function and they don't communicate at arms length (separate processes that communicate through an inter-process interface or files), then the GPL applies to Program X as well.

If Program X isn't licensed under a GPL-compatible license, then Program X can't be distributed.

To quote their FAQ:

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

You cannot incorporate GPL-covered software in a proprietary system. The goal of the GPL is to grant everyone the freedom to copy, redistribute, understand, and modify a program. If you could incorporate GPL-covered software into a non-free system, it would have the effect of making the GPL-covered software non-free too.

A system incorporating a GPL-covered program is an extended version of that program. The GPL says that any extended version of the program must be released under the GPL if it is released at all. This is for two reasons: to make sure that users who get the software get the freedom they should have, and to encourage people to give back improvements that they make.

However, in many cases you can distribute the GPL-covered software alongside your proprietary system. To do this validly, you must make sure that the free and non-free programs communicate at arms length, that they are not combined in a way that would make them effectively a single program.

The difference between this and “incorporating” the GPL-covered software is partly a matter of substance and partly form. The substantive part is this: if the two programs are combined so that they become effectively two parts of one program, then you can't treat them as two separate programs. So the GPL has to cover the whole thing.

If the two programs remain well separated, like the compiler and the kernel, or like an editor and a shell, then you can treat them as two separate programs—but you have to do it properly. The issue is simply one of form: how you describe what you are doing. Why do we care about this? Because we want to make sure the users clearly understand the free status of the GPL-covered software in the collection.

If people were to distribute GPL-covered software calling it “part of” a system that users know is partly proprietary, users might be uncertain of their rights regarding the GPL-covered software. But if they know that what they have received is a free program plus another program, side by side, their rights will be clear.

In how far the standpoint of the FSF is legally valid is a bit uncertain, but I wouldn't want to be the testcase to see how the courts find on it.


答:
It's not always recommended, read for example the Android guidelines:

Avoid internal getters/setters

Virtual method calls are expensive, much more so than instance field lookups. It's reasonable to follow common object-oriented programming practices and have getters and setters in the public interface, but within a class you should always access fields directly.

Title: Why use getters only as opposed to marking things final?

Body:
I'm working in a java role after working a couple years in functional programming. Our company was bought by google and I took a java role after the acquisition.

Coming back to java as a polyglot developer, I'm generating getters for immutable objects and I'm seeing it's a total hogwash.

Are there any reasons why the 'getField' convention should be used so prolifically? To me it seems almost horrifying at this point that so many libraries expect public getter methods to work with their functionality when simply making a field public and final would have the same effect as making only a getter on a public mutable field.

Why isn't it more of a common practice to ditch the setters and just expose a final field?


问:
Best approach for tracking dependent state
Let's pretend I work on a project tracking application.  The application is a database backed, server hosted, web application.  In this application there are Projects which have many Activities which have many Tasks.  A Task has two date fields an originalDueDate and a projectedDueDate.

In addition, there are dynamic fields on the Activities and the Projects which indicate whether the Activity or Project is behind schedule based on the projected due dates of the child tasks and various other variables such as remaining buffer time, etc.

There are a number of things that can cause the projectedDueDate to change.  For example, an employee working on the project may (via a server request) enter in a shipping delay.  Alternatively, a site may (via a server request) enter in an unexpected closure.

When any of these things occur I need to not only update the projectedDueDate of the Task but also trigger the corresponding Project and Activity to update as well.

What is the best way to do this?

I've thought of the observer pattern but I don't keep a single copy of all these objects in memory.  When a request comes in, I query the Task in from the database, at that point there is no associated Activity in memory that would be a listener.  I could remove the ability to query for Tasks and force the application to query first by Project, then by Activity (in context of Project), then by task (in context of Activity) adding the observer relationships at each step but I'm not sure if that is the best way.

I could setup a database event listening system so when a Task modified event is dispatched I have a handler which queries for the Activity at that point.

I could simply setup a two-way relationship between Task and Activity so that the Task knows about the parent Activity and when the Task updates his state the Task grabs his parent and updates state.

Right now I'm stuck considering all the options and am wondering if any single approach (doesn't have to be a listed approach) is jumping out at others as the best approach.

答:
Let's take a look at your observer pattern: As you stated, parent objects may not be in the memory at the time of change. The observer pattern is only applied to situations where the entire observer hierarchy is present in the memory so that changes may be reflected directly. To consider this option would mean considering the following:

What does it mean for the server to contain the entire hierarchy in memory? Can the server handle it under all circumstances?

What does it mean for storage? Does every change need to be applied to the database immediatly? Is event-queuing something that needs to be considered at this point?

However, there is one answer in the form of the observer pattern possible, where you could delay all these caveats (until a design restructure would require it). This would be a design that I haven't seen used in practice yet: create a Observer class where it's instances would be pointing to the parents, instead of having the parents be the observers. So they can for example hold the database record id of the parent that they're observing for.

This way, when a Task for example is loaded, you could also load all the observers from the database that observer that task (from a seperate table with records each pointing to 1 task and 1 observer, then get all observers by task ID). Now you don't have to get the entire hierarchy, only the observer objects that observe said task.

In these observer objects you would then have the parent's ID as a variable, so that when the observers need to update, you could go for one of the following options:

Load observing parents into memory, then change them and have the changes reflected in the database. Most likely used option for: when the parent objects in question are needed rather soon again, to not have to reload them into memory again so soon.

Update the parent objects in database directly. Most likely used option for: not needing to get data from the database in order to perform the update operation.

But seeing as the hierarchy of observers may be deeper than just 1 level, chances are a task update results in a activity update, which results in a project update. So to deal with this, you'd have to load the observers that observe the parent of the Task in question. Because of this, the observer objects would then have to check if their target parent has observers, after the direct update is complete, to be able to notify the parent's parents. I'm not sure if a generalized recursive structure for this is advisable, you'd have to find out for yourself if the project/activity/task structure could become more complex in the future, in order to decide on that.

Anywho, I hope this helps. Good luck.


问:
Project is nearly done, but procedural spaghetti code. Do I rewrite or just keep trying to ship it?
I'm a beginner web developer (one year of experience).

A couple of weeks after graduating, I got offered a job to build a web application for a company whose owner is not much of a tech guy. He recruited me to avoid theft of his idea, the high cost of development charged by a service company, and to have someone young he can trust onboard to maintain the project for the long run (I came to these conclusions by myself long after being hired).

Cocky as I was back then, with a diploma in computer science, I accepted the offer thinking I can build anything.

I was calling the shots. After some research I settled on PHP, and started with plain PHP, no objects, just ugly procedural code. Two months later, everything was getting messy, and it was hard to make any progress. The web application is huge. So I decided to check out an MVC framework that would make my life easier. That's where I stumbled upon the cool kid in the PHP community: Laravel. I loved it, it was easy to learn, and I started coding right away. My code looked cleaner, more organized. It looked very good.

But again the web application was huge. The company was pressuring me to deliver the first version, which they wanted to deploy, obviously, and start seeking customers.

Because Laravel was fun to work with, it made me remember why I chose this industry in the first place - something I forgot while stuck in the shitty education system.

So I started working on small projects at night, reading about methodologies and best practice. I revisited OOP, moved on to object-oriented design and analysis, and read Uncle Bob's book Clean Code.

This helped me realize that I really knew nothing. I did not know how to build software THE RIGHT WAY. But at this point it was too late, and now I'm almost done. My code is not clean at all, just spaghetti code, a real pain to fix a bug, all the logic is in the controllers, and there is little object oriented design.

I'm having this persistent thought that I have to rewrite the whole project. However, I can't do it... They keep asking when is it going to be all done.

I can not imagine this code deployed on a server. Plus I still know nothing about code efficiency and the web application's performance.

On one hand, the company is waiting for the product and can not wait anymore. On the other hand I can't see myself going any further with the actual code. I could finish up, wrap it up and deploy, but god only knows what might happen when people start using it.

Do I rewrite, or just keep trying to ship, or is there another option that I've missed?

答:
Two more suggestions, I'll bet at least one of these you haven't done.

1) Put a bug tracker in place and teach your boss to use it. This can be part of the conversation about how you screwed up, have learned better and are going to fix it in a planned manner

2) Start using version control, although hopefully you are doing so already.

There are heaps of hosted systems out there which provide both the above for free on small accounts. I'm particularly fond of FogBugz which also has a great estimating and task completion system which will give your boss even more certainty that you are tackling things in a well-managed manner.

edit

Wow, someone really didn't like this - a downvote AND a delete flag? Why?

I've been developing software for over thirty years including a lot of consulting work and inheriting other people's code. A huge number of the problem systems I've seen have been where people dug a pit and didn't have detailed notes on how they got there nor did they have version control.


问:
ASP.NET MVC - Dynamic Views with many similar controls
I have a main View which has several sections and a main dropdown at the top which defines how the rest of the view looks like.
All these sections have some data that is visible all the time, and some that need to be hidden when certain values are chosen in the main dropdown.

As of now, I have partial views for each section, and I am having lots of if/else statements in my view to show/hide the specifics, which is getting clumsier by the day.

答:
My personal favorite would be to use knockout to accomplish this kind of page manipulation through a two-way binding with some kind of "security" class. I use quotes here because it really isn't security so much as it's just interface manipulation. Security should always be handled server side. However, with a good knockout model you would be able to use nomenclature as simple as data-bind="visible: displayModel.IsSpecialRole", and simply by updating the model you'd be able to have full control of each element. It's very simple to manage, and it is very simple to apply AJAX to make it even more dynamic.

Failing the usage of that, another technique that might be simpler to deploy would be a common display class that you insert into the ViewBag. I'm not a proponent of the ViewBag, I find it clumsy, but it would certainly be useful here. You could create a method or series of methods whose job would be to output the html attributes collection based on your conditionals. One of the outputs could be a css class that specifies only display: none to make sure it is not displayed on the page even if it is produced. This would still deliver html to the client side, but it would not be visible or usable to the client.

A third alternative available to you would be to create your own HtmlHelper extension method that accepts the arguments you need to base your conditional decisions on. It's return would be the rendered output of any actionlinks or raw html that would be produced. You have to be careful, though, to make sure that the extension doesn't generate anything that would be part of the template. It should only generate simple elements with css class attributes and default element attributes (src, href, etc.). The only real benefit to doing this would be that your conditionals would be abstracted into the extension method and your element definitions in your template would look simpler. A drawback is that your conditionals would be abstracted into the extension method. This may obfuscate the behavior for future developers/maintainers.


问:
Is it useful to keep 'definition' entities in a database vs using an enum?
In a project that I have started working on, the database has a lot of FooDefinition tables which act like an enum. It's a C# project using Entity Framework although that is not central to the question.

The entities have an ID, a string Name field and an int Type field that is converted to an enum. For example:

```<code>public class FooDefinition
{
    public int Id { get; set; }
    public string Name { get; set; }
    public FooType FooType { get; set; } // this is an enum that defines the entity
}
</code>```

The FooDefinition table is populated with an entity for each defined enum value, and does not change unless there is a new enum value added.

I am struggling to see the use in this pattern over just using the enum directly as opposed to joining on this Definition table. What are the possible benefits of this approach?

答: The main benefit I see is that you can add new enum values with a database operation, without compiling and deploying a new version of your application.  By treating the set of "Foos" which may exist as data, the impact on the running application of adding new types of "Foo" is kept small.</p>


问:
Is recursion an instance of being "too clever" when programming?
I've read several books and learned through experience that optimizing code to the point where it is inscrutable, or coming up with an extremely fast but extremely complex solution to a problem is not desirable when working in teams, or even when you're working by yourself and have to understand your clever solution some time later.

My question is, should recursion be treated in the same manner?  Does the average programmer understand recursion easily and thus one should use it with impunity, or does the average programmer not understand recursion very well and one should stay away from it for the sake of overall team productivity?

I know there are simple answers of, "Any programmer who doesn't understand recursion isn't worth a grain of salt, so don't worry about them" but I was wondering if you all had some real world experience you would like to share that would illuminate the issue more than the opinion I just mentioned.

答:
Recursion, is the simplest mechanism from a code cleanliness standpoint. If speed is absolutely of the essence, then perhaps you can use a 2D array of problem parameters. Spawning a daughter process is then simply appending another item to the array. I once did an assembler tridiagonal solver, that was a big deal back in the day. The context needed per instance was 8 words per level, and each subproblem was a third the size of the previous. This "library" was only popular because it beat the heck out of all the other implementations out there. But, that's a pretty rare situation in programming, so you needn't succumb to "premature optimization", just because this solution is available. Obviously for a few things its terrible overkill, like the recursion 101 example "compute the factorial". But for most apps, it is a really elegant way to eliminate source code complexity.

I have a simple spell-checker I use for an app, (where I want to give hints about correcting minor misspellings), where I compute the "distance" between two strings, allowing deletions and additions are allowed. This leads to a potentially large tree structure, and the branches are trimmed as we only care about close matches. With recursion, its maybe twenty lines of code (I have both Fortran and C versions). I think it would be messy otherwise. Heck it was much easier to program/debug verify, than it was to think about that tree!

ContentLicense: CC BY-SA 2.5


问:
In BDD, going from feature to user story how does it works?
My background is the book BDD in action.

How one goes from Feature to Stories? More specifically I would like to understand the following:

1- When does one provide the decomposition into stories? Do you do it while spotting the examples that illustrate your feature ?

2 - If so how do you proceed in your development then: Do you first start to on work on the stories while leaving your feature pending ? Do you right the feature scenario first and then, move on the stories that comes out of it, while leaving the feature test pending ?

The key here is the process, if i do a decomposition of a feature into stories, before writing my actual scenario that spot those stories, i might be writing stories that are not relevant to the feature isn't it?

This though make me think that stories must be fleshed out in the same way as unit test/integration test are fleshed out of a user stories?

However if one does that well it is difficult to plan a feature for scrum iteration.

I understand that it is just a planning tool, but it would be interesting to understand how this planning is actually used in the context of dealing with a feature.

I believe one should not do too much upfront planning, not commit to things without being sure, but in the mean time, it seem to me that the decomposition into the different process (stories) involve into the feature process requires some upfront planning.

I would appreciate a clarification on that point.

答:
Ultimately, user stories translate into software requirements, and so do features.

All high-level descriptions of software should ultimately translate into individual software requirements that are Specific, Measurable, Assignable, Realistic, and Timely.  If you get this right, then you're doing it "correctly," assuming your requirements gathering process is sufficiently thorough.

A user story is one or more sentences in the everyday or business language of the end user or user of a system that captures what a user does or needs to do as part of his or her job function.  Typically a User Story takes the form:

```<code>"As a <role>, I want <goal/desire> so that <benefit>"
</code>```

For example:

As a Customer Service Representative, I want to search for my customers by their first and last names, so that I can find them in the system if they don't know their account number.

This translates into the requirement:

The Customer Service screen shall provide the capability to look up customers by first and last name.

User Stories don't necessarily have to derive from features.  Most customer service representatives already know that they need a tool to look up customers, irrespective of any feature list that may or may not be created yet.

Further Reading

User Stories

Body:
Ultimately, user stories translate into software requirements, and so do features.

All high-level descriptions of software should ultimately translate into individual software requirements that are Specific, Measurable, Assignable, Realistic, and Timely.  If you get this right, then you're doing it "correctly," assuming your requirements gathering process is sufficiently thorough.

A user story is one or more sentences in the everyday or business language of the end user or user of a system that captures what a user does or needs to do as part of his or her job function.  Typically a User Story takes the form:

"As a <role>, I want <goal/desire> so that <benefit>"

For example:

As a Customer Service Representative, I want to search for my customers by their first and last names, so that I can find them in the system if they don't know their account number.

This translates into the requirement:

The Customer Service screen shall provide the capability to look up customers by first and last name.

User Stories don't necessarily have to derive from features.  Most customer service representatives already know that they need a tool to look up customers, irrespective of any feature list that may or may not be created yet.

Further Reading

User Stories


问:
Web Service REST clarification
I'm new to web-service programming, and I'm unsure of a few things. I know that REST web-services can be used to interact with the system like this:

to retrieve a user: GET /user?id=1

to retrieve all users: GET /user

to insert a user: PUT /user?{all user data}

When I need to do an update action for some tables using a JSON object can this be done with a REST API or does it need to be some other interface? If is REST, what is the right method (GET, POST, DELETE, etc) to use?

Is it correct to have two type of patterns in the same web-service?

答:
Before I answer your question, a couple of points about your example:

REST is based on resources, so the ID for e.g. a User resource would usually be part of the resource path (rather than a URL query parameter):

GET /user/1

Inserting is adding an entity to a resource collection, so to insert into e.g. a User collection you'd usually use something like:

POST(with user data in request body) /user/

Now to answer your question, updates are modifications to existing resources, so are usually accomplished with something like:

PUT(with user data in request body) /user/1

The Wikipedia article on REST is a good high-level reference on the subject; in particular, see the Applied to web services section.

There are several good Stack Overflow questions on the topic, one of which is this one from 2010.

Title: Web Service REST clarification


答:
The answer is that getters and setters give the library writers the flexibility to change the internal workings of their library without requiring users of that library to recompile every time a change is made. This area is called Binary or Behavioural Compatibility, and is one of the basics of Software Engineering and came about because exposing the internals of a class can quickly become a maintainence nightmare.

THere's unlikely to be any peformance benefit either in directly accessing a field instead of through a getter, unless your HotSpot compiler is sub-standard.

There are certain cases, e.g. small classes, where is can be considered unnecessary.

Renaming a final field and introducing a getter instead is a BC break. It will require the users of you library to recompile which will just piss them off (I've worked in situations where we were not allowed break BC, or there'd be legal ramifications)

As for making everything immutable and making a copy when a change is needed... try sorting an array with that logic. Immutability comes into play with concurrency when threads share data, but there's a lot more to it than just making everything immutable.

Your question is really a moan about why Java isn't Scala, and well the answer to that is that it's because it's Java.


问:
Comparing two software versions in C#
I´m working on a mod update checker for minecraft, but there is a big problem: The modders and online database that I´m using for update checks has no standard software versions e.g.:

```
Local: rv0-stable-10 Online: rv1-alpha-13
Local: R1.1-83 Online: r1.1-81
Local: 1.7.10-0.2.250 (1.7.10 is indicating the Minecraft version) Online: 0.2.274
Local: 1.1.0c Online: 1.1.0e
Local: 2.2.526 Online: 2.2.526-experimental
```

Is there an algorithm or something like that, that is able to compare such different versions?

答:
I'd say your best bet is to create some sort of pattern for either each mod, or a dictionary of all known patterns, and use that to parse each version.

For mod1, Local: rv0-stable-10 Online: rv1-alpha-13, the pattern will be complicated. It looks like you'll need to first parse rvX- as a number, the middle part perhaps as an enum, and the last as a number again. That can be your first pattern class.

Ones like Local: 1.1.0c Online: 1.1.0e should be easier, since the alphabetic component can easily be treated as a number.

For random -experimental and 1.7.10- affixes, you'd probably need to decide how you want to treat them yourself - but an experimental version should generally be treated as a lower number than the same number without experimental.

Overall, you may end up creating several strategy classes to cover all the comparisons. (They could probably be IEqualityComparer instances, which would make some things easier!) I'd give each mod a comparison class (maybe save the comparison/modname mapping to a file)

Overall, It may not be as bad as you might expect.

Title: Comparing two software versions in C#


问:
Purest functional programming language(s)?
I'm interested in better learning functional programming. To do so, it seems obvious that I should force myself to use the purest possible functional programming language. Hence, I'm here asking, more or less, for an ordering of functional programming languages according to their purity.

It seems to me that it would be more practical to learn Lisp or Clojure (or Scheme, or Scala, etc.), but for what I've heard recently, Haskell would be very hard to beat at teaching functional programming principles to someone. I'm not sure about this yet, so I'm asking you: which is the purest functional programming language? An ordering would be great if several are competing for the magnificent title of the purest functional programming language.

答:
Erlang, Haskell, Scheme, Scala, Clojure, and F#

This question would probably best you help you in your search as well.


答:
I see three reasons

1) As jimwise says, they can be changed without recompiling.
If they are actually used as enum values in application (do something if it equals that), only usefull thing to change without recommpiling is their name.

2) they CAN contain more than name and id, but two cannot have same id unlike C# style enums

3) they can be used in queries/views to make results more human readable.
Its better to see request with state failed than with state 3.

Title: Is it useful to keep 'definition' entities in a database vs using an enum?

Body:
In a project that I have started working on, the database has a lot of FooDefinition tables which act like an enum. It's a C# project using Entity Framework although that is not central to the question.

The entities have an ID, a string Name field and an int Type field that is converted to an enum. For example:

```<code>public class FooDefinition
{
    public int Id { get; set; }
    public string Name { get; set; }
    public FooType FooType { get; set; } // this is an enum that defines the entity
}
</code>```

The FooDefinition table is populated with an entity for each defined enum value, and does not change unless there is a new enum value added.

I am struggling to see the use in this pattern over just using the enum directly as opposed to joining on this Definition table. What are the possible benefits of this approach?


问:
How reduce the usage of Magic Strings?
In the application database there is a configuration table with this schema:

Table: ReleaseProperty

ReleasePropertyID

ReleaseID

Name

Value

Currently to retrieve a specific property I pass to the Repository class the arguments ReleaseID (that come from the current web page address) and a Name, that is basically hard coded

E.g.

```<code>var property = ReleasePropertyRepository.Select(ReleaseID, "MyProperty");
</code>```

I don't like to use hard coded strings around my code, and the only idea to improve the quality of this code is to use a container class for constants.

```<code>var property = ReleasePropertyRepository.Select(ReleaseID, Constants.MyProperty);
</code>```

Is there any other way to develop a better code?

答:
Hardcoded strings are not a problem. Let them be.

What you should have though is functions wrapping the queries so each of the identifiers is only used once in the code.

If you have more than one place where you need the strings, creating constants for them makes sense, because the compiler will make sure that they are consistent. But if you have one place in code and one place in the database, the compiler won't be checking anything if you make constants, so the only thing constants will give you is more lines of code, (probably) extra source where the constants will live and more places to change whenever the constants need to change (because you want to change both the value and the name of the constant every time; in this case you need to know the actual string, so letting the symbolic name and text diverge would make things worse). And they'll win you exactly nothing, because checking against the database (or configuration or whatever) will still only happen in tests and/or at runtime.

The usual advice against hard-coded values is about values where the meaning of the value is not obvious from the value and can be made obvious by introducing a symbolic constant or constants that appear in multiple places where have to be kept consistent. Meaning of keys in configuration or property table is obvious from the value and usually don't appear in many places, so the advice does not apply.

Or, more succinctly, if you have more descriptive name for the value, or if you can make the actual value strongly typed, make a symbolic constant. If the symbolic name would derive from the value, don't.

… you seem to have the later case.

Title: How reduce the usage of Magic Strings?


问:
Eliminating Magic Numbers: When is it time to say "No"?
We're all aware that magic numbers (hard-coded values) can wreak havoc in your program, especially when it's time to modify a section of code that has no comments, but where do you draw the line?

For instance, if you have a function that calculates the number of seconds between two days, do you replace

```<code>seconds = num_days * 24 * 60 * 60
</code>```

with

```<code>seconds = num_days * HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE
</code>```

At what point do you decide that it is completely obvious what the hard-coded value means and leave it alone?

答:
I would avoid creating constants (magic values) to convert a value from one unit to other. In case of converting I prefer a speaking method name. In this example this would be e.g. DayToSeconds(num_days) internal the method don't need magic values because, the meaning of "24" and "60" is clear.

In this case I'd never use seconds / minutes / hours. I would only use TimeSpan/DateTime.


问:
Why doesn't the HTML\DOM specification allow hyperlinks to set an accept header?
The purpose of the Accept header from the client is to tell the server what kind of data it will accept as a response to its request. We can set this header in asynchronous HTTP calls in Javascript, but not in HTML.

For example, consider a link such as Get as CSV. If an attribute like accept="text/csv" were allowed, and the browser interpreted that to send an Accept: text/csv header with that request, the server could respond to the semantics of the request. Without it, we might create a link such as Get as CSV, and the server must respond to the arbitrary query string parameter instead.

What are the reasons, both technical and historical, behind the HTML\DOM specification not allowing the setting of an Accept header through markup?

答:
The primary answer is that a link in a web page is intended to be rendered as a web page. If the web server returns some type other than a renderable page (image, downloaded file, etc), then the content might be rendered by the browser or not (it might be saved as a file).

There is no way for a link in a web page that leads to a CSS file or a JavaScript file, etc, to be properly rendered in a browser.

To achieve whatever it is you are trying to achieve (you didn't say), you can create a link that invokes a JavaScript function that provides the extra functionality you need.


问:
Desktop to Web - How to deal with user-interactive workflows
I start a new project this summer, consisting in developing a web version of a proprietary desktop ERP.

The main goal of my company is to be able to propose a web version of its ERP, with all advantages it involves (mobility, possibility of selling SaaS versions, modern look and components ...), without losing any business feature.  By this, I mean that us developers can't rework the business side of the app. The main goal is to be able to translate same processes into web application.

Business layer of the older version is not directly reusable, since it's really GUI-dependent. Those business process were rewritten as UML diagrams, which will be used as support for us to develop the new app.

The problem I meet is that I don't know how to deal with process that need user interactions. For example :

On validation of a sale order, the validation process checks all products it contains, verifying if there is available stock, and then perform different operations. If there is no stock available, the user is asked if he wants to cancel the order, remove this product or select another one equivalent. It works like a Javascript alert or confirm : current "thread" (ie validation process) is on hold, waiting for user interaction. After user's choice, it finishes dealing with the current product, and then validates the next one, and so on.

How to deal with this kind of processes with a web application ? Is there some framework, design pattern or something else that permits to write this kind of business processes, able to start and hold like that ?

A solution could be to split those business processes into smaller ones. For my example, we would have 2 sub-processes : the first one checks all products and flags the problematic ones. Then the user has a screen to decide what to do on flagged products, and validates. At this moment we are sure all products are OK, we can start the second sub-process to perform the others operations.

The problem with it is that even if it's pretty simple on this example, it can be really more complicated. Some process have a lot of users interactions like this one, and then could be splitted into 10 subparts. Like I earlier precised, we don't want to modify or rethink business process, to be sure that we lose nothing or introduce new business bugs.

Does someone has an experience about it ? Do you know some way to deal with this kind of desktop-to-web developments ?

EDIT 15/07/14

There was some misunderstanding about this post, surely related to my poor english expression and vocabulary.

To summarize the problem :

I got a bunch of business workflows described into UML diagrams. They comes from a huge 30-year-old CAMM (production management ERP). The project is to redevelop this application under Java web environment.
The main point is that some of those workflows are user-dependent, since, in the middle of the processing, they need a user-interaction. Because web applications are based on a client-server architecture, I don't know how to port them.
Reworking/rethinking these workflows is not an option, because it would be too much time-consuming. I need a way to simulate a desktop application on a web app, like Wt, but for Java (i'm not talking about UI but about how to develop workflows ), or to define rules to make those user-dependent workflows web-compatibles.

答:
This http://www.unigui.com/ seems relevant. This seems also close https://forums.embarcadero.com/thread.jspa?messageID=510208&tstart=0. I guess your old "business layer" code is written with Borland tools, either C++ or Delphi?

Some decade ago I was porting lots of legacy code from 16bit DOS (Turbo Pascal) to 16bit DPMI (Borland Pascal) and to 32bit Windows (Borland Delphi). In order to port the DOS part as-is without breaking anything (rewriting the code was not an option, just small refactorings) first thing I had to do was to create a "DOS terminal emulator" placed as a component inside a Windows GUI surrounded with 32bit Win32 API and new Windows components etc. Though it seems different, the way DOS application works with user input through modal dialogs etc. is totally different from how Windows event queues work. The emulator arranged things by running the DOS emulator in separate thread - all user I/O functions redirected to the emulation layer which in turn suspended the DOS thread when waiting for an Windows event. The DOS code and its logic was not changed (broken) at all.

In your case you can also get out gracefully by first creating(using) an emulator like JSC C# → JavaScript http://jsc.sourceforge.net/examples/web/CardGames/fx.FreeCell.htm. Once you can run your application "in the browser" you can add the required advantages ("..mobility, possibility of selling SaaS versions, modern look and components ...") one by one

I don't know which technology would be best suited for your legacy server-side language (the GUI-dependent business layer). But the running in the browser technology is already here, building on asm.js as the web processor, see e.g. https://isocpp.org/blog/2013/03/cpp-to-javascript or quite long list of tools that can be used to convert legacy code to be run in the browser at https://github.com/jashkenas/coffeescript/wiki/List-of-languages-that-compile-to-JS


答:
There's no scale for assessing the degree of purity of functional languages. If the language allows sideeffects it's impure, otherwise it's pure. By this definition, Haskell, Mercury, Clean etc are pure functional languages; whereas Scala, Clojure, F#, OCaml etc are impure ones.

EDIT: Maybe I should have phrased this as "if language doesn't allow side-effects without letting the type system know, it's pure. Otherwise it's impure.".

Title: Purest functional programming language(s)?

Body:
I'm interested in better learning functional programming. To do so, it seems obvious that I should force myself to use the purest possible functional programming language. Hence, I'm here asking, more or less, for an ordering of functional programming languages according to their purity.

It seems to me that it would be more practical to learn Lisp or Clojure (or Scheme, or Scala, etc.), but for what I've heard recently, Haskell would be very hard to beat at teaching functional programming principles to someone. I'm not sure about this yet, so I'm asking you: which is the purest functional programming language? An ordering would be great if several are competing for the magnificent title of the purest functional programming language.


问:
Database design with "draft" version of data
The database I'm currently building is pretty traditional relational database stuff, but there is one requirement that is not clear to me how model appropriately.

There are many business rules which are translated into database consistency checks (i.e. date A must be between date B and C or this field must be not null when another field is a specific value). My problem arises because a user must be able to work on a "draft" version on the data, being allowed to save their changes even if the consistency checks fail.

Eventually, a user can commit their draft, but only once all the consistency checks pass.

The main reason the client wants this functionality is so that they can query the database directly for reports, and be sure that they are using the most recent version of the data that is "consistent", but not restrict the user from entering partial data.

I've played around with storing the changeset to the data in JSON in a document store, and then applying the changeset in code when dealing with the user is dealing with draft data, but this makes it hard to manage things like relationships and the creation/deletion of records.

Is there a common way to accomplish this goal? Or does anyone have any suggestions about how I may approach this problem differently?

答:
Use some sort of identification field for draft mode (IsFinal) on your records. This value can then be taken into consideration when applying any finalization criteria:

```<code>If IsFinal then //do a bunch of checks
</code>```

You can do this in your code, database constraints or triggers.

Body:
Use some sort of identification field for draft mode (IsFinal) on your records. This value can then be taken into consideration when applying any finalization criteria:

If IsFinal then //do a bunch of checks

You can do this in your code, database constraints or triggers.


答: This is going to sound crazy but I'd create a separate service that stored the data in another set of tables, but this other set of tables had no integrity checking. The user would do all the partial work there, and when they were ready you could move their data into the checked schema in a single transaction.</p>

Title: Database design with "draft" version of data

Body:
The database I'm currently building is pretty traditional relational database stuff, but there is one requirement that is not clear to me how model appropriately.

There are many business rules which are translated into database consistency checks (i.e. date A must be between date B and C or this field must be not null when another field is a specific value). My problem arises because a user must be able to work on a "draft" version on the data, being allowed to save their changes even if the consistency checks fail.

Eventually, a user can commit their draft, but only once all the consistency checks pass.

The main reason the client wants this functionality is so that they can query the database directly for reports, and be sure that they are using the most recent version of the data that is "consistent", but not restrict the user from entering partial data.

I've played around with storing the changeset to the data in JSON in a document store, and then applying the changeset in code when dealing with the user is dealing with draft data, but this makes it hard to manage things like relationships and the creation/deletion of records.

Is there a common way to accomplish this goal? Or does anyone have any suggestions about how I may approach this problem differently?


问:
Why use getters only as opposed to marking things final?
I'm working in a java role after working a couple years in functional programming. Our company was bought by google and I took a java role after the acquisition.

Coming back to java as a polyglot developer, I'm generating getters for immutable objects and I'm seeing it's a total hogwash.

Are there any reasons why the 'getField' convention should be used so prolifically? To me it seems almost horrifying at this point that so many libraries expect public getter methods to work with their functionality when simply making a field public and final would have the same effect as making only a getter on a public mutable field.

Why isn't it more of a common practice to ditch the setters and just expose a final field?

答: I think a serious part of the answer is that Java developers are used to the convention of using getters and setters. If you use a different style, other Java developers will have a somewhat more difficult time reading your code. Considering that the convention doesn't really cost anything in terms of performance or maintainability, I believe that the increased readability is worth it.</p>


问:
Best practices / reasons for String constants in JavaScript
In static languages like Java/C#, I commonly make use of constants for strings or numbers, rather than insert them into the code alone. However, I tend to avoid this practice in JavaScript. More recently, as some other coders around me have taken this approach in JS, I decided I should probably solidify either my, or their, reasoning.

There is no actual "const" declaration syntax in JavaScript. We usually just settle for an informal policy of not changing uppercase properties. But my opinion is usually to avoid them altogether, because most of their benefits are lost in JavaScript. In Java, a misspelt string will cause the program to fail when you try to run it, at which point you correct it and move on. Having a static checker where both instances are pointing to the same constant eliminates that problem, as it can be found at compile-time. But JavaScript will simply have that problem all over the place, as you're ALWAYS going to discover your spelling's correctness at run-time:

```<code>Library = { doThing: function() }
setTimeout(function()
  Liberry.doThing()
  // No such object: Liberry
}, 0);
</code>```

The best safeguard against this, usually, is "use strict". For developers that prefer it, I'm fine with them using that to find issues with undeclared variables more quickly. But my opinion has been that providing string constants for REST APIs, etc., doesn't actually safeguard you against anything. Another example:

```<code>CompanyAPI.constants.ENROLL_URL = "/rest/enroll";
CompanyAPI.constants.FIRST_NAME = "firstName";

ajax({url: CompanyAPI.constants.ENROLL_URL,
data: CompanyAPI.constants.FIRST_NAME
});
// vs.
ajax({url: "/rest/enroll",
data: "firstName"
});
</code>```

...You meant to write the above, but then made typos. Whoops.

```<code>ajax({url: CompanyAPI.constants.ENROL_URL,
  data: CompanyAPI.constants.FIRS_NAME
});
// vs.
ajax({url: "/rest/enrol",
  data: "firsName"
});
</code>```

The constant-based one will still provide undefined, while "firsName" is no better. To that end, I tend to just see this as a benefit of static languages, and not bother having a system to fix it (besides maybe starting to use "use strict" for debugging). Can some other people tell me what their preferred practice for string/integer constancy is?

EDIT: To clarify, my preference is usually to put strings like "firstName" directly inline with no top-level constant declaration - the penalties for misspelling it are the same either way. Strings that might get long, like a REST URL, I'll tend to define at the top of the file.

答:
Just like learning another language, one shouldn't compare it to his/her mother tongue. Some Languages often have concepts that are not found in others. We simply learn to accept them.

Constants in Java, C# and C++ do not exist in binary code. These constants were invented to help programmers and compilers. As this answer (https://stackoverflow.com/questions/130396/are-there-constants-in-javascript) says "Nothing's ever constant"

Therefore, the answer to your questions is in the Naming Convention and Code Review.
You and your team will need to define how to name constants, agree that constants will not be modified, and use the code review as a way to enforce the rule. At the end of the day, it does not matter which way you decide to go, it will not be fool-proof.

My Preferred way of dealing with constants is

```<code>var NAMESPACE.CONSTANT = 1;
</code>```

Body:
Just like learning another language, one shouldn't compare it to his/her mother tongue. Some Languages often have concepts that are not found in others. We simply learn to accept them.

Constants in Java, C# and C++ do not exist in binary code. These constants were invented to help programmers and compilers. As this answer (https://stackoverflow.com/questions/130396/are-there-constants-in-javascript) says "Nothing's ever constant"

Therefore, the answer to your questions is in the Naming Convention and Code Review.
You and your team will need to define how to name constants, agree that constants will not be modified, and use the code review as a way to enforce the rule. At the end of the day, it does not matter which way you decide to go, it will not be fool-proof.

My Preferred way of dealing with constants is

var NAMESPACE.CONSTANT = 1;


答:
I'm a big proponent of immutable domain objects as well, and have seen cases where encapsulating the field with a getter has sure come in handy.

One point to note is that the immutability of an object can be pretty useless if it's only so in a shallow way.

To illustrate the point, consider a class that has a final field (private or not) of type Date. Now the point of immutability is that your object won't change; it could be passed off to other methods, cached, shared around across threads, etc., without fear of anything changing.

But, consider if someone gets a hold of that date field. I'm not saying that Jimmy is malicious or stupid, but he can do some pretty surprising things, and there's no guarantee that he's not going to call date.setTime on that puppy.

So, what do you do? You use encapsulation. You make the field private and exposing it through an accessor (getter), which instead of returning the stored data object, creates a copy with the same value. Oh, and you do the same thing in your constructor (you wouldn't want Jimmy to hold on to the reference he passed in and do more malicious/stupid/surprising  things, would you?)

Okay, so now you expose, say, 7 fields directly, and one via an accessor. And Jimmy comes along and wants to use your API, and, well, what the hell is going on? Is this guy giving me the fields directly? Or wrapping them in methods? Some of each? Can't we just be consistent, he wonders?

And in this case, yeah, I have to agree with Jimmy.


问:
Handling leaves in tree-based menus
Tl;Dr

Given a language with no polymorphism how to you elegantly modify the behavior of a leaf in a tree data structure.

Context

I'm programming an application in C for a microcontroller and I'm wondering what would be the best way to design flexible GUI-less menus.

Basically inputs may come from 2 different sources: The built-in buttons on the board used by the user and a Uart port used by the production team to calibrate the device before shipping.

I already have a mechanism using a thread to listen to inputs (from both the buttons and the serial port) who post them to a crude parser. The parser then takes action depending on the currently registered callback for the received input. It also knows if the menu must be printed on the LCD screen or through the serial port.

I'm also using a k-ary tree to represent the hierarchy between sub-menus and different options. Since the menus are not defined yet it'll allow me to simply add / remove nodes when my supervisor makes his mind on the supported features.

Now when the currently displayed menu is not a leaf, the behavior is quite simply. Left and Right moves between siblings, Back selects the parent and Enter selects the first child.

If its a leaf, Enter activates / deactivates modifications, Left and Right increment / decrement the value and Back cancels the moficiation.

Other concerns

Am I over-engeenering stuff that could be done with a bunch of
switch-cases?

Are there ressources giving example of clean GUI-less menus when you don't
know where the inputs come from, the actions you will have to take, the menus you must offer and where to display those menus?

Since there is basically 2 options (leaf or not) should I just do
everything with if/elses and move on?

答:
The answer to this kind of question is always the same: if the language doesn't provide a useful abstraction, you must emulate it. (Whether doing this is worth the additional effort depends on the specific circumstances of your program, which you know better than we do, but for the purposes of this answer I'm assuming that it is.)

Polymorphism is the ability of objects of related classes to behave differently in response to the same message, and language implementers usually provide it by keeping type/class information associated with each object instance and consulting it when dispatching a message. So that is what you'd have to do yourself: implement a notion of "I'm a leaf"/"I'm an inner node" that an object can consult and change its behaviour accordingly. That can mean a type flag and switch statements in the appropriate places, but any other language construct that achieves the same could be used.

Such a solution can become inelegant as the program grows and a good illustration of why polymorphism was raised to the level of language feature in the first place, but it doesn't have to be. One example is the implementation of the virtual file system in the Linux kernel; despite the fact that it's pure C, i.e. with no class-related features, it allows adding new file systems very easily, and it's also reasonably easy to read (via C macros) and even a lot more efficient than the obvious C++ solution would be. (Greg Kroah-Hartman describes this in detail in his chapter of Beautiful code, so he thinks it's rather elegant indeed.)

Title: Handling leaves in tree-based menus


答:
Switch cases are still a viable option for such limited scenarios(it is doubtful that your tree navigation will ever change so radically, that switch case won't be able to handle it). It is the simplest solution, but not nesessarily the best.

So, I could recommend you to use pointer-to-functions to implement some sort of polymorphic behaviour:

```<code>struct TreeElement
{
    char* DisplayName;

    void (*Enter)(void);

    void (*MoveToPrevious)(void);

    void (*MoveToNext)(void);
}

ReturnCode TreeElement_Leaf_Initialize(TreeElement* leaf, char* displayName ...)
ReturnCode TreeElement_Node_Initialize(TreeElement* node, char* displayName ...)
//...
treeElement->Enter();
</code>```

Well, you should think which functions(pointers-to-functions) exactly you would really need, but this solution is quite generic and will allow you to easily modify element behaviours and avoid huge switch-cases.

3.
If your project is going to need something more powerful, than you may want to read this SO thread about how to turn your C program into C++ -like framework. Especially you may want to read this book.

P.S. Proposal 3 could easily become an overkill for most projects, so it should be used only for really complex projects for which C++ compiler cannot be used.

Title: Handling leaves in tree-based menus

Body:
Tl;Dr

Given a language with no polymorphism how to you elegantly modify the behavior of a leaf in a tree data structure.

Context

I'm programming an application in C for a microcontroller and I'm wondering what would be the best way to design flexible GUI-less menus.

Basically inputs may come from 2 different sources: The built-in buttons on the board used by the user and a Uart port used by the production team to calibrate the device before shipping.

I already have a mechanism using a thread to listen to inputs (from both the buttons and the serial port) who post them to a crude parser. The parser then takes action depending on the currently registered callback for the received input. It also knows if the menu must be printed on the LCD screen or through the serial port.

I'm also using a k-ary tree to represent the hierarchy between sub-menus and different options. Since the menus are not defined yet it'll allow me to simply add / remove nodes when my supervisor makes his mind on the supported features.

Now when the currently displayed menu is not a leaf, the behavior is quite simply. Left and Right moves between siblings, Back selects the parent and Enter selects the first child.

If its a leaf, Enter activates / deactivates modifications, Left and Right increment / decrement the value and Back cancels the moficiation.

Other concerns

Am I over-engeenering stuff that could be done with a bunch of
switch-cases?

Are there ressources giving example of clean GUI-less menus when you don't
know where the inputs come from, the actions you will have to take, the menus you must offer and where to display those menus?

Since there is basically 2 options (leaf or not) should I just do
everything with if/elses and move on?

Body:
Switch cases are still a viable option for such limited scenarios(it is doubtful that your tree navigation will ever change so radically, that switch case won't be able to handle it). It is the simplest solution, but not nesessarily the best.

So, I could recommend you to use pointer-to-functions to implement some sort of polymorphic behaviour:

struct TreeElement
{
    char* DisplayName;

    void (*Enter)(void);

    void (*MoveToPrevious)(void);

    void (*MoveToNext)(void);
}

ReturnCode TreeElement_Leaf_Initialize(TreeElement* leaf, char* displayName ...)
ReturnCode TreeElement_Node_Initialize(TreeElement* node, char* displayName ...)
//...
treeElement->Enter();

Well, you should think which functions(pointers-to-functions) exactly you would really need, but this solution is quite generic and will allow you to easily modify element behaviours and avoid huge switch-cases.

3.
If your project is going to need something more powerful, than you may want to read this SO thread about how to turn your C program into C++ -like framework. Especially you may want to read this book.

P.S. Proposal 3 could easily become an overkill for most projects, so it should be used only for really complex projects for which C++ compiler cannot be used.


问:
How should I include jQuery in a library?
I'm writing a JavaScript graphing library using canvas which I am licensing under MIT, and I'm using jQuery, as well as a couple of other open sourced libraries, all under MIT. I'm also using bower to manage my front-end dependencies. How should I best handle these dependencies without violating the license?

Preferably, the user would not have to include multiple scripts, just one , and it would include all of the plugins.

Should I just ask the user to include jQuery and the other libraries in its own script tag, or should I concat all of the scripts together into one big file, headers included?

答:
Ignoring licensing, it is generally preferable to provide at least one version of your script that includes none of its external dependencies.  Some libraries include a wide variety of wrappers and bundles (e.g., HistoryJS) to make things easier on their users.

Complicated sites may or may not already include dependencies (and not necessarily the same version you'd include).

Users may wish to update your script without updating their other dependencies.

Popular dependencies are available on large CDNs. Users may prefer to download such dependencies from these CDNs, to leverage cross-site caching (i.e., users of my site can avoid downloading JQuery if both myself and others link to a copy on Google's CDN).

It's less effort to concatenate dependencies into a script than to split a script apart (and users who wish to do so may very well be using a framework which does so automatically).


问:
Ruby IDE code completion
I just started writing some ruby in my spare time and am currently using Netbeans 7 with the Ruby and Rails plugin v0.111. I'm primarily a Java programmer coming from IntelliJ and Eclipse.

One downside of my Ruby programming setup is that my Netbeans isn't very helpful when it comes to code completion. This seems due to the fact that Ruby is not strongly typed and since the IDE doesn't know the type it can't suggest methods. As a result I must spend a lot of time in my browser looking at documentation and switching back to my IDE to manually type in the method there.

Are there any changes I can make to my setup to get code completion for Ruby or is it pretty much impossible due to the nature of the language? How do other developers work with Ruby, other than memorizing all the methods in the Core Library?

答: A bit of a late submission, but Atom (by GitHub) has support for Ruby, as well as many other languages, including Puppet.</p>

Title: Ruby IDE code completion


答:
Sometimes something you get from an object is stored internally as a field, and sometimes it isn't. The example I use with my students is a Date class. It would be madness to represent a date internally as a separate day, month and Year; you just use the number of days passed since some reference day. This ensures consistency, and makes it easy to compare dates and do arithmetic.

Of course, from the perspective of the user of your class, it's a different matter. They want to know about the month and the year and so on. So you compute those on the fly and expose them with getters.

To me, this is the very heart of programming: make things easy for your users and (if needs be) difficult for yourself. This means working from the outside in. Set up the API that your user needs and then worry about how to implement it. And as usual, if you happen to be your own user, it doesn't change a thing. Every piece of code has a user and a developer.

So imagine you're a user, and you want to ask object foo for its bar. In your world, your have to stop to consider how foo is implemented. Is bar an stored explicitly as a field, or is it computed on the fly?

This isn't just about saving the user time, the fact that a user has to think about implementation details shows a seriously leaky abstraction. As others pointed out, this means that you can't just change bar from a field to a value that's computed on the fly. Saying you "have to recompile" doesn't do justice to the impact. You have to track down every piece of code that calls your class and figure out what the impact is. This could be in another company, in another country, and it could be a decade later.

Good coding means worrying about you interfaces, because nothing costs more than changing an interface. Getters are good interface design.


问:
When I test out the difference in time between shifting and multiplying in C, there is no difference. Why?
I have been taught that shifting in binary is much more efficient than multiplying by 2^k. So I wanted to experiment, and I used the following code to test this out:

```<code>#include <time.h>
#include <stdio.h>

int main() {
    clock_t launch = clock();
    int test = 0x01;
    int runs;

    //simple loop that oscillates between int 1 and int 2
    for (runs = 0; runs < 100000000; runs++) {

    // I first compiled + ran it a few times with this:
    test *= 2;

    // then I recompiled + ran it a few times with:
    test <<= 1;

    // set back to 1 each time
    test >>= 1;
    }

    clock_t done = clock();
    double diff = (done - launch);
    printf("%f\n",diff);
}
</code>```

For both versions, the print out was approximately 440000, give or take 10000. There was no (visually, at least) significant difference between the two versions' outputs. So my question is, is there something wrong with my methodology? Should there even be a visual difference? Does this have something to do with the architecture of my computer, the compiler, or something else?

答: The compiler recognizes constants and converts multiplies to shifts where appropriate.</p>


问:
Implementing IEnumerator without using 'yield return' in c#
I'm new to C# programming, I was experimenting with iterators concept in C#. Here, I'm trying to display all the terms in a list, for that I'm trying different ways to obtain the results. In the below code, I'm using two classes ListIterator and ImplementList.

In the ListIterator class : I defined a HashSet and it uses IEnumerator to store the values. Here GetEnumerator() method returns the values in the list. GetEnumerator is implemented in the ImplementList class (other class). Finally, the list is displayed in the console.

```<code>public class ListIterator
{
   public void DisplayList()
   {
    HashSet<int> myhashSet = new HashSet<int> { 30, 4, 27, 35, 96, 34};
    IEnumerator<int> IE = myhashSet.GetEnumerator();
    while (IE.MoveNext())
      {
        int x = IE.Current;
        Console.Write("{0} ", x);
      }
      Console.WriteLine();
    Console.ReadKey();
   }
}
</code>```

In the ImplementList class : GetEnumerator() is defined and it returns the list using yield return x.

```<code>public class ImplementList : IList<int>
  {
    private List<int> Mylist = new List<int>();
    public ImplementList() { }

    public void Add(int item)
    {
        Mylist.Add(item);
    }

    public IEnumerator<int> GetEnumerator()
    {
      foreach (int x in Mylist)
        yield return x;
    }
  }
</code>```

Now, I want to rewrite the GetEnumerator() without using yield return. And it should return all the values in a list. I tried using for loop as for(int x=0; x<Mylist.Count; x++), but it doesn't return all the values in the list.

Is it possible to get all the values in the list without using yield return in IEnumerator

答:
MoveNext() is a method that is called over and over and every time it has to move to the next item. This means you can't implement it by simply using a for loop (unless you use yield return, which is pretty much the reason why yield return exists), you need to rewrite it so that each MoveNext() call executes just part of that loop.

Specifically, it would look like this:

```<code>class Enumerator : IEnumerator<int>
{
    private int i = -1;
    private ImplementList list;

    public Enumerator(ImplementList list)
    {
        this.list = list;
    }

    public bool MoveNext()
    {
        i++;
        return i < list.myList.Count;
    }

    public int Current { get { return list.myList[i]; } }

    object IEnumerator.Current { get { return Current; } }

    public void Dispose() {}

    public void Reset() { throw new NotSupportedException(); }
}
</code>```

This way, every call to MoveNext() performs the i++ and i < list.Count parts of the for loop.

Body:
MoveNext() is a method that is called over and over and every time it has to move to the next item. This means you can't implement it by simply using a for loop (unless you use yield return, which is pretty much the reason why yield return exists), you need to rewrite it so that each MoveNext() call executes just part of that loop.

Specifically, it would look like this:

class Enumerator : IEnumerator<int>
{
    private int i = -1;
    private ImplementList list;

    public Enumerator(ImplementList list)
    {
        this.list = list;
    }

    public bool MoveNext()
    {
        i++;
        return i < list.myList.Count;
    }

    public int Current { get { return list.myList[i]; } }

    object IEnumerator.Current { get { return Current; } }

    public void Dispose() {}

    public void Reset() { throw new NotSupportedException(); }
}

This way, every call to MoveNext() performs the i++ and i < list.Count parts of the for loop.


答:
As said in the other answer, most compilers will automatically optimize multiplications to be done with bitshifts.

This is a very general rule when optimizing:
Most 'optimizations' will actually misguide the compile about what you really mean, and might even lessen the performance.

Only optimize when you have noticed a performance problem and measured what the problem is. (and most code we write doesn't get executed that often, so we don't need to bother)

The big downside to optimizing is that the 'optimized' code is often much less readable. So in your case, always go for multiplication when you are looking to multiply. And go for bit shifting when you want to move bits.

Title: When I test out the difference in time between shifting and multiplying in C, there is no difference. Why?

Body:
I have been taught that shifting in binary is much more efficient than multiplying by 2^k. So I wanted to experiment, and I used the following code to test this out:

```<code>#include <time.h>
#include <stdio.h>

int main() {
    clock_t launch = clock();
    int test = 0x01;
    int runs;

    //simple loop that oscillates between int 1 and int 2
    for (runs = 0; runs < 100000000; runs++) {

    // I first compiled + ran it a few times with this:
    test *= 2;

    // then I recompiled + ran it a few times with:
    test <<= 1;

    // set back to 1 each time
    test >>= 1;
    }

    clock_t done = clock();
    double diff = (done - launch);
    printf("%f\n",diff);
}
</code>```

For both versions, the print out was approximately 440000, give or take 10000. There was no (visually, at least) significant difference between the two versions' outputs. So my question is, is there something wrong with my methodology? Should there even be a visual difference? Does this have something to do with the architecture of my computer, the compiler, or something else?


答:
Constants do serve a error-checking function in statically-typed languages, but they also serve a second purpose. They centralize information into one place. This is not lost when we move to JavaScript.

Imagine that your example looks more like this,

config.js:

```<code>CompanyAPI.constants.ENROLL_URL = "/rest/enroll";
CompanyAPI.constants.FIRST_NAME = "firstName";
</code>```

enroll.js:

```<code>ajax({url: CompanyAPI.constants.ENROLL_URL,
    data: CompanyAPI.constants.FIRST_NAME
});
</code>```

special-enroll.js:

```<code>ajax({url: CompanyAPI.constants.ENROLL_URL,
    data: CompanyAPI.constants.FIRST_NAME
});
</code>```

need-to-enroll-from-this-other-place.js:

```<code>ajax({url: CompanyAPI.constants.ENROLL_URL,
    data: CompanyAPI.constants.FIRST_NAME
});
</code>```

goto-enroll.js:

```<code>redirect({url: CompanyAPI.constants.ENROLL_URL,
    data: CompanyAPI.constants.FIRST_NAME
});
</code>```

Notice how, now, these constants are showing up in files all over the place. If I wasn't using constants, I would have to find all the instances of that particular string, and replace them manually. Admittedly, there is duplication here, but notice that the last one is actually different. This means that even if we removed the duplication, we couldn't actually abstract this away. Now, because we are using constants, and CompanyAPI.constants.FIRST_NAME needs to change, we can change it in one and only one place, and it automatically changes everywhere.

If I'm using a string in only one place, and it is not configuration (ie, an array string index is not configuration), then I'll put it inline. If I find I'm using it in a few places close to each other, I'll look to refactor it into one use. If I cannot refactor, I would likely move it into a "class"-level constant.

Title: Best practices / reasons for String constants in JavaScript

Body:
In static languages like Java/C#, I commonly make use of constants for strings or numbers, rather than insert them into the code alone. However, I tend to avoid this practice in JavaScript. More recently, as some other coders around me have taken this approach in JS, I decided I should probably solidify either my, or their, reasoning.

There is no actual "const" declaration syntax in JavaScript. We usually just settle for an informal policy of not changing uppercase properties. But my opinion is usually to avoid them altogether, because most of their benefits are lost in JavaScript. In Java, a misspelt string will cause the program to fail when you try to run it, at which point you correct it and move on. Having a static checker where both instances are pointing to the same constant eliminates that problem, as it can be found at compile-time. But JavaScript will simply have that problem all over the place, as you're ALWAYS going to discover your spelling's correctness at run-time:

```<code>Library = { doThing: function() }
setTimeout(function()
  Liberry.doThing()
  // No such object: Liberry
}, 0);
</code>```

The best safeguard against this, usually, is "use strict". For developers that prefer it, I'm fine with them using that to find issues with undeclared variables more quickly. But my opinion has been that providing string constants for REST APIs, etc., doesn't actually safeguard you against anything. Another example:

```<code>CompanyAPI.constants.ENROLL_URL = "/rest/enroll";
CompanyAPI.constants.FIRST_NAME = "firstName";

ajax({url: CompanyAPI.constants.ENROLL_URL,
data: CompanyAPI.constants.FIRST_NAME
});
// vs.
ajax({url: "/rest/enroll",
data: "firstName"
});
</code>```

...You meant to write the above, but then made typos. Whoops.

```<code>ajax({url: CompanyAPI.constants.ENROL_URL,
  data: CompanyAPI.constants.FIRS_NAME
});
// vs.
ajax({url: "/rest/enrol",
  data: "firsName"
});
</code>```

The constant-based one will still provide undefined, while "firsName" is no better. To that end, I tend to just see this as a benefit of static languages, and not bother having a system to fix it (besides maybe starting to use "use strict" for debugging). Can some other people tell me what their preferred practice for string/integer constancy is?

EDIT: To clarify, my preference is usually to put strings like "firstName" directly inline with no top-level constant declaration - the penalties for misspelling it are the same either way. Strings that might get long, like a REST URL, I'll tend to define at the top of the file.

Body:
Constants do serve a error-checking function in statically-typed languages, but they also serve a second purpose. They centralize information into one place. This is not lost when we move to JavaScript.

Imagine that your example looks more like this,

config.js:

CompanyAPI.constants.ENROLL_URL = "/rest/enroll";
CompanyAPI.constants.FIRST_NAME = "firstName";

enroll.js:

ajax({url: CompanyAPI.constants.ENROLL_URL,
    data: CompanyAPI.constants.FIRST_NAME
});

special-enroll.js:

ajax({url: CompanyAPI.constants.ENROLL_URL,
    data: CompanyAPI.constants.FIRST_NAME
});

need-to-enroll-from-this-other-place.js:

ajax({url: CompanyAPI.constants.ENROLL_URL,
    data: CompanyAPI.constants.FIRST_NAME
});

goto-enroll.js:

redirect({url: CompanyAPI.constants.ENROLL_URL,
    data: CompanyAPI.constants.FIRST_NAME
});

Notice how, now, these constants are showing up in files all over the place. If I wasn't using constants, I would have to find all the instances of that particular string, and replace them manually. Admittedly, there is duplication here, but notice that the last one is actually different. This means that even if we removed the duplication, we couldn't actually abstract this away. Now, because we are using constants, and CompanyAPI.constants.FIRST_NAME needs to change, we can change it in one and only one place, and it automatically changes everywhere.

If I'm using a string in only one place, and it is not configuration (ie, an array string index is not configuration), then I'll put it inline. If I find I'm using it in a few places close to each other, I'll look to refactor it into one use. If I cannot refactor, I would likely move it into a "class"-level constant.


问:
Why does C have no competitors in low level stuff?
As far as I know, C is by far the most widely used language for low level stuff such as systems programming and embedded. Sometimes assembly is used, but that's when you really need to be close to the hardware.

My question is why doesn't C have any competitors in low level development? It might be my ignorance, but I'm pretty sure that C is the obvious (or possibly only) choice for low level programming.

This is as opposed to high level development, where there are many competing programming languages to choose from.

How can you explain this?

答:
(Source: embedded developer.)

First and foremost, you need a language that compiles to machine instructions, not some intermediate instructions (e.g., Python, Java). If your compiler builds to Java bytecodes, what runs the bytecodes?

The compiled to machine code requirement eliminates many, many high level languages.

Second, your language needs to compile to machine instructions of multiple platforms. OK, so Haskell can compile x86 and ARM. How about the other dozen CPUs out there?

C's linker gives me a crazy amount of power. I can put code in a specific location. Say my CPU starts up at 0x08000. I can tell the linker to store code at that location. I can tell the linker to store certain code in certain segments. The loader will put those segments in a specific location. That's useful if I have code I want to run out of flash vs code to run out of RAM. The Linux kernel puts startup code into a chunk of memory that is later freed, thus recovering memory from code that's only run once, ever.

I can call assembly from C and C from assembly. CPU startup is all in assembly. Low-low level stuff is done in assembly because the C environment might not be initialized yet! (Something has to call main().)  The very low level multiple CPU synchronization constructs (semaphores, mutexes, etc) are usually in assembly because they require specific CPU instructions. Caches, MMUs, etc, are usually configured in fiddly bits of assembly.  (ARM is loaded with specific instructions to configure cache, MMU.)

C is a thin layer about assembly. C is faster than assembly. So C wins for low level stuff. C wins because no one else has come up with a competitor.


答:
Use of accessors is convenient in the following cases:

When, during some hairy debugging, you need to keep track of who is accessing a given field. If there is an accessor method, it is trivial to add the relevant tracking code in that method; otherwise, this is a more complex and protracted game of searching throughout all the code which potentially accesses that field (or it could be done with some instrumentation magic, but that's hardly simple).

You might want at some point to save on memory, and replace your "final" field with a piece of code which recomputes the value dynamically, instead of keeping it around. Depending on the relative costs of CPU and RAM, this may be a worthwhile exchange -- and since it is a performance-related issue, it cannot be decided until actual measures have been made, i.e. quite late in the development process. At that point, changing an already existing accessor method is much easier than tracking all callers throughout the code base.

One important point is that Java was meant for big projects involving a lot of people; in such contexts, one cannot assume that recompiling the whole code is practical or even possible. Interfaces are where developer teams meet, and they are very hard to change. Modifying a field access into a method call is an interface change.

On the side of pure performance, Sun pretends that the JIT compiler is smart enough to inline calls to simple method, so that a trivial getter method actually costs nothing at runtime. Or so they say.

Of course, a convention is just a convention. The reasons above should be considered as arguments for using accessors generally, but that's not a dogma. It is more a reminder that the software development cycle is long, often involves a lot more people than initially envisioned, and short-term gains must be balanced against long-term costs. It is OK to use public final fields if that is fine for you; but remember that in any project involving more than one developer, you are not alone, and interface decisions impact everybody.


答:
I fully agree with the doubts and conclusions of the author of this question.

IMMO in java getters are mainly used because people like "rules of thumb" like "all fields must be private and have a getter" and really don't understand why its the real reason behind this.

Its really annoying when i see a java "bean" with N fields and getter&setters for all the fields, and the people do this because "its object oriented" when in fact this totally breaks encapsulation and creates coupling and more coupling with code like that:

```<code>  instance.getFoo().getBar().getFooBar()...
</code>```

Sometimes you don't need and object, you need a data structure, its perfectly right put all field public and finals.

Sometimes you want an object, if you really want an object why you expose internal state with a getter?. off course you want to ask for something to your object (normally i prefer a tell don't ask approach, but not always is posible) ask you object for that value, but this its not a getter, this its a method that an object expose to give some information to the outside world, and by any means this implies that this object has a property holding this value!.

IMMO the term "getter" its for me one of the most notorious symptom of the big misunderstanding of object orientation in the community.

Body:
I fully agree with the doubts and conclusions of the author of this question.

IMMO in java getters are mainly used because people like "rules of thumb" like "all fields must be private and have a getter" and really don't understand why its the real reason behind this.

Its really annoying when i see a java "bean" with N fields and getter&setters for all the fields, and the people do this because "its object oriented" when in fact this totally breaks encapsulation and creates coupling and more coupling with code like that:

  instance.getFoo().getBar().getFooBar()...

Sometimes you don't need and object, you need a data structure, its perfectly right put all field public and finals.

Sometimes you want an object, if you really want an object why you expose internal state with a getter?. off course you want to ask for something to your object (normally i prefer a tell don't ask approach, but not always is posible) ask you object for that value, but this its not a getter, this its a method that an object expose to give some information to the outside world, and by any means this implies that this object has a property holding this value!.

IMMO the term "getter" its for me one of the most notorious symptom of the big misunderstanding of object orientation in the community.


问:
How to prove that following practices and industrial standards are profitable, and investment in refactoring are good
I started working in a company not much time ago, and what I see a lot inside a project is a high amount of low quality code and some custom ideas instead of industry standards and selected best practices.

But when I trying to talk with manager about that, I often see the answers, that guys who doing that make things quick and they are good etc, etc, etc

答:
In the case of refactoring, for example: Refactoring takes time. Time costs money. Therefore, refactoring is only worthwhile if you get benefits from it that outweigh the refactoring cost.

Just after you have created a kind-of-working solution, that's the time when refactoring is cheapest (because you know the code inside out at that point), and can give immediate benefits if refactoring makes bugs visible and debugging easier, so you get to bug-free code faster.

The other time when refactoring is useful is just before or while you have to make changes anyway, if the existing code is sufficiently bad, and it is cheaper to turn bad code into good code and modifying good code than trying to understand bad code and modify it.

Refactoring code that nobody looks at is pointless.


问:
Do immutable objects that constantly change impact memory/performance?
I'm writing a program that goes into a loop and keeps changing the state of some models (similar to a game). Naturally, many things are mutable. However, I'm also writing some classes that are immutable because they're inherently treated like values (for example: vectors, matrices, etc.)

However, these values change on every loop (maybe 50-100 times a second). Does this mean that on every change, the program would need to allocate a new chunk of memory? If I'm using managed code, does this mean that the memory usage will build up very quickly? How does this impact determinism, performance, and garbage collection in languages such as C# and Java, especially when many garbage collectors have to pause the entire program in order to clear the memory?

答:
If you need something which behaves like a group of independent-but-related variables bound together with duct tape (E.g. the coordinates of a vector), use an exposed-field structure.  The fields of an exposed-field structure are mutable when the structure is stored in a mutable location, and immutable when the storage location is stored in an immutable location.

Because an open-field structure behaves like a bunch of independent-but-related variables, some people who think everything should behave like an object deride them as "evil".  I would posit that although open-field or otherwise-mutable structures are generally not suitable in places requiring something that behaves like an object, they are a perfect fit in places where one will need bunches of variables stuck together with duct tape.

It's possible to use immutable class objects to hold bunches of independent-but-related values.  It can even be advantageous in cases where composite values (i.e. particular combination of values) will be passed around much more frequently than they are created.  On the other hand, if code which holds a reference to a vector (34,39) wants to hold a reference to a vector whose x component is one larger, it won't be able to simply increment a field (as it could with a structure) but must instead create an entirely new vector object (35,39).  The performance cost of doing this won't be a problem if one never has to perform such operations repeatedly within an inner loop.  On the other hand, if a program would frequently execute significant loops whose primary purpose involves constructing slightly-modified versions of objects, the time required to construct such objects could become a substantial fraction of overall execution time.