答:
Let me ask you a completely serious counter-question: What, in your view, is the difference between "data" and "code"?

When I hear the word "data", I think "state". Data is, by definition, the thing that the application itself is designed to manage, and therefore the very thing that the application can never know about at compile time. It is not possible to hard-code data, because as soon as you hard-code it, it becomes behaviour - not data.

The type of data varies by application; a commercial invoicing system may store customer and order information in a SQL database, and a vector-graphics program might store geometry data and metadata in a binary file. In both of these cases and everything in between, there is a clear and unbreakable separation between the code and data. The data belongs to the user, not the programmer, so it can never be hard-coded.

What you seem to be talking about is, to use the most technically accurate description available to my current vocabulary: information governing program behaviour which is not written in the primary programming language used to develop the majority of the application.

Even this definition, which is considerably less ambiguous than just the word "data", has a few problems. For example, what if significant parts of the program are each written in different languages? I have personally worked on several projects which are about 50% C# and 50% JavaScript. Is the JavaScript code "data"? Most people would say no. What about the HTML, is that "data"? Most people would still say no.

What about CSS? Is that data or code? If we think of code as being something that controls program behaviour, then CSS isn't really code, because it only (well, mostly) affects appearance, not behaviour. But it isn't really data, either; the user doesn't own it, the application doesn't even really own it. It's the equivalent of code for a UI designer. It's code-like, but not quite code.

I might call CSS a kind of configuration, but a more practical definition is that it is simply code in a domain-specific language. That's what your XML, YAML, and other "formatted files" often represent. And the reason we use a domain-specific language is that, generally speaking, it's simultaneously more concise and more expressive in its particular domain than coding the same information in a general-purpose programming language like C or C# or Java.

Do you recognize the following format?

```<code>{
    name: 'Jane Doe',
    age: 27,
    interests: ['cats', 'shoes']
}
</code>```

I'm sure most people do; it's JSON. And here's the interesting thing about JSON: In JavaScript, it's clearly code, and in every other language, it's clearly formatted data. Almost every single mainstream programming language has at least one library for "parsing" JSON.

If we use that exact same syntax inside a function in a JavaScript file, it can't possibly be anything other than code. And yet, if we take that JSON, shove it in a .json file, and parse it in a Java application, suddenly it's "data". Does that really make sense?

I argue that the "data-ness" or "configuration-ness" or "code-ness" is inherent to what is being described, not how it's being described.

If your program needs a dictionary of 1 million words in order to, say, generate a random passphrase, do you want to code it like this:

```<code>var words = new List<string>();
words.Add("aa");
words.Add("aah");
words.Add("ahhed");
// snip 172836 more lines
words.Add("zyzzyva");
words.Add("zyzzyvas");
</code>```

Or would you just shove all those words into a line-delimited text file and tell your program to read from it? It doesn't really matter if the word list never changes, it's not a question of whether you're hard-coding or soft-coding (which many rightly consider to be an anti-pattern when inappropriately applied), it's simply a question of what format is most efficient and makes it easiest to describe the "stuff", whatever the "stuff" is. It's fairly irrelevant whether you call it code or data; it is information that your program requires in order to run, and a flat-file format is the most convenient way to manage and maintain it.

Assuming you follow proper practices, all of this stuff is going into source control anyway, so you might as well call it code, just code in a different and perhaps very minimalistic format. Or you can call it configuration, but the only thing that truly distinguishes code from configuration is whether or not you document it and tell end users how to change it. You could perhaps invent some bogus argument about configuration being interpreted at startup time or runtime and not at compile time, but then you'd be starting to describe several dynamically-typed languages and almost certainly anything with a scripting engine embedded inside of it (e.g. most games). Code and configuration are whatever you decide to label them as, nothing more, nothing less.

Now, there is a danger to externalizing information that isn't actually safe to modify (see the "soft coding" link above). If you externalize your vowel array in a configuration file, and document it as a configuration file to your end users, you are giving them an almost foolproof way to instantly break your app, for example by putting "q" as a vowel. But that is not a fundamental problem with "separation of code and data", it's simply bad design sense.

What I tell junior devs is that they should always externalize settings that they expect to change per environment. That includes things like connection strings, user names, API keys, directory paths, and so on. They might be the same on your dev box and in production, but probably not, and the sysadmins will decide how they want it to look in production, not the devs. So you need a way of having one group of settings applied on some machines, and other settings applied on other machines - ergo, external configuration files (or settings in a database, etc.)

But I stress that simply putting some "data" into a "file" isn't the same as externalizing it as configuration. Putting a dictionary of words into a text file doesn't mean that you want users (or IT) to change it, it's just a way of making it much easier for developers to understand what the hell is going on and, if necessary, make occasional changes. Likewise, putting the same information in a database table does not necessarily count as externalization of behaviour, if the table is read-only and/or DBAs are instructed never to screw with it. Configuration implies that the data is mutable, but in reality that is determined by process and responsibilities rather than the choice of format.

So, to summarize:

"Code" is not a rigidly-defined term. If you expand your definition to include domain-specific languages and anything else which affects behaviour, a lot of this apparent friction will simply disappear and it will all make sense. You can have non-compiled, DSL "code" in a flat file.

"Data" implies information that is owned by the user(s) or at least someone other than the developers, and not generally available at design time. It could not be hard-coded even if you wanted to do so. With the possible exception of self-modifying code, the separation between code and data is a matter of definition, not personal preference.

"Soft-coding" can be a terrible practice when over-applied, but not every instance of externalization necessarily constitutes soft-coding, and many instances of storing information in "flat files" is not necessarily a bona fide attempt at externalization.

Configuration is a special type of soft-coding that is necessary because of the knowledge that the application may need to run in different environments. Deploying a separate configuration file along with the application is far less work (and far less dangerous) than deploying a different version of the code to every environment. So some types of soft-coding are actually useful.

Body:
Let me ask you a completely serious counter-question: What, in your view, is the difference between "data" and "code"?

When I hear the word "data", I think "state". Data is, by definition, the thing that the application itself is designed to manage, and therefore the very thing that the application can never know about at compile time. It is not possible to hard-code data, because as soon as you hard-code it, it becomes behaviour - not data.

The type of data varies by application; a commercial invoicing system may store customer and order information in a SQL database, and a vector-graphics program might store geometry data and metadata in a binary file. In both of these cases and everything in between, there is a clear and unbreakable separation between the code and data. The data belongs to the user, not the programmer, so it can never be hard-coded.

What you seem to be talking about is, to use the most technically accurate description available to my current vocabulary: information governing program behaviour which is not written in the primary programming language used to develop the majority of the application.

Even this definition, which is considerably less ambiguous than just the word "data", has a few problems. For example, what if significant parts of the program are each written in different languages? I have personally worked on several projects which are about 50% C# and 50% JavaScript. Is the JavaScript code "data"? Most people would say no. What about the HTML, is that "data"? Most people would still say no.

What about CSS? Is that data or code? If we think of code as being something that controls program behaviour, then CSS isn't really code, because it only (well, mostly) affects appearance, not behaviour. But it isn't really data, either; the user doesn't own it, the application doesn't even really own it. It's the equivalent of code for a UI designer. It's code-like, but not quite code.

I might call CSS a kind of configuration, but a more practical definition is that it is simply code in a domain-specific language. That's what your XML, YAML, and other "formatted files" often represent. And the reason we use a domain-specific language is that, generally speaking, it's simultaneously more concise and more expressive in its particular domain than coding the same information in a general-purpose programming language like C or C# or Java.

Do you recognize the following format?

{
    name: 'Jane Doe',
    age: 27,
    interests: ['cats', 'shoes']
}

I'm sure most people do; it's JSON. And here's the interesting thing about JSON: In JavaScript, it's clearly code, and in every other language, it's clearly formatted data. Almost every single mainstream programming language has at least one library for "parsing" JSON.

If we use that exact same syntax inside a function in a JavaScript file, it can't possibly be anything other than code. And yet, if we take that JSON, shove it in a .json file, and parse it in a Java application, suddenly it's "data". Does that really make sense?

I argue that the "data-ness" or "configuration-ness" or "code-ness" is inherent to what is being described, not how it's being described.

If your program needs a dictionary of 1 million words in order to, say, generate a random passphrase, do you want to code it like this:

var words = new List<string>();
words.Add("aa");
words.Add("aah");
words.Add("ahhed");
// snip 172836 more lines
words.Add("zyzzyva");
words.Add("zyzzyvas");

Or would you just shove all those words into a line-delimited text file and tell your program to read from it? It doesn't really matter if the word list never changes, it's not a question of whether you're hard-coding or soft-coding (which many rightly consider to be an anti-pattern when inappropriately applied), it's simply a question of what format is most efficient and makes it easiest to describe the "stuff", whatever the "stuff" is. It's fairly irrelevant whether you call it code or data; it is information that your program requires in order to run, and a flat-file format is the most convenient way to manage and maintain it.

Assuming you follow proper practices, all of this stuff is going into source control anyway, so you might as well call it code, just code in a different and perhaps very minimalistic format. Or you can call it configuration, but the only thing that truly distinguishes code from configuration is whether or not you document it and tell end users how to change it. You could perhaps invent some bogus argument about configuration being interpreted at startup time or runtime and not at compile time, but then you'd be starting to describe several dynamically-typed languages and almost certainly anything with a scripting engine embedded inside of it (e.g. most games). Code and configuration are whatever you decide to label them as, nothing more, nothing less.

Now, there is a danger to externalizing information that isn't actually safe to modify (see the "soft coding" link above). If you externalize your vowel array in a configuration file, and document it as a configuration file to your end users, you are giving them an almost foolproof way to instantly break your app, for example by putting "q" as a vowel. But that is not a fundamental problem with "separation of code and data", it's simply bad design sense.

What I tell junior devs is that they should always externalize settings that they expect to change per environment. That includes things like connection strings, user names, API keys, directory paths, and so on. They might be the same on your dev box and in production, but probably not, and the sysadmins will decide how they want it to look in production, not the devs. So you need a way of having one group of settings applied on some machines, and other settings applied on other machines - ergo, external configuration files (or settings in a database, etc.)

But I stress that simply putting some "data" into a "file" isn't the same as externalizing it as configuration. Putting a dictionary of words into a text file doesn't mean that you want users (or IT) to change it, it's just a way of making it much easier for developers to understand what the hell is going on and, if necessary, make occasional changes. Likewise, putting the same information in a database table does not necessarily count as externalization of behaviour, if the table is read-only and/or DBAs are instructed never to screw with it. Configuration implies that the data is mutable, but in reality that is determined by process and responsibilities rather than the choice of format.

So, to summarize:

"Code" is not a rigidly-defined term. If you expand your definition to include domain-specific languages and anything else which affects behaviour, a lot of this apparent friction will simply disappear and it will all make sense. You can have non-compiled, DSL "code" in a flat file.

"Data" implies information that is owned by the user(s) or at least someone other than the developers, and not generally available at design time. It could not be hard-coded even if you wanted to do so. With the possible exception of self-modifying code, the separation between code and data is a matter of definition, not personal preference.

"Soft-coding" can be a terrible practice when over-applied, but not every instance of externalization necessarily constitutes soft-coding, and many instances of storing information in "flat files" is not necessarily a bona fide attempt at externalization.

Configuration is a special type of soft-coding that is necessary because of the knowledge that the application may need to run in different environments. Deploying a separate configuration file along with the application is far less work (and far less dangerous) than deploying a different version of the code to every environment. So some types of soft-coding are actually useful.


问:
Is it better to use already build plugins/extensions or code your own in programming projects
I am building a web app in  PHP and Symfony.

Basically if we search there are plugins / extensions / bundles for almost 60% of stuff.

The advantage of using them is that you can easily get your functionality and it will be maintained by the author
and we don't need to worry about compatibility.

But their downside is

Sometimes it's hard to do little bit customization if we want some extra behavior. In past I used some extension it work ok to start with.

Then I wanted to do something else which i was not able to figure out and in the end i had to code my own. It was not as efficient but I had full control.

Also if we depend on extension then we don't learn much as everything is done by the extension. Then if I need to switch the language or framework and that extension is not available in that environment then again I had to scratch my head and start from scratch.

But if I don't use them then I am thinking that I am wasting my time. I am confused what should be done?

答:
Some of the pros of using existing components/plugins/extensions/frameworks:

You don't have to re-invent the wheel. This can save you time and money.

Popular components are probably well-tested, well-supported, and well-documented (in theory... hopefully)

Consistent behaviour across all your applications that use these components, as well as behaviour that's consistent with other systems that use them. That could make for a better UX.

New developers who are familiar with a popular framework don't have to learn your home-brewed stuff.

Some of the cons of using existing components/plugins/extensions/frameworks:

Existing components might not do exactly what you need or want, and customizing to get exactly what you want might be very difficult, if it's even possible.

You're not always in control of updates and dependencies. Sometimes this is a problem.

Exploits in popular components could expose vulnerabilities in your application.

If you become heavily dependent on something that is only available to one platform/language/OS/whatever, switching to something else will be difficult.

Overall, I find the pros usually outweigh the cons. I suspect many people agree, considering how popular plug-in frameworks are.

ContentLicense: CC BY-SA 3.0


问:
2D movement of an object based on speed and new vector
I am writing a small game where a sea vessel (like a battleship) can be moved in a 2D place based on orders that it receives. I wanted to know if someone can help direct me to a post or example code that will help me move a ship from one location to another based on the speed and new vector.

So, if I had a ship that is moving in a south westerly direction (say 120 degrees) and it receives new orders to turn to a new vector of 020 degrees, how can I calculate the turn. I don't want it to just turn on a dime and head in the new direction. I want it to make the wide turn (as if it were in water) and then when it reaches the new vector, start heading in that direction.

Any help would be appreciated.

答:
You're travelling in a particular direction at a particular speed. So in a xy coordinate system, you're probably doing something like:

```<code>velocity_x = speed*cos(angle)
velocity_y = -speed*sin(angle)
x += velocity_x*t
y += velocity_y*t
</code>```

You now want to go at a different angle, i.e. a different velocity. A difference in velocities is an acceleration. It might be easier to consider this as a constant radians/s2 rather than anything more 'realistic'. So perhaps something like the followng:

```<code>acceleration = a_constant // for simplicity
angle = start_angle
while angle < end_angle // depending on clockwise or anticlockwise turn
    angle += acceleration*t
    velocity_x = speed*cos(angle)
    velocity_y = -speed*sin(angle)
    x += velocity_x*t
    y += velocity_y*t
</code>```

Body:
You're travelling in a particular direction at a particular speed. So in a xy coordinate system, you're probably doing something like:

velocity_x = speed*cos(angle)
velocity_y = -speed*sin(angle)
x += velocity_x*t
y += velocity_y*t

You now want to go at a different angle, i.e. a different velocity. A difference in velocities is an acceleration. It might be easier to consider this as a constant radians/s2 rather than anything more 'realistic'. So perhaps something like the followng:

acceleration = a_constant // for simplicity
angle = start_angle
while angle < end_angle // depending on clockwise or anticlockwise turn
    angle += acceleration*t
    velocity_x = speed*cos(angle)
    velocity_y = -speed*sin(angle)
    x += velocity_x*t
    y += velocity_y*t


问:
How do you overcome your own coding biases when handed legacy code?
As programmers, we often take incredible pride in our skills and hold very strong opinions about what is 'good' code and 'bad' code.

At any given point in our careers, we've probably had some legacy system dropped in our laps, and thought 'My god, this code sucks!' because it didn't fit into our notion of what good code should be, despite the fact that it may have well been perfectly functional, maintainable code.

How do you prepare yourself mentally when trying to get your head around another programmer's work?

答:
With experience comes the judgment to know when code is really bad, and when it is just written in a different style.  If it's perfectly functional and maintainable and there is good automated test coverage, then it's not bad and you just need to open your mind.  You will probably learn something.  Bad code is not functional and maintainable.

Here are some markers of truly bad code:

Large blocks of logic have been duplicated instead of refactored.

Circular dependencies between classes or packages

High coupling; low cohesion

Unused variables, writing to variables that are never read, unreachable code.

Reimplementation of standard library functions, e.g. date formatting.

Unnecessarily complex logic; i.e. 50 lines of code where 10 would do nicely.

No comments describing the purpose of classes or methods.

Misleading comments.

A lack of automated tests doesn't mean the code is bad, but it means the project is bad.

These are not a matter of taste; these practices make program maintenance much more expensive.

How do you prepare yourself?

Accept the fact that it takes a while to be able to successfully work on a new code base.  If it's "perfectly maintainable" and there is high test coverage, it takes less time but it still won't happen immediately.  If the code is bad, then the first thing I do is warn the stakeholders that it is in bad shape and initial progress will be slow.  If they are skeptical, then I back up my claim by showing them a sample of problems in the actual code and explaining how it varies from industry best practice.

ContentLicense: CC BY-SA 2.5


答:
This is a standard approach; track the ship using is speed and heading and change those as required. Make the x and y velocity a function of those.</p>

```<code>class Ship
{
    double x = 0;
    double y = 0;
    double speed = 15; // m/s;
    double heading = 120;
    double plannedHeading = 0;
    double turnRate = 3; // deg /s
    public Ship()
    {
        plannedHeading = heading;
    }
    void update(double dt)
    {
        x += dt * getVx();
        y += dt * getVy();
        if (heading != plannedHeading)
        {
            computeTurn(dt);
        }

    }
    void computeTurn(double dt)
    {
        double dh = plannedHeading - heading;
        if (dh < -180)
            dh += 360;
        if (dh > 180)
            dh -= 360;
        if (Math.Abs(dh) < turnRate * dt)
            heading = plannedHeading;
        else
        {
            int dir = 1;
            if (dh < 0)
                dir = -1;
            heading += turnRate * dt* dir;
        }
    }

    public void turnTo(double newHeading)
    {
        plannedHeading = newHeading;
    }
    public double getVx()
    {
        return speed * Math.Acos(heading * Math.PI / 180);
    }
    public double getVy()
    {
        return speed * Math.Asin(heading * Math.PI / 180);
    }

}
</code>```

Title: 2D movement of an object based on speed and new vector

Body:
I am writing a small game where a sea vessel (like a battleship) can be moved in a 2D place based on orders that it receives. I wanted to know if someone can help direct me to a post or example code that will help me move a ship from one location to another based on the speed and new vector.

So, if I had a ship that is moving in a south westerly direction (say 120 degrees) and it receives new orders to turn to a new vector of 020 degrees, how can I calculate the turn. I don't want it to just turn on a dime and head in the new direction. I want it to make the wide turn (as if it were in water) and then when it reaches the new vector, start heading in that direction.

Any help would be appreciated.

Body:
This is a standard approach; track the ship using is speed and heading and change those as required. Make the x and y velocity a function of those.

class Ship
{
    double x = 0;
    double y = 0;
    double speed = 15; // m/s;
    double heading = 120;
    double plannedHeading = 0;
    double turnRate = 3; // deg /s
    public Ship()
    {
        plannedHeading = heading;
    }
    void update(double dt)
    {
        x += dt * getVx();
        y += dt * getVy();
        if (heading != plannedHeading)
        {
            computeTurn(dt);
        }

    }
    void computeTurn(double dt)
    {
        double dh = plannedHeading - heading;
        if (dh < -180)
            dh += 360;
        if (dh > 180)
            dh -= 360;
        if (Math.Abs(dh) < turnRate * dt)
            heading = plannedHeading;
        else
        {
            int dir = 1;
            if (dh < 0)
                dir = -1;
            heading += turnRate * dt* dir;
        }
    }

    public void turnTo(double newHeading)
    {
        plannedHeading = newHeading;
    }
    public double getVx()
    {
        return speed * Math.Acos(heading * Math.PI / 180);
    }
    public double getVy()
    {
        return speed * Math.Asin(heading * Math.PI / 180);
    }

}


问:
Which one to choose: XML attribute or Sub node?
We want to export some data from our data base as XML.  For example, a Person can have age, name and some other properties.

We have two choices to define the XML format.

Choice #1:

```<code><Persons>
   <Person>
       <Age>16</Age>
       <Name>Richard</Name>
   </Person>
   <Person>
       <Age>34</Age>
       <Name>Eric</Name>
   </Person>
   ...
</Persons>
</code>```

Choice #2:

```<code><Persons>
   <Person Age="16" Name="Richard"/>
   <Person Age="34" Name="Eric"/>
   ...
</Persons>
</code>```

So what's the difference between definition of sub node or attribute?
And what's the benefit of each choice?

答:
There is no clear documentation/best practice for this, but, consider the alternatives, as you have:

As Element text:

it can be easier to display the data as xhtml, etc, where the text content is considered text, rather than markup or meta-data.

there can be more than one. If you need child content with multiple age or name rows, attributes won't allow this

if you need row level meta data, you have the option of using the attributes of <name> or <age> for this purpose

As Attributes:

the XML is more compact

XSLT and DocTypes are simpler to specify

you don't have to worry about whitespace (padding, indenting, line breaks), or other items that can be introduced (comments, PI's) in PCDATA areas (element text)

there can be only one! you don't have to worry about child content containing multiple age attributes.

I have spent a lot of time working with XML, and, in my opinion, for pure data communication, attributes should be used whenever possible. If the XML is likely to be used for presentation (XSLT, xhtml, etc.) then it may be better as text content (but not necessarily).

OwnerDisplayName: ZijingWu


问:
How can Scrum be adapted to a Volunteer setting?
I have recently joined a young hackerspace still in the process of setting itself up.  We're fortunate because the space has a few internal projects that need working on and no shortage of volunteers to work on them.

There have been some discussions on how to organize these projects.  My most recent professional experience has been with Scrum so I'm considering pitching a Scrum approach for our software projects, but I'm not sure it will be a good fit.

Although I've seen Scrum work well for small full-time teams, the nature of this organisation is different:

The members are volunteers.  Some are full time students.  Others work jobs full time.  We can't expect a constant level of contribution from anyone as their real lives take priority.

While pretty much everyone has years of experience writing software, not many members have done so professionally or in teams.

There is no Product Owner.  The requirements for these projects are determined by a committee.  The members of this committee will also be working on the implementation.  This means we will have no single, dedicated, Product Owner.

We have no deadlines (soft or hard).  The projects will get done when they get done.

These are pretty significant differences, but I'm not convinced they will be blockers to applying Scrum.  I think some minor tweaking could get us over this hurdle:

If we change Sprints to have a fixed story-point size, but fluid duration (time), we can still benefit from iterative releases without putting unrealistic delivery pressure on volunteer devs.

We can ditch burndown charts and velocity calculation.  If I understand correctly, these are tools and metrics that work as a bridge between the dev team and the Management.  They serve to report progress in a form that is meaningful to both the developers and the stakeholders.  Considering we have no one to report to (no Project Manager, no Product Owner, and no outside stakeholders) I believe we can drop this altogether.

Things I think we could benefit from which won't require tweaking:

The Requirements Gathering meeting(s).  Where everyone sits around a table and discusses User Stories, sketches up UI mocks, and builds up a Product Backlog.

Sprint Retrospectives.  This will be an interesting way for us to converge on a development process that works for us as a team of volunteers.

Things I'm not sure about:

How should daily Stand-ups be treated?  I wonder if they would have much value at all in our setting.  My understanding of the stand-up ritual is that it helps communication by naturally disseminating information throughout the team.  Considering the fact that our Sprints will likely be delivering much less complexity than an average Sprint there might be less need to be abreast of all the other team members' progress/developments.

Should I push for XP things like Continuous Integration, Code Reviews, and TDD?  I'm concerned this will be asking for a lot.  I'd be more tempted to bring these concepts in on future projects once people are more familiar with Scrum and working as a team.

My Questions:

Can Scrum be adapted to a volunteer-based environment?

And, is my planned approach so far going in the right direction?

答:
I might suggest a different approach.  Since you're dealing with volunteers you have a few things to consider. Your team will probably have a high turnover, life will get in the way and people will get distracted.  Of those left a few will contribute consistently but not very much, then lastly you'll have that hardcore group who really sink their teeth into the project.  I'm making a lot of assumptions about your work force here and if you feel that my assessment doesn't reflect the people you're working with feel free to ignore the rest of this.

Now you need a strategy that will allow people who don't do a lot of work to be able to work fairly autonomously, they only have so much time to dedicate to this and you don't want to make them spending the majority of that in communication.  The people who are more involved should be responsible for integration and flushing out some of the more complex ideas.

This leads me to think of a development process more focused around wire frames and prototypes.

You can have a pool of work items available and encourage people to write wire frames for those.  You can use these as Tracer Bullets (terminology borrowed from Pragmatic programmer) to hone in on the idea and provide inspiration for people to build on.  From there you can graduate the successful ideas into prototypes, again these are very small  projects designed to help the people learn more about the projects.  After that you now have a smaller section of solid ideas that have been built by a multitude of people that you can hand off to some of the team that is a little more active and they can work to integrate those ideas into your system.


问:
Creation of an Assembler
I've always been interested in how programming languages are created, so for the past 8 months I've been researching, practicing and more about the creation of compilers. I've been able to quite easily write front ends for languages and withing the past couple months have been reading more about the back end pieces of a compiler. On top of this I've been reading about and practicing things with the x86 instruction set.

It has been my dream to write a compiler and I would like to make my first big step of understanding back ends, this being attempting a simple x86 assembler. My goal for this is to learn more about code generation, x86 instruction set, executables and figure out the best algorithms and techniques (don't answer anything about the front end, I have this down lol). Eventually to be satisfied in my progression I would like it to output an executable for my platform (Ubuntu Linux amd64, ELF executable) written in the assembly language.

This is a daunting task, though I feel I'm ready with some blood, sweat, and tears. So, my question is: what and in what way does my assembler need to do things? I know it needs to process the actual source, the what? From all I've gathered after processing the source I need to, write out a ELF header and then output the generated x86 code after this correct? I can't find much in depth information on how the x86 code is stored in the executable or even relocatable object files. I know there's sections of some sort but I can't find out how these are expressed, and what they're for.

Anyone willing to answer any of these questions or point me in the right direction is awesome, I've been working on this a long time.

答:
For a stand-alone assembler, you need to:

(optionally) pre-process, including handling things like "%include", conditional code, macros, etc

tokenise the text into, um, tokens

(optionally) do initial constant expression evaluation, e.g. something like mov eax,123+456*99 becomes mov eax,0x29889

For a compiler back-end, you'd start with pre-tokenised assembly and skip all of the above.

In any case; the next step is to:

sort the code to determine which section/s different pieces go into

find labels and store them somewhere (symbol table), typically with a "section", with an "offset within section" if possible/known

convert tokens into either machine code or data as much as possible (where no labels with unknown "offset within section" is involved)

After that (optionally):

do a "peephole like" optimisation pass. There's typically a lot of instructions that can be simplified. For example, something like lea eax,[ebx + myStructure.firstMember] might become lea eax,[ebx + 0] and could be optimised to mov eax,ebx without breaking anything.

After that:

fix any references to labels that you couldn't do in the previous steps

Note: for a decent assembler (at least for 80x86), this is typically repeated until everything is resolved. The reason for this is optimisation - there are several different control transfer instructions (jmp, call) with different sizes, so you can't know the "offset within section" of most labels until you've found the smallest/best control transfer instructions in previous code.

Finally; you generate the output file. This may be a flat binary (where you can, and must, resolve all references to labels to actual addresses). This may also be one of many different object file formats (where you can't resolve references to labels down to actual addresses).

Note: If you are not constrained by "compatibility with existing tools" limitations; and if you are smart; then you can use the "pre-tokenised assembly" as your own object file format (e.g. where compiler and the first half of the assembler generate "pre-tokenised assembly object files") and use the latter half of the assembler in place of a traditional linker. This allows you to do much more aggressive optimisation in the latter half of the assembler/linker (basically, you end up with the equivalent of link-time optimisation without any of the normal hassles).

Title: Creation of an Assembler


问:
How to connect mvc application using entityframework or ado.net?
I am an ASP.NET developer. I want to learn ASP.NET MVC. In fact I am learning it. But Now I am confused at a point. How can I connect my database to my application. Using entity framework or linq or ado.net. I have good knowledge about ado.net. But about entity framework I cant say anything. Now my problem is this whichever ebook or website I see every entity framework is used. So is it essential for me to learn first entity framework before ASP.NET MVC or not? </p>

答:
You will have to use LINQ and EF together if you want to do anything more complicated than CRUD with EF. That said, EF makes CRUD dirt simple. Build your models or database, push the changes the other way (update the database or your models respectively), add controllers and views to taste.

If you start getting into more complicated objects than can be stored in a related set of tables (parent, child, grandchild, etc.), you will have to switch over to LINQ. But fear not gentle traveler, LINQ can use the EF objects directly, making a lot of things trivial (e.g., complicated nested, barely related data in structures that would make JSON blush). LINQ also gives you the advantage of being able to use SQL statements directly. AFAIK, you will only be able to use the EF connection while using SQL. I haven't had any need to even use that so far.

EF is getting better and more capable all the time. I don't see it catching up with LINQ, but it might be more than enough for most data access soon.

I would hazard a guess that you can learn EF and MVC at the same time.

I should also mention that you can combine any or all of the technologies you mentioned.


答:
It surprises me that no one pointed it out, but your project seems like most open-source projects. If you check out some more popular open-source projects, you might find some inspiration. And I think you should forget about SCRUM and think about this from perspective of general agile.

Agile is a all about communication and collaboration. There is reason why there 2 points out of 4 in Agile Manifesto talk about it.

Individuals and interactions over processes and tools

Customer collaboration over contract negotiation

And the way you describe your project, it would be difficult to have face-to-face communication with everyone working on the project, something both Agile and SCRUM encourage. So first thing I would focus on is to establish communication channels for whole team (both volunteers and product committee). Things like wiki, forums, videoconferences and proper backlog, task and bug tracking system are great ways to ensure everyone knows what is happening and what needs to be done.

Second thing I would note is not to just brush around the technological parts of agile. Many believe (myself included) that they are the ones that make agile work, not the process side of things. Code review is important and most open-source work by having someone who knows the project review the commits/push to ensure high enough quality is maintained. TDD is practically given for any agile project. It ensures any changes to the code don't break the previous functionality which is even more important in your case when volunteers cannot be bothered to fix other people's errors and mistakes. It also makes code review easier because reviewer can see in tests what functionality was added and by running them he ensures the functionality actually works as intended. Continuous integration is same as TDD. It ensures the application does what is intended by allowing short feedback loop with customer/product committee.

Last thing is that I believe you should have at least few  people working on the project full-time. Those people should have specific roles:

Product owner : While it is nice you have a whole committee dedicated to this, there should be one person who is responsible for interpreting this committee's words into specification or user stories and ensuring they are properly implemented.

Coordinator & Scrum Master : This person should be responsible for the whole process and ensuring that everyone knows about the important things happening in the project. Also, he maintains the wiki and task&bug tracking tools. If someone has a question about the project, this is first person they should ask.

Main developer & architect : The person who knows the code best. He does the code reviews and ensures the quality of code is good enough for agile development.

Title: How can Scrum be adapted to a Volunteer setting?

Body:
I have recently joined a young hackerspace still in the process of setting itself up.  We're fortunate because the space has a few internal projects that need working on and no shortage of volunteers to work on them.

There have been some discussions on how to organize these projects.  My most recent professional experience has been with Scrum so I'm considering pitching a Scrum approach for our software projects, but I'm not sure it will be a good fit.

Although I've seen Scrum work well for small full-time teams, the nature of this organisation is different:

The members are volunteers.  Some are full time students.  Others work jobs full time.  We can't expect a constant level of contribution from anyone as their real lives take priority.

While pretty much everyone has years of experience writing software, not many members have done so professionally or in teams.

There is no Product Owner.  The requirements for these projects are determined by a committee.  The members of this committee will also be working on the implementation.  This means we will have no single, dedicated, Product Owner.

We have no deadlines (soft or hard).  The projects will get done when they get done.

These are pretty significant differences, but I'm not convinced they will be blockers to applying Scrum.  I think some minor tweaking could get us over this hurdle:

If we change Sprints to have a fixed story-point size, but fluid duration (time), we can still benefit from iterative releases without putting unrealistic delivery pressure on volunteer devs.

We can ditch burndown charts and velocity calculation.  If I understand correctly, these are tools and metrics that work as a bridge between the dev team and the Management.  They serve to report progress in a form that is meaningful to both the developers and the stakeholders.  Considering we have no one to report to (no Project Manager, no Product Owner, and no outside stakeholders) I believe we can drop this altogether.

Things I think we could benefit from which won't require tweaking:

The Requirements Gathering meeting(s).  Where everyone sits around a table and discusses User Stories, sketches up UI mocks, and builds up a Product Backlog.

Sprint Retrospectives.  This will be an interesting way for us to converge on a development process that works for us as a team of volunteers.

Things I'm not sure about:

How should daily Stand-ups be treated?  I wonder if they would have much value at all in our setting.  My understanding of the stand-up ritual is that it helps communication by naturally disseminating information throughout the team.  Considering the fact that our Sprints will likely be delivering much less complexity than an average Sprint there might be less need to be abreast of all the other team members' progress/developments.

Should I push for XP things like Continuous Integration, Code Reviews, and TDD?  I'm concerned this will be asking for a lot.  I'd be more tempted to bring these concepts in on future projects once people are more familiar with Scrum and working as a team.

My Questions:

Can Scrum be adapted to a volunteer-based environment?

And, is my planned approach so far going in the right direction?


问:
How do you version your files (Version Numbers)
I wonder how do you decide on the version number of your apps, do you really record down all changes made (for a change log)? Then how will you decide how to increment the version number. eg. +0.0.1 for each bug fix or something, +0.1 for each new feature release? or maybe you bundle many changes into +0.1 of your version number?</p>

答:
Making this change by hand will result in customers having different versions of your DLL's with the same version number.  the only safe way I know is to use the Build server to do this automatically. The build server will add a 0.0.1 each time the code is built.

As far as I am concerned the 0.1 and 1. changes occur when you make release branches, keeping the trunk development as 0.0.0.x


问:
How to represent one special related record
I have two tables, project and photo. photo has ID,projectID,path : each project has multiple photos.

Now one of these photos is the one that has to be displayed. The question is how to represent this in the database.

Earlier, I used descending order of ID numbers and chose the latest one, but that failed and caused problems. Now I am not sure which way to go :

Create a new table projectPhotoDisplayed that holds project.ID and photo.ID(those that are to be displayed only) numbers.

The bad : too much work, as well as replicating the information that photo table already has (photos associated with projects ).

Create a new binary field in the photo table. If true, then display, else not.

The bad : Structurally does not prevent multiple photos being marked to display. I want radio button behavior

Create a new field in the project table that stores the photoID of the photo to be displayed.

The bad : Does not ensure that the particular photoID is actually linked to this project. Also does this information belong here?

Any approach with foreign keys so that referential integrity is maintained..?

Using PHP and MySQL InnoDB database, though I'm sure it won't matter.

Which is the best way to store this info?

答:
All the three ways are viable solutions, but I would avoid the first one and the third one because of redundant information which could get "out of sync". There could be a photoID stored as foreign key of a photo which belongs - or is moved to - a different project.

Create a new binary field in the photo table.

You surely meant a boolean field, not a binary field. This would be my favorite option. To make sure there will be at maximum one photo to be displayed, you may add "before update" and "before insert" triggers to your DB, counting the numbers of rows where your "display" column has the value "true" and throwing an error if there would be more than one. Here you find an example how to use "before insert" triggers for verifying constraints.


答:
Another consideration beyong rolfl's ones is the number of fields.

More than a small number of attributes becomes a mess, and hard to read (that's assuming you want your xml to be human readable, but as a programmer you're going to want to do that for testing at least).

Also, if you expect the data structure of one of the fields to change over time, don't make it an attribute.

For example, your name field. Maybe in the future this would become

```<code><name>
  <firstName>George</firstName>
  <lastName>Orwell</lastName>
  <maidenName></maidenName>
  <nickName>Robert</nickName>
</name>
</code>```

If you expect something like that to happen, making it an attribute would mean more refactoring code later.

Title: Which one to choose: XML attribute or Sub node?

Body:
We want to export some data from our data base as XML.  For example, a Person can have age, name and some other properties.

We have two choices to define the XML format.

Choice #1:

```<code><Persons>
   <Person>
       <Age>16</Age>
       <Name>Richard</Name>
   </Person>
   <Person>
       <Age>34</Age>
       <Name>Eric</Name>
   </Person>
   ...
</Persons>
</code>```

Choice #2:

```<code><Persons>
   <Person Age="16" Name="Richard"/>
   <Person Age="34" Name="Eric"/>
   ...
</Persons>
</code>```

So what's the difference between definition of sub node or attribute?
And what's the benefit of each choice?

Body:
Another consideration beyong rolfl's ones is the number of fields.

More than a small number of attributes becomes a mess, and hard to read (that's assuming you want your xml to be human readable, but as a programmer you're going to want to do that for testing at least).

Also, if you expect the data structure of one of the fields to change over time, don't make it an attribute.

For example, your name field. Maybe in the future this would become

<name>
  <firstName>George</firstName>
  <lastName>Orwell</lastName>
  <maidenName></maidenName>
  <nickName>Robert</nickName>
</name>

If you expect something like that to happen, making it an attribute would mean more refactoring code later.


答:
For the Persons tag, it is normal to have more tags of Person, it makes sense, a list of Persons have some entities, not attributes.

The story is different for Person and its components. A Person doesn't contain a name, the name is an attribute of the Person, so I'd stick with attributes instead of new tags. Tags are useful when you have repetitive things like Addresses, you can't do it with attributes.

If we think in HTML context, you don't have an input with a name tag with a value, do you?


答:
You have to see these elements as layers of a cake.

ASP .Net WebForms or ASP .Net MVC is the top layer of the cake,
namely the user interface layer.  This, ideally, should handle the
user's browsing and pass anything more complicated than that off to
the business logic.

The next layer down, the middle of the cake, is the 'business logic',
where you'd set rules of your application, or the 'how it all works'
coding.  Anything more complicated than this, namely reading/writing
to the database is passed down again.

The bottom layer of the cake, is the data layer; this layer reads and
writes data to/from the database, irrespective of whether you're
using SQL Server, Access, Oracle, MySQL, whatever.

Learn to cut your code up like this and you'll be in a better position for your career, going forward. (For Dependency Injection, Inversion of Control, Unit Testing, etc etc etc.)

In the case you've mentioned, Entity Framework is known as an Object Relational Mapper, or ORM for short.  NHibernate is another example of an ORM.  The job of an ORM is to remember that a particular table in your database is 'mapped' to a class object in your code.  There are lots of examples on StackOverFlow.com for Entity Framework, but to be honest, I'd buy a book that not directly focused on EF as it sounds like you need an MVC grounding first.  Try something like this: ASP .Net 4.

LINQ, however, is something that you can use with coding in general but primarily, you'd use LINQ to query a database, or other collection of objects, as in:

```<code>    // The Three Parts of a LINQ Query:
    //  1. Data source.
    int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };

    // 2. Query creation.
    // numQuery is an IEnumerable<int>
    var numQuery =
        from num in numbers
        where (num % 2) == 0
        select num;

    // 3. Query execution.
    foreach (int num in numQuery)
    {
        Console.Write("{0,1} ", num);
    }
</code>```

Have a look here as this might be a good place to start.

Title: How to connect mvc application using entityframework or ado.net?

Body: I am an ASP.NET developer. I want to learn ASP.NET MVC. In fact I am learning it. But Now I am confused at a point. How can I connect my database to my application. Using entity framework or linq or ado.net. I have good knowledge about ado.net. But about entity framework I cant say anything. Now my problem is this whichever ebook or website I see every entity framework is used. So is it essential for me to learn first entity framework before ASP.NET MVC or not? </p>

Body:
You have to see these elements as layers of a cake.

ASP .Net WebForms or ASP .Net MVC is the top layer of the cake,
namely the user interface layer.  This, ideally, should handle the
user's browsing and pass anything more complicated than that off to
the business logic.

The next layer down, the middle of the cake, is the 'business logic',
where you'd set rules of your application, or the 'how it all works'
coding.  Anything more complicated than this, namely reading/writing
to the database is passed down again.

The bottom layer of the cake, is the data layer; this layer reads and
writes data to/from the database, irrespective of whether you're
using SQL Server, Access, Oracle, MySQL, whatever.

Learn to cut your code up like this and you'll be in a better position for your career, going forward. (For Dependency Injection, Inversion of Control, Unit Testing, etc etc etc.)

In the case you've mentioned, Entity Framework is known as an Object Relational Mapper, or ORM for short.  NHibernate is another example of an ORM.  The job of an ORM is to remember that a particular table in your database is 'mapped' to a class object in your code.  There are lots of examples on StackOverFlow.com for Entity Framework, but to be honest, I'd buy a book that not directly focused on EF as it sounds like you need an MVC grounding first.  Try something like this: ASP .Net 4.

LINQ, however, is something that you can use with coding in general but primarily, you'd use LINQ to query a database, or other collection of objects, as in:

    // The Three Parts of a LINQ Query:
    //  1. Data source.
    int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };

    // 2. Query creation.
    // numQuery is an IEnumerable<int>
    var numQuery =
        from num in numbers
        where (num % 2) == 0
        select num;

    // 3. Query execution.
    foreach (int num in numQuery)
    {
        Console.Write("{0,1} ", num);
    }

Have a look here as this might be a good place to start.


问:
Refactor or Concentrate on Completing App
Would you refactor your app as you go or focus on completing app first? Refactoring will mean progress of app app will slow down.

Completing app will mean you get a possibly very hard to maintain app later on?

The app is a personal project. I don't really know how to answer "What drives the functionality and design", but I guess it's to solve inefficiencies in current software out there. I like minimal easy to use software too. So I am removing some features and add some that I feel will help.

答:
I always refactor as I go, especially using TDD.

Write the tests

Make the tests pass

Refactor

This will help you have less bugs and better code for the finished product. It will also let you have less code to maintain when you are done.


问:
Viability of a Development Team with no *dedicated* Tester role
I've been thinking a lot lately about how to build a lean development team.  Ultimately, I'd like to open up my own little software house with a small number of like-minded people.  The goal won't be to become rich, but rather to have a healthy work environment.

So far, I'm defining a lean team as the following:

Small;

Self-organizing;

All members must have QA in mind;

Members must be capable of performing multiple roles

The last point is where I'm worried a bit because, as the mantra goes...

Developers make bad testers.

While I understand that, often, developers are "too close" to their code or their colleague's code to make higher-level assessments of quality, I'm not convinced they are de-facto bad testers.  On the contrary, I'm of the opinion that the qualities of a good developer overlap greatly with the qualities of a good tester.

Assuming this is correct, I've been thinking of different ways of getting around the dev/tester problem and I believe I have come up with a viable model.

My model requires:

A small software house with 2+ projects

An Agile (iterative) approach to development and delivery

1 team per project

All team members will be Software Developers

Their job description will clearly state Development, Quality Assurance, Testing, and Delivery as responsibilities

If all these preconditions have been met, then the projects can be organized in the following fashion (this example will refer to two projects, A and B):

Every team member will alternate between Developer role and Tester role

If a team member is a Developer on project A, they will be a Tester on project B

Members will work on only 1 project at a time, and therefore are expected to be acting as either a Dev or a Tester.

A Role Cycle consists of 3 iterations as a Dev and 2 iteration as a Tester (again, on two different projects)

Project teams would have 3 Devs and 2 Testers at all times.

Member Role Cycles should be out of phase by 1 iteration.

This minimizes the abruptness of the team changes.  For each iteration, 2 Devs and 1 Tester will remain the same as the previous iteration.

Given the above, I see the following Pros and Cons:

Pros

Distributes project knowledge throughout the company.

Ensures team members aren't testing the code they helped write.

Out-of-phase role cycles means no project ever has a 100% member switch.

Alternating roles breaks the monotony of boring projects.

Cons

The iterations of both projects are tightly coupled.  If one project were to cancel an iteration halfway through and start again, then the two projects would be out of sync.  This would make the role-cycle difficult to manage.

Hinges on hiring Developers open working as Testers as well.

I've received mixed reviews when discussing this approach with friends and colleagues.  Some believe that few developers would ever want to alternate roles like this, while others tell me they personally would love to try it.

So my question is:  Could such a model work in practice?  If not, could it be tweaked into a working model?

Note:  For the sake of brevity I have only focused on the Dev and Tester roles.  I'll expand on other roles if needed.

答:
I agree with @Rob Y's answer, and would like to add a few points:

In agile, dedicated testers within a team are an anti-pattern, because they force teams to pipeline work and be inherently inefficient. You constantly end up with stories which are "dev done" but not tested. Dedicated testers are fine if they work outside of the team (or a separate team).

Dev make bad testers... and testers make bad testers. QA is hard. In fact, it's very hard. Your problem might not be people and roles. Your problem might be that your software is rushed out. Again, in agile, it's your team's responsibility to test before production (whether they have dedicated QA or not).

QA is part of development, like refactoring, architecture, etc. It's the responsibility of a development team to produce software to a certain, agreed, realistic standard. QAs will not improve that standard. Better developers probably will.

Provocation: Who says that QAs are better than developers at QA-ing? It's something people say but... [citation needed]. The needed "hacker" mentality of QA is a developer mentality. In fact, basically all hackers are or were developers, not QA...

Provocation 2: 99% of QA work can be (and, dare I say, should be) automated via scripts.  A good team will do this, and to do this properly you need... developers.


问:
An alternative to an array of functions?
I'm programming an app (php) which requires a very long list of similar yet different functions, which are being called by a set of keys:

```<code>$functions = [
    "do this" => function() {
        // does this
    },
    "do that" => function() {
        // does that
    }
]
etc.
</code>```

I've chosen to place the similar functions in an array because they are not similar enough - getting the same result with one big function which is full of conditional statements isn't gonna work. And I do need to be able to call them only by key, for example:

```<code>$program = ["do this", "do that", "do this"];
foreach ($program as $k => $v) {
    $functions[$v]();
}
</code>```

Thing is this functions-array structure is causing many problems, for example I'm having a hard time calling one array function from within another array function, e.g. this doesn't work:

```<code>"do that" => function() {
    $functions["do this"]();
}
</code>```

nor this:

```<code>"do that" => function() {
    global $functions;
    $functions["do this"]();
}
</code>```

or this:

```<code>"do that" => function($functions) {
    $functions["do this"]();
}

$functions["do that"]($functions);
</code>```

I guess I could have one giant function with a long switch statement:

```<code>function similar_functions($key) {
    switch ($key) {
        case "do this":
            // does this
        break;
        case "do that":
            // does that
        break;
    }
}
</code>```

But that doens't really seem like good practice. Or maybe it is?

So, what are my alternatives? Should I go with the switch structure? Or is there another, better solution?

答:
I think a better way is to change the array to namespace.
So you can use normal function names and normal calling from another functions.

When needed dynamic call - use reference.

```<code>namespace foo {
  function f1($a) { print "1\n"; };
  function f2($a) { print "2\n"; f1(3); };
}
namespace bar {
  $f = '\foo\f2';
  $f(2);
}
</code>```

Body:
I think a better way is to change the array to namespace.
So you can use normal function names and normal calling from another functions.

When needed dynamic call - use reference.

namespace foo {
  function f1($a) { print "1\n"; };
  function f2($a) { print "2\n"; f1(3); };
}
namespace bar {
  $f = '\foo\f2';
  $f(2);
}


答:
Really depends on where you are at!

Other things to think about:

How certain are you, you've really got the functional design right? Could you end up re-designing again after you get some user feedback?

I'd prefer to release than rewrite. Optimize after you are sure you've nailed the functional design.

Title: Refactor or Concentrate on Completing App

Body:
Would you refactor your app as you go or focus on completing app first? Refactoring will mean progress of app app will slow down.

Completing app will mean you get a possibly very hard to maintain app later on?

The app is a personal project. I don't really know how to answer "What drives the functionality and design", but I guess it's to solve inefficiencies in current software out there. I like minimal easy to use software too. So I am removing some features and add some that I feel will help.


问:
Apple eating problem
Player A and Player B play a game. On the middle of the table there is a pot full of N apples of different weights. Player A starts first and choose an apple and start eating it. Losing no time player B do the same. When a player eats the whole apple, without losing time repeat the same procedure. In case both player have eaten the apple at the same time, Player A still have the advantage of choosing first. Note that both players eat with same speed

What apple should the Player A choose at first to ensure that with right tactics he'll eat as much as grams of apples possible if the player B plays optimally?

I thought that choosing the smallest or the biggest apple should do the job, but there are specific cases when this doesn't work.

This is  C++ contest problem, so there should be a nice solution to this. I think that brute force maybe provide a solution, but this will require much time, because the number of apples is up to 10000.

I would rather like some hint on how to approach this question, how to find the optimal tactic or intuition rather than a code.

答:
As it was said it can be solved via backtracking. The important thing to note is that the weight of the apples eaten is proportional to the time spent eating. That means that maximizing the weight is the same as maximizing the time spent eating.

Another observation is that it is never beneficial to pause in eating. That means that pauses can be ignored.

So the algorithm i propose:

define state as:

amount eaten by A

amount eaten by B

list of apples left

Now in each step of backtracking you receive this state. The person on turn to choose another apple is the one with the lesser amount eaten (because it has eaten faster). Now it is easy to generate another state for the backtracking algorithm.

example

suppose you have received state:

eaten by A = 600

eaten by B = 400

apples left = 300, 400

From this you can generate states:

eaten by A = 600

eaten by B = 700

apples left = 400

and

eaten by A = 600

eaten by B = 800

apples left = 300

end of example

The algorithm ends when there are no apples left in the list. It will be probably necessary to think about some heuristics (the order in which the apples are picked). You can also prune the search space greatly if you also keep the sum of the apples left  and end when its clear that you can't be better that some solution you have found earlier. I am sure there are more similar possibilities how to speed it up.

Title: Apple eating problem


答:
I don't know much about "nodes" and "graphs", and besides, I prefer a practical approach....

This is what I decided; it's a brute force approach, and is a trade-off between CPU time and programmer time (CPU time is cheaper). It works well with a small number of apples; 9 apples takes 3.5 seconds to run, 10 apples takes about 40 seconds; more than 12 would probably want a different approach.

Write a function that takes (time so far for player 1, time so far for player 2, the next apple, and the remaining apples). It returns, for the optimum play for both player 1 and player 2: the amount of apple eaten by player 1, the amount of apple eaten by player 2, and, in order, the apples eaten.

The code for this function is as follows:

The "next apple" is eaten (added to player 1's time, or player 2's time, according to who is next due to eat an apple).

If there are no (more) apples, this function is now trivial - return the times for player 1 and player 2 (which you have already calculated), and the list of apples eaten (which consists of the "next apple to be eaten").

Otherwise, go through each apple on your list one by one (hereafter the new "next apple"), doing the following: call this same function, with the updated times, the new "next apple", and the list of remaining apples. Get the result of each, and find the one either with the lowest time for player 1, or the lowest time for player 2, depending on who is choosing this apple. Since the returned time for player 1+player 2 must be the same as the list of apples, the lowest time for player 1 = the highest time for player 2, so you can easily sort the list by duration for player 1, and then take either the first, or last entry in the list of results. Whichever entry is selected, add your "next apple" to the start of the "apple-eaten-order list" (the third item of the result), and return the result.

Note that there may be multiple "best" results. When you are actually calling this function for real, set the "time so far" for player 1 & 2 to 0, and set the first "next apple" to 0 - an imaginary apple, so we don't have to know in advance which apple to eat first.

Title: Apple eating problem

Body:
Player A and Player B play a game. On the middle of the table there is a pot full of N apples of different weights. Player A starts first and choose an apple and start eating it. Losing no time player B do the same. When a player eats the whole apple, without losing time repeat the same procedure. In case both player have eaten the apple at the same time, Player A still have the advantage of choosing first. Note that both players eat with same speed

What apple should the Player A choose at first to ensure that with right tactics he'll eat as much as grams of apples possible if the player B plays optimally?

I thought that choosing the smallest or the biggest apple should do the job, but there are specific cases when this doesn't work.

This is  C++ contest problem, so there should be a nice solution to this. I think that brute force maybe provide a solution, but this will require much time, because the number of apples is up to 10000.

I would rather like some hint on how to approach this question, how to find the optimal tactic or intuition rather than a code.


答:
At a previous job, we had only developers and no QA staff. As a result there was no one else to blame if a problem made it through to production. We took our QA responsibilities very seriously, and relied heavily on automated test suites.  Since writing automated tests is still coding, it wasn't a big deal to get developers to do it.

The key thing is to make it part of the culture of the team, and part of every project. We wrote up test plans (just brief lists of tests we intended to write for a project), and other developers would review and suggest cases and scenarios we'd missed.

If you're rigorous about it, it can work very well. It did for us - we had excellent uptime and low defects in an always-on e-commerce web service.

Title: Viability of a Development Team with no *dedicated* Tester role

Body:
I've been thinking a lot lately about how to build a lean development team.  Ultimately, I'd like to open up my own little software house with a small number of like-minded people.  The goal won't be to become rich, but rather to have a healthy work environment.

So far, I'm defining a lean team as the following:

Small;

Self-organizing;

All members must have QA in mind;

Members must be capable of performing multiple roles

The last point is where I'm worried a bit because, as the mantra goes...

Developers make bad testers.

While I understand that, often, developers are "too close" to their code or their colleague's code to make higher-level assessments of quality, I'm not convinced they are de-facto bad testers.  On the contrary, I'm of the opinion that the qualities of a good developer overlap greatly with the qualities of a good tester.

Assuming this is correct, I've been thinking of different ways of getting around the dev/tester problem and I believe I have come up with a viable model.

My model requires:

A small software house with 2+ projects

An Agile (iterative) approach to development and delivery

1 team per project

All team members will be Software Developers

Their job description will clearly state Development, Quality Assurance, Testing, and Delivery as responsibilities

If all these preconditions have been met, then the projects can be organized in the following fashion (this example will refer to two projects, A and B):

Every team member will alternate between Developer role and Tester role

If a team member is a Developer on project A, they will be a Tester on project B

Members will work on only 1 project at a time, and therefore are expected to be acting as either a Dev or a Tester.

A Role Cycle consists of 3 iterations as a Dev and 2 iteration as a Tester (again, on two different projects)

Project teams would have 3 Devs and 2 Testers at all times.

Member Role Cycles should be out of phase by 1 iteration.

This minimizes the abruptness of the team changes.  For each iteration, 2 Devs and 1 Tester will remain the same as the previous iteration.

Given the above, I see the following Pros and Cons:

Pros

Distributes project knowledge throughout the company.

Ensures team members aren't testing the code they helped write.

Out-of-phase role cycles means no project ever has a 100% member switch.

Alternating roles breaks the monotony of boring projects.

Cons

The iterations of both projects are tightly coupled.  If one project were to cancel an iteration halfway through and start again, then the two projects would be out of sync.  This would make the role-cycle difficult to manage.

Hinges on hiring Developers open working as Testers as well.

I've received mixed reviews when discussing this approach with friends and colleagues.  Some believe that few developers would ever want to alternate roles like this, while others tell me they personally would love to try it.

So my question is:  Could such a model work in practice?  If not, could it be tweaked into a working model?

Note:  For the sake of brevity I have only focused on the Dev and Tester roles.  I'll expand on other roles if needed.


答:
A non-recursive answer: divide the apples into two piles, so they are as close as possible equal. Then, eat the smallest apple in the largest pile.

Halving the pile is left to the reader, but remember that the difference in pile size can be no larger than the smallest apple in the largest pile; if it is any larger, then moving that apple to the other pile will give you a closer answer. It can also not be larger than the difference between an apple in the larger pile, and the next smaller apple in the smaller pile - if the larger pile contains a 600 gramme apple, and the smaller pile contains a 500 gramme apple, and the difference between the two piles is more than 100 grammes, then you could swap those two apples and get closer.

For example, if you have 300+400+500 gramme, you should divide them into two piles, each being as close as possible to (300+400+500)/2=600 gramme. This comes out as one being 500 gramme, the other being 300+400=700 gramme. Eat the smallest apple from the largest (700 gramme) pile - i.e. the 300 gramme apple.

In the case of 100+200+300+900, the closest you can get to two piles of 750 grammes each is one pile of 900, the other of 600, eat the largest (and only) apple from the largest (900 gramme) pile.

Title: Apple eating problem


问:
Is more dependency inversion always better?
Is there any situation in industrial object-oriented programming when the dependency inversion principle should not be used? </p>

答:
Yes: whenever supporting the easy exchange of collaborators would be more work than it saves, then it isn't worthwhile.

In general, there are very few principles that you should follow in 100% of cases. Decoupling is generally good because it allows reuse, better understanding of large code bases, faster implementation of unexpected changes, etc. It looks especially good in comparison with current industry practice in the 70s and 80s, when monolithic one-module applications and absolute, pervasive dependence on one database or lookup provider was commonplace. (Back then, modularization wasn't a thing, and many programming languages didn't support it, often you didn't even have a choice of database, etc.) This created problems when systems became really big, and on the whole, modern software architecture principles turned out to work better than the old way of doing things. To a good approximation, more decoupling (which DI is primarily used for) is good.

But there is always a point of diminishing returns. Any given system has to be put out in a certain time frame and at a limited cost or it isn't worthwhile. Some systems aren't so big that you need to separate everything from everything else to understand them. Sometimes the risk that a collaborator will change isn't big enough to justify the extra architecting necessary to make it easily replaceable. (New messaging protocols pop up every month, but next year's new big thing will probably still run over TCP/IP). Deciding whether you need to be able to react nimbly to a potential future change comes down to a risk-management decision like any other in engineering.


问:
PHP OOP - Getters / setters vs. database storing

Problem

I am trying to optimize the architecture of my web-application developed in PHP using the Symfony framework.

I have an object "pool" that contains "swimmers". I need to display the number of swimmers in my pool, but only those with a pink bath-suit.

In order to do this, I see many possible approaches :

Approaches

Create a custom getter method in my Pool class, and filters the swimmers by bath suits color :

```<code>public function getSwimmersInPinkSuit() {
    for each($this->getSwimmers() as $swimmer) {
        if($swimmer->getBathSuitColor() == "pink") {
             $pinkSwimmers[] += $swimmer;
        }
    return $pinkSwimmers;
}
</code>```

{{ pool.getSwimmersInPinkSuit | length }}

Create a custom SQL query in my controller, define the number there before sending it to my template.

Add a "$pinkSwimmers" property to my Pool class, and increment/decrement it with an eventListener every time I persist in database the event "a pinkSwimmer joins/leaves the pool". I then can access the value where i want :

{{ pool.pinkSuits }}

Use a denser twig request to filter out the pink swimmers directly in my template

{{ pool.swimmers.suitColor("pink") | lenght }} // If that's even possible o0

Question

In the four propositions above, I see pros and cons to each of them, so :

What is the best practice in this situation ? Am I overseeing a better logic in addition to the ones mentioned above ? I try to find an implementation that would be lightweight in term of performance (memory, bandwidth), but also easy to reconfigure (change from pink to green suits, or from suit color to swimming style).

答:
From the comments, it appears as though you are searching 250 swimmers with 25 properties each.

Even if this is done by application code, it should still take an unnoticeable amount of time,  unless you are making N queries per swimmer, or any sort of complex lookup per swimmer.  If this is the case, look up the N+1 select problem and use the minimum number queries/lookups to build your swimmers.

SO answer on N+1 select

PHP article on N+1 select


问:
Member functions vs. Non-member functions for math operators
I'm writing a linear algebra library (long story short, it's a school assignment) that involves matrices, vectors, etc.  In the process of creating this library, I'm going to be creating functions that perform mathematical operations on objects.  For example, transpose matrix, invert matrix, normalize vector, etc.

I was curious as to what is the "best practice" for this sort of function...  That is, should I make the function a member function, or non-member?  (For clarity/library use sake)

Example:

```<code>//Member function way:
B = A.transpose();
C = A.inverse();

//Non-member function way:
B = linalg::transpose(A); //Non-member transpose function in linear algebra namespace
C = linalg::inverse(A);
</code>```

Is there some standard regarding these sorts of operations?  Or, at least, is there a common way people do this?  I'm leaning towards the first option, but I'd like to know if this is recommended.

答:
Both member and non-member functions have real advantages besides mere taste. For example, the underlying array(s) used to implement a matrix class will probably be private, therefore, you will have to use friend unless you use member functions. In this respect, an OO design may be better.

However, keep in mind that, from time to time, computer scientists have to implement complex math formula without always knowing what thy really do. When I have to do so, I prefere non-member functions since the "visual" result will be closer to the original math formula (since math formula generally use a functional style).

In the end, the answer is the same as Doc Brown's one: it's a matter of taste. In short, you could consider writing an OO-style library with member functions (easier to write, no friend), then writing non-member functions to do the same tasks which will simply forward their arguments to the member ones. It allows you to be consistent and to let the user choose what he thinks is best.


Title: How do you version your files (Version Numbers)

Body: I wonder how do you decide on the version number of your apps, do you really record down all changes made (for a change log)? Then how will you decide how to increment the version number. eg. +0.0.1 for each bug fix or something, +0.1 for each new feature release? or maybe you bundle many changes into +0.1 of your version number?</p>

Body: Major.Minor.Revision.Build


问:
How to write camel case for words like "phonenumber", "motorcycle", "wavelength", etc
I am having a problem in understanding how to apply camelCase syntax to some of my variable names.

For example, how should I correctly write a word like "phonenumber" in camel case?  Is it phoneNumber or phonenumber?  Similarly with "username", is it username or userName?

I think it doesn't look right with camel case like motorCycle, passWord, sunDay, setUp or waveLength since these are just one word each. I think that could be why it's called hashMap but also hashtable in camel case without the capital in the last case because hashtable is one word while hash map is two words.

But if the motorcycle has a color then would it be motorcycleColor since a word is concatenated?  Is that correct or should it be phoneNUmber, waveLength, sunBlock and even sunDay for the Sunday of the week?

Why for instance is the method called getISOCountries while it says HttpHeaders e.g. it's not clear what becomes lowercase if we have a method like String camelCaseString = dog.toCamelCase() or interface CamelCase.

Related: https://english.stackexchange.com/questions/889/when-should-compound-words-be-written-as-one-word-with-hyphens-or-with-spaces

答:
This is where a complication with plain English gets in the way of how one later abuses English to fit with the white-space rules of tokens in programming contexts.

Of the example words you give, almost all are compounds. Sunday isn't, as while it originated as a compound, it did so so long ago that it can scarcely be considered one now, especially as its being dedicated to the sun is more a historical curiosity than a strong part of the religious and cultural outlook of English-speaking people.

And in English, the three main ways to write a compound are open (with a space between the two words), hyphenated, and closed (with no space or hyphen between the two). And while there are some rules about hyphenating open compounds in certain situations, there isn't really much in the way of firm rules for knowing what form is used for a given compound beyond seeing what other people do, and there are still times when you'll find two or even all three forms (eggbeater, egg-beater and egg beater for example).

Here, phone number is almost always written open, so it should be treated as two words.

And when inter-capping to form a token, the space or hyphen is removed and the second and subsequent word written in title-case, hence phoneNumber or PhoneNumber as appropriate for your convention.

The thing that makes phoneNumber seem strange is probably that it's more commonly just given as phone in most contexts, or as number when the context is about a telephonic connection.


问:
can a software be an ERP and CMS simultaneously
I was reading about CMS and ERP. And got confused at this point that whether a system can both be an ERP and a CMS? is it possible?</p>

答:
An example, though maybe a contrived one but one I encounterd in the wild a long time ago:

An application was built that would store incoming documents pertaining to required reports sent in by customers of a financial services company.

The same application also served to automatically send out reminder letters to customers who were late sending in those documents, and as an entry point for the telephone support people in the company to look up customer information if customer called (or had to be called).

In that case both functionalities were closely intertwined. In other systems both functionalities might exist but not be as tightly linked (think something like SAP or Lotus Notes).


答:
Sure - you can program whatever you like. Whether it makes any sense is a different question.

As for whether having an ERP/CMS hybrid makes sense or already exists - I don't think so. There are some vague similarities and overlaps in that both will typically allow you to define your own entities with fields ("document types" in a CMS, "business objects" in an ERP) and present a web interface for data entry and publishing, but at heart they have completely different purposes.

Title: can a software be an ERP and CMS simultaneously

Body: I was reading about CMS and ERP. And got confused at this point that whether a system can both be an ERP and a CMS? is it possible?</p>


问:
Is there a web-specific reason for the design choices behind the JavaScript language?
With the advent of "the web is the platform", JavaScript is fast becoming the most widely used programming language in the world.

However, many tasks that are easy to accomplish in other modern languages are difficult or puzzling in JavaScript, because the language design is so "unique":

JavaScript has a prototype-based OOP system; most other modern languages have an inheritance-based one

JavaScript has such a weird typing system that it doesn't fall into any of the standard categories (plenty of examples on WTFJS)

JavaScript is extremely lenient in how it parses the syntax (semicolons are optional etc.)

From a developer's point of view, most of these design decisions make developing in JavaScript harder. Conceptually, the JavaScript language seems one step behind Java, and two steps behind Python and Ruby. But since I don't believe that the people behind JavaScript are striving to create a language that is difficult to use, I can only reason that those design points must have something to do with the intended use of JavaScript as a scripting language for web sites, deeply connected to the DOM.

How (if at all) do these design points cater to the intended use cases of JavaScript? What reasoning is behind those seemingly random design decisions?

答:
Doug Crockford has answered your question in the video "JavaScript: The Good Parts":
http://www.youtube.com/watch?v=hQVTIJBZook

Just because JavaScript is different, it doesn't mean it's worse. The problems is when you try to make a classical inheritance in JS - but you shouldn't. Prototypes are quite great once you get to understand it.

BTW: Go (golang) has escaped classical inheritance in favor for embedding. Some people say it's liberating.


答:
In a very theoretical sense yes. But in most cases this would not make very much sense. The basic functionality of an ERP system is business management. The data produced here may become part of the data displayed on a web site. But normally the data here is pure text and numbers, like definitions of products, orders, invoices and some statistical information.

An CMS main task is to provide information in a way that not only the content as such can be edited but often enough the representation and styling too. Its functionality is much more limited and the amount of data normally far less than in an ERP system.

In our company for example all our product and customer data is kept in an ERP system. Customers can login and search products, order them and see shipment and invoice data. All this they get directly from the ERP system. Some information in the ERP is specifically there for the web site (for example our product categories for the web site are slightly different from those used internally for statistical purposes). But this data is purely information. In theory this ERP system would have a lot of options to store even more information, even combined with some styling information. We don't use this.

Information that we do not actually need for business purposes is edited in a small CMS system for the web site. This includes things like a news section, some pages with company information and similar more text/style oriented data. We could store this in the ERP too, there are tables for such things, but it is more effort to code in the ERP area and then we would have more effort to display on the web.


答: Generally it's a Major.minor.revision number. The major and minor number are choosen by the marketing types to reflect the awesomeness or lack of awesomeness in the new release. The revision number is dictated by the version control system.</p>


问:
How to address the concerns of the software architect but still maintain collective code ownership?
The quality of the code in our software is indeed lacking. When you change a line of code in one component it usually breaks code in other components.

Our software architect blames this on collective code ownership. He believes that if every developer was responsible for his own piece of code then he would tidy it up all the time because he would feel ownership over the component.

In the current situation, developers change code in multiple components and they break other components either because they don't understand how the component works (because they work with so many components) or because they don't care about how their changes will affect the other clients of the component (as long as they are not affected).

How can I address the concerns of the software architect but still maintain collective code ownership?

答: Just three things: code reviews, code reviews, code reviews - they will help you improve the code quality as well as the feeling of responsibility for "the shared code".</p>


答:
When you change a line of code in one component it usually breaks code
  in other components. ...if every developer was responsible for his own
  piece of code then he would tidy it up all the time because he would
  feel ownership over the component.

So hang on, if the problem is that updating your component breaks someone else's component (due to a dodgy architecture that doesn't have any decent decoupling), how is it that making a component be owned by a developer suddenly stops someone else's component magically decouple so it doesn't break on updating the first!?!

The only answer is to properly organise the components so that are no longer as intertwined as they currently are. That, and documenting the interfaces and data contracts between them.

I do agree with component ownership as it can help with quality of a lot more than just code, but a substitute is code reviews - someone after all needs to know a lot about each component in order to enforce the API and correct behaviour of it. In this case, I think code reviews are just a way of implementing ownership anyway.

Title: How to address the concerns of the software architect but still maintain collective code ownership?

Body:
The quality of the code in our software is indeed lacking. When you change a line of code in one component it usually breaks code in other components.

Our software architect blames this on collective code ownership. He believes that if every developer was responsible for his own piece of code then he would tidy it up all the time because he would feel ownership over the component.

In the current situation, developers change code in multiple components and they break other components either because they don't understand how the component works (because they work with so many components) or because they don't care about how their changes will affect the other clients of the component (as long as they are not affected).

How can I address the concerns of the software architect but still maintain collective code ownership?