答:
OOP is also about Separation of concerns, that is to separate different roles/responsabilities in different objects.

MVC separates into these components :

Model : the data and its business logic

View : representation of the data

Controller : coordination between the model and the view.

So these responsabilities are clearly distinct and should indeed be separated into multiple entities.

Title: Isn't MVC anti OOP?


问:
Is it the job of a developer to suggest IT requirements?
I am the only developer working on a web application which is nearing to its end. Now we are looking into making it Live in maybe a couple of months time.

This is a web application for a non IT company. Though they have their own internal IT team, they have asked me on what will be the hardware requirements for the live servers eg. RAM, 32 bit or 64 bit.

Shouldn't the internal IT team be doing this or since I am the only person working on the project is it my resposiblity to let them know of the any specific hardware requirements which may impact the performance of the project?

The reason I am asking this question is that, I have not done this before. All the times I used to be given a server and asked to deploy apps on it. I never used to worry about the server configuration, etc.

答:
At this point in the process, they should absolutely be asking you for this information.  The developer/development team is not just responsible for writing code.  It is your job to understand the application you are building and all of its inner workings.  This knowledge should have come from your internal design meetings.  Who better to evaluate the execution profile of the system with all of its nuances than the team/developer who built it.

This late in the game, I would be more concerned if they were dictating the server configuration instead of asking me.

ContentLicense: CC BY-SA 3.0


问:
Isn't MVC anti OOP?
The main idea behind OOP is to unify data and behavior in a single entity - the object. In procedural programming there is data and separately algorithms modifying the data.

In the Model-View-Controller pattern the data and the logic/algorithms are placed in distinct entities, the model and the controller respectively. In an equivalent OOP approach shouldn't the model and the controller be placed in the same logical entity?

答:
OOP does not restrict interactions among objects that each have their own data and their own behavior.

Think of an ant and an ant colony analogy: behavior of an individual ant (run around all day, bringing food) is different from behavior of the overall colony (find the most desirable place, make more ants). The MVC pattern describes the desired social structure of an ant colony, while OOP guides the design of individual ants.

Title: Isn't MVC anti OOP?


问:
Is a "model" branch a common practice?
I just thought it could be a good thing to have a dedicated version control branch for all database schema changes and I wanted to know if anyone else is doing the same and what have the results been.

Say that you are working with:

Schema model/documentation (some file where you model the database visually to generate the schema source, say MySQL Workbench, with a .mwb file, which is binary)

Schema source (a .sql file)

Schema-based code generation

The normal way we were working was with feature branches, so we would do changes to the model files (the database specific ones), and then have to regenerate points 2 and 3, dealing with the possible conflicts (or even code rewriting).

Now say that your workflow goes the same way as the previous item numbering. With a model branch you wouldn't have to reconcile the schema model with binaries in other feature branches, or have to regenerate schema source and regenerate code (which might have human code on top of it).

It makes so much sense to me it feels weird not having seen this earlier as a common practice.

Edit: I'm counting on branch merges to be the assertions for the model matching the code. I use a DVCS, so I don't fear long-lived branches or scary-looking merges. I'm also doing feature branching.

答:
It's bad idea in terms of "development philosophy" and usability

you have broken rule "branch per task/feature" - model branch have not related task (or more than one task in timespan)

This branch will be "forever-live" branch

additional permanent merges with features-branches and broken builds if merge missed after schema-changes

Title: Is a "model" branch a common practice?


答:
The model layer is not merely data any more than the controller layer is merely logic.

The controller layer will have a complete collection of objects for its purposes. There will be objects for receiving input from the view, and from transforming that input into a form the model can process. The Struts Java framework has a good example of this in its Action/Form model. The Form is populated with input from the user, and then passed to the Action. The Action takes that data and uses it to manipulate the model.

In the same way, the Model layer doesn't consist entirely of data. Take a User object, for example - you may need code that gets a user from a database, or code to associate a User with an Order, or to validate that the User's address is within the area your company services...you get the picture. This is not controller logic. It's business logic, and it's led many to split their Model layer into several layers such as Service or Manager layers for business logic, a DAO (Database Access Object) layer for database access, and others.

MVC isn't a method for organizing individual Model operations. It works at a higher level than that - it's a method for organizing how the application is accessed. View is for presenting data and human actions for manipulating it, Controller is for translation between user actions and the various views, and the Model is where business data and the business reasons for it to exist reside.

Title: Isn't MVC anti OOP?

Body:
The main idea behind OOP is to unify data and behavior in a single entity - the object. In procedural programming there is data and separately algorithms modifying the data.

In the Model-View-Controller pattern the data and the logic/algorithms are placed in distinct entities, the model and the controller respectively. In an equivalent OOP approach shouldn't the model and the controller be placed in the same logical entity?


答:
In the Model-View-Controller pattern the data and the logic/algorithms
  are placed in distinct entities, the model and the controller
  respectively.

Model and controller are two distinct roles. A model has both state and logic, and a controller has both state and logic. The fact that they communicate doesn't break the encapsulation of either one -- the controller doesn't know or care how the model stores its data, or what it does to the data when the controller retrieves or updates some part of it. The model doesn't know or care what the controller does with data that the model provides.

Think of it this way: if objects couldn't pass data back and forth without breaking encapsulation, you could really only have one object!

In an equivalent OOP approach shouldn't the model and the controller
  be placed in the same logical entity?

MVC is an OOP approach -- specifically, it's a recipe for deciding how to use objects to organize a program effectively. And no, the model and controller shouldn't be the same entity. A controller allows separation between model and view. Keeping model and view independent of each other makes them both more testable and more reusable.

Title: Isn't MVC anti OOP?


问:
How is IntelliJ better than Eclipse?
I know there have been questions like What is your favorite editor/IDE?, but none of them have answered this question: Why spend the money  on IntelliJ when Eclipse is free?

I'm personally a big IntelliJ fan, but I haven't really tried Eclipse. I've used IntelliJ for projects that were Java, JSP, HTML/CSS, Javascript, PHP, and Actionscript, and the latest version, 9, has been excellent for all of them.

Many coworkers in the past have told me that they believe Eclipse to be "pretty much the same" as IntelliJ, but, to counter that point, I've occasionally sat behind a developer using Eclipse who's seemed  comparably inefficient (to accomplish roughly the same task), and I haven't experienced this with IntelliJ. They may be on par feature-by-feature but features can be ruined by a poor user experience, and I wonder if it's possible that IntelliJ is easier to pick up and discover time-saving features.

For users who are already familiar with Eclipse, on top of the real cost of IntelliJ, there is also the cost of time spent learning the new app. Eclipse gets a lot of users who simply don't want to spend $250 on an IDE.

If IntelliJ really could help my team be more productive, how could I sell it to them? For those users who've tried both, I'd be very interested in specific pros or cons either way.

答:
Intellij is better for many reasons, not least the darcula theme ... but there are a few others :

autocomplete for method names  - it offers what I want to call them usign convention.

jquery autocomplete very easy to set up (never got it workign with
eclipse).

EL autocomplete in jsp's

spring integration and inspection shows errors in set up (eg
duplicate bean names)

autocomplete for controller/url mappings

easy to use and set up database integraion (it detects the datasource
automatically) and autocomplete obviously

code inspections, like checkstyle and findbugs, built in and easy to use.

jslint and jshint built in and easy to use.

maven integration works out of the box straight away.

All the settings are where you expect them to be.

It does not detect errors incorrectly, I used to get highlighted
errors in eclisp ewhere there were none and had to restart.

Autocomplete and error detection in xml files (a big deal with spring)

hibernate mappings have autocomplete enabled (a pojos' fields are supplied as autocomplete option in the mapped pojo - gr8).

ctrl+alt+click opens the implentation, not the declaration

Hotdeploy : you can easily set it up so that when intellij loses
focuses your deployed app gets updated automatically - I alt tab to
my browser and the new code (be it classes, javascript, or jsps) is
already deployed.

a built in rest client with no extra config required.

built in chat client that allows code pointers - actually very
useful.

persistence view, easy access to your all your jpa/hibernate entities
and settings.

bug fixing, actual accountable bug fixing I have submitted a number
of bugs and they have been fixed promptly.

inspection and autocomplete in your xml documents, very very useful
with spring (I know this is a repeat but it is great, revealed a myriad of errors).

I have been using it abotu 3 weeks now so hopefully find some more soon; its well worth the money.

Oh one more thing it actually opens ... I had a bug in my eclipse that meant it would refuse to open. Just "google eclipse wont open" there are loads of links. I feel stupid for taking this long to change.

Title: How is IntelliJ better than Eclipse?


问:
git changing head not reflected on co-dev's branch
Basically, we undid history.  I know this is bad, and I am already committed to avoiding this at all costs in the future, but what is done is done.

Anyway, I issued a git push origin <1_week_old_sha>:master to undo some bad commits.  I then deleted a buggered branch called release(which had also received some bad commits) from remote and then branched a new release off master.  I pushed this to remote.  So basically, remote master & release are clones and just how I want them.

The issue is if I clone the repo anew(or work in my current repo) everything looks great....but when my co-devs delete their release branch and create a new one based off the new remote release I created, they still see all the old junk I tried to remove.

I feel this has to do with some local .git files mistaking the new branch release for the old release.

Any thoughts?  Thanks.

答:
So the branch is still synced to the local site. It needs to be reset to the commit in the remote. I think, ideally, what you would want to do...

```<code>$ git checkout release
$ git reset --hard origin/release
$ git checkout master
$ git reset --hard origin/master
</code>```

Or... if they have everything locally pushed, they can just delete the local repo and clone again.

In the future, instead of rewriting history, it's normally easer to just revert those commits. You'll still see the history but the code won't be in HEAD of that branch.

Body:
So the branch is still synced to the local site. It needs to be reset to the commit in the remote. I think, ideally, what you would want to do...

$ git checkout release
$ git reset --hard origin/release
$ git checkout master
$ git reset --hard origin/master

Or... if they have everything locally pushed, they can just delete the local repo and clone again.

In the future, instead of rewriting history, it's normally easer to just revert those commits. You'll still see the history but the code won't be in HEAD of that branch.


问:
Naming Convention for Dedicated Thread Locking objects
A relatively minor question, but I haven't been able to find official documentation or even blog opinion/discussions on it.

Simply put: when I have a private object whose sole purpose is to serve for private lock, what do I name that object?

```<code>class MyClass
{
    private object LockingObject = new object();

    void DoSomething()
    {
        lock(LockingObject)
        {
            //do something
        }
    }
}
</code>```

What should we name LockingObject here? Also consider not just the name of the variable but how it looks in-code when locking.

I've seen various examples, but seemingly no solid go-to advice:

Plenty of usages of SyncRoot (and variations such as _syncRoot).

Code Sample: lock(SyncRoot), lock(_syncRoot)

This appears to be influenced by VB's equivalent SyncLock statement, the SyncRoot property that exists on some of the ICollection classes and part of some kind of SyncRoot design pattern (which arguably is a bad idea)

Being in a C# context, not sure if I'd want to have a VBish naming. Even worse, in VB naming the variable the same as the keyword. Not sure if this would be a source of confusion or not.

thisLock and lockThis from the MSDN articles: C# lock Statement, VB SyncLock Statement

Code Sample: lock(thisLock), lock(lockThis)

Not sure if these were named minimally purely for the example or not

Kind of weird if we're using this within a static class/method.

EDIT: The Wikipedia article on locks also uses this naming for its example

Several usages of PadLock (of varying casing)

Code Sample: lock(PadLock), lock(padlock)

Not bad, but my only beef is it unsurprisingly invokes the image of a physical "padlock" which I tend to not associate with the abstract threading concept.

Naming the lock based on what it's intending to lock

Code Sample: lock(messagesLock), lock(DictionaryLock), lock(commandQueueLock)

In the VB SyncRoot MSDN page example, it has a simpleMessageList example with a private messagesLock object

I don't think it's a good idea to name the lock against the type you're locking around ("DictionaryLock") as that's an implementation detail that may change. I prefer naming around the concept/object you're locking ("messagesLock" or "commandQueueLock")

Interestingly, I very rarely see this naming convention for locking objects in code samples online or on StackOverflow.

(EDIT) The C# spec under section "8.12 The Lock Statement" has an example of this pattern and names it synchronizationObject

Code Sample: lock(SynchronizationObject), lock(synchronizationObject)

Question:
What's your opinion generally about naming private locking objects?

Recently, I've started naming them ThreadLock (so kinda like option 3), but I'm finding myself questioning that name.

I'm frequently using this locking pattern (in the code sample provided above) throughout my applications so I thought it might make sense to get a more professional opinion/discussion about a solid naming convention for them. Thanks!

答:
I've taken to the habit of calling it SomeResourceLock where the SomeResource is what you need the lock to access/update, i.e. (forgive any thread issues, this is just an illustration)

```<code>public class ProcessDataInQueue
{
    private static Queue<Data> _dataQueue = new Queue<Data>();
    private static object _dataQueueLock = new Object();

    public void AddOneItem(Data itemToAdd)
    {
        lock(_dataQueueLock)
        {
            _dataQueue.Enqueue(itemToAdd);
        }
    }

    public void ProcessOneItem()
    {
        Data itemToProcess = null;
        lock(_dataQueueLock)
        {
            itemToProcess = _dataQueue.Dequeue();
        }
        // ... process itemToProcess
    }
}
</code>```

I've come upon this habit after having classes where I may have multiple locks for different resources, so I name the locking object based on what resources it's locking access to. Sometimes one object may be locking multiple resources in which case I would try to make the names respect that in some way, so the reader knows "other locks for those individual resources will be in contention with this lock as well".

Body:
I've taken to the habit of calling it SomeResourceLock where the SomeResource is what you need the lock to access/update, i.e. (forgive any thread issues, this is just an illustration)

public class ProcessDataInQueue
{
    private static Queue<Data> _dataQueue = new Queue<Data>();
    private static object _dataQueueLock = new Object();

    public void AddOneItem(Data itemToAdd)
    {
        lock(_dataQueueLock)
        {
            _dataQueue.Enqueue(itemToAdd);
        }
    }

    public void ProcessOneItem()
    {
        Data itemToProcess = null;
        lock(_dataQueueLock)
        {
            itemToProcess = _dataQueue.Dequeue();
        }
        // ... process itemToProcess
    }
}

I've come upon this habit after having classes where I may have multiple locks for different resources, so I name the locking object based on what resources it's locking access to. Sometimes one object may be locking multiple resources in which case I would try to make the names respect that in some way, so the reader knows "other locks for those individual resources will be in contention with this lock as well".


答:
I always used lck_. That way if you ctrl+f 'lck' then you should only find the locks whilst 'lock' will also find things like 'clock'.

Things like lockThis and Padlock are fine for uni portfolios but for proper projects you should really use semantic names so that when you look at the declarations you know what the object actually does without searching through the code.

Title: Naming Convention for Dedicated Thread Locking objects

Body:
A relatively minor question, but I haven't been able to find official documentation or even blog opinion/discussions on it.

Simply put: when I have a private object whose sole purpose is to serve for private lock, what do I name that object?

```<code>class MyClass
{
    private object LockingObject = new object();

    void DoSomething()
    {
        lock(LockingObject)
        {
            //do something
        }
    }
}
</code>```

What should we name LockingObject here? Also consider not just the name of the variable but how it looks in-code when locking.

I've seen various examples, but seemingly no solid go-to advice:

Plenty of usages of SyncRoot (and variations such as _syncRoot).

Code Sample: lock(SyncRoot), lock(_syncRoot)

This appears to be influenced by VB's equivalent SyncLock statement, the SyncRoot property that exists on some of the ICollection classes and part of some kind of SyncRoot design pattern (which arguably is a bad idea)

Being in a C# context, not sure if I'd want to have a VBish naming. Even worse, in VB naming the variable the same as the keyword. Not sure if this would be a source of confusion or not.

thisLock and lockThis from the MSDN articles: C# lock Statement, VB SyncLock Statement

Code Sample: lock(thisLock), lock(lockThis)

Not sure if these were named minimally purely for the example or not

Kind of weird if we're using this within a static class/method.

EDIT: The Wikipedia article on locks also uses this naming for its example

Several usages of PadLock (of varying casing)

Code Sample: lock(PadLock), lock(padlock)

Not bad, but my only beef is it unsurprisingly invokes the image of a physical "padlock" which I tend to not associate with the abstract threading concept.

Naming the lock based on what it's intending to lock

Code Sample: lock(messagesLock), lock(DictionaryLock), lock(commandQueueLock)

In the VB SyncRoot MSDN page example, it has a simpleMessageList example with a private messagesLock object

I don't think it's a good idea to name the lock against the type you're locking around ("DictionaryLock") as that's an implementation detail that may change. I prefer naming around the concept/object you're locking ("messagesLock" or "commandQueueLock")

Interestingly, I very rarely see this naming convention for locking objects in code samples online or on StackOverflow.

(EDIT) The C# spec under section "8.12 The Lock Statement" has an example of this pattern and names it synchronizationObject

Code Sample: lock(SynchronizationObject), lock(synchronizationObject)

Question:
What's your opinion generally about naming private locking objects?

Recently, I've started naming them ThreadLock (so kinda like option 3), but I'm finding myself questioning that name.

I'm frequently using this locking pattern (in the code sample provided above) throughout my applications so I thought it might make sense to get a more professional opinion/discussion about a solid naming convention for them. Thanks!


答:
I usually call it locker, but since it's private, I believe it's a somewhat unimportant implementation detail. First rule of thumb, use your team's/company's standards. If there is not one, well, please make one and use it, but in making it, keep things simple. If your class has a single locking object, calling it foo is good enough. If you have many, a good order of business might just be revisiting that class's design first to see if it's doing too many different things. But, if not, then the name becomes important, as in this completely contrived example:

```<code>public sealed class CustomerOrders
{
    private readonly object customerLocker = new object();

    private readonly object orderLocker = new object();

    public IEnumerable<Customer> Customers
    {
        get
        {
            lock (this.cutomerLocker)
            lock (this.orderLocker)
            {
                // stuff...
            }
        }

        set
        {
            lock (this.cutomerLocker)
            lock (this.orderLocker)
            {
                // other stuff...
            }
        }
    }

    public IEnumerable<Order> Orders
    {
        get
        {
            lock (this.orderLocker)
            {
                // stuff...
            }
        }

        set
        {
            lock (this.cutomerLocker)
            {
                // different stuff...
            }
        }
    }
}
</code>```

Body:
I usually call it locker, but since it's private, I believe it's a somewhat unimportant implementation detail. First rule of thumb, use your team's/company's standards. If there is not one, well, please make one and use it, but in making it, keep things simple. If your class has a single locking object, calling it foo is good enough. If you have many, a good order of business might just be revisiting that class's design first to see if it's doing too many different things. But, if not, then the name becomes important, as in this completely contrived example:

public sealed class CustomerOrders
{
    private readonly object customerLocker = new object();

    private readonly object orderLocker = new object();

    public IEnumerable<Customer> Customers
    {
        get
        {
            lock (this.cutomerLocker)
            lock (this.orderLocker)
            {
                // stuff...
            }
        }

        set
        {
            lock (this.cutomerLocker)
            lock (this.orderLocker)
            {
                // other stuff...
            }
        }
    }

    public IEnumerable<Order> Orders
    {
        get
        {
            lock (this.orderLocker)
            {
                // stuff...
            }
        }

        set
        {
            lock (this.cutomerLocker)
            {
                // different stuff...
            }
        }
    }
}


问:
Is there a constant for "end of time"?
For some systems, the time value 9999-12-31 is used as the "end of time" as the end of the time that the computer can calculate. But what if it changes? Wouldn't it be better to define this time as a builtin variable?

In C and other programming languages there usually is a variable such as MAX_INT or similar to get the largest value an integer could have. Why is there not a similar function for MAX_TIME i.e. set the variable to the "end of time" which for many systems usually is 9999-12-31. To avoid the problem of hardcoding to a wrong year (9999) could these systems introduce a variable for the "end of time"?

**Real example **

End of validity date: 31/12/9999. (official documents are listed like this)
The blogger wants to write a page that is always on top, the welcome page. So it's given a date as far in the future as possible:

3000? Yes, the welcome page which you're facing is posted at 1 January
  3000. So this page will be kept on the top of the blog forever =) It's actually posted at 31 august 2007.

答: Store your times as a 64 bits IEE754 double precision floating point number, and you can use +INF. Don't use single-precision, that's only accurate to 7 digits which is a bit low for a date.

Title: Is there a constant for "end of time"?


答:
Disclaimer

This is limited to Android development only (In Java obviously).

I am coming to this with some limited knowledge of Eclipse and IntelliJ both; however, I have recently had to decide on a development environment for Android. It would seem that the first clear choice would be to use Eclipse since Google supports it with their ADT plugin. Unfortunately, I found it terribly clunky to get around since I am used to Visual Studio (2010, more recently 2012). I have always used ReSharper with Visual Studio so I decided to give IntelliJ a try. After about 10 minutes I realized that I had made the right decision.

IntelliJ, as some have stated, indexes everything. The intellisense was a joy to work with and the intelligence surrounding suggestions was excellent. The debugging experience I found to be a pleasure and quite honestly, I really couldn't live without the code analysis. I know a lot of purists would have a problem with that kind of thing but I don't care. I have to push out projects very quickly for lots of people so sometimes it's just nice to run the code anaylsis and see what the IDE suggests. Whether or not you take those suggestions is another story but I didn't find anything like this in Eclipse.

Some also say that there is no Android designer in the current version of IntelliJ. This is certainly the case but I wouldn't ever use it anyway. I am debugging on a device most of the time so it doesn't matter. I get to see the interface and play with it everytime I run the program. Anyway, from a traditionally "non-Java" guy I have to say that Java is particularly nice as compared to Eclipse.

Title: How is IntelliJ better than Eclipse?

Body:
I know there have been questions like What is your favorite editor/IDE?, but none of them have answered this question: Why spend the money  on IntelliJ when Eclipse is free?

I'm personally a big IntelliJ fan, but I haven't really tried Eclipse. I've used IntelliJ for projects that were Java, JSP, HTML/CSS, Javascript, PHP, and Actionscript, and the latest version, 9, has been excellent for all of them.

Many coworkers in the past have told me that they believe Eclipse to be "pretty much the same" as IntelliJ, but, to counter that point, I've occasionally sat behind a developer using Eclipse who's seemed  comparably inefficient (to accomplish roughly the same task), and I haven't experienced this with IntelliJ. They may be on par feature-by-feature but features can be ruined by a poor user experience, and I wonder if it's possible that IntelliJ is easier to pick up and discover time-saving features.

For users who are already familiar with Eclipse, on top of the real cost of IntelliJ, there is also the cost of time spent learning the new app. Eclipse gets a lot of users who simply don't want to spend $250 on an IDE.

If IntelliJ really could help my team be more productive, how could I sell it to them? For those users who've tried both, I'd be very interested in specific pros or cons either way.


问:
Of what significance is the solution to the game of checkers in AI research?
I have been doing some research into artificial intelligence and I came across a 2007 paper titled "Checkers is Solved" on the game of checkers being solved by AI techniques after more than 16 years of trial. A solution to the game is defined by the team as  "determining the final result in a game with no mistakes made by either player". The search for a solution started back in 1989 and it was finally found in 2007. Of what importance is this to the field of AI?</p>

答:
When you explore AI, you do so first with a problem space that is relatively small and bounded by specific rules, so that you can prove your techniques.

Checkers is such a space.  It therefore makes an ideal playground for AI explorations.  This is also true of chess, although checkers is a smaller problem space, and therefore is more suitable to simpler explorations of AI. Board games like chess and checkers are easily modelled in a computer using a two-dimensional array.

As your knowledge improves, you can begin to alter your techniques and apply AI to more complex and non-deterministic domains, like human interactions.


问:
How to calculate Sin function quicker and more precisely?
I want to calculate y(n)=32677Sin(45/1024•n), where y is an integer and n ranges from 0 to 2048. How can I make this process quicker and more precisely?
   Now I want to show you a reference answer:
   Since   Sin(a+b)=Sin(a)Cos(b)+Cos(a)Sin(b)
   And  Cos(a+b)=Cos(a)Cos(b)-Sin(a)Cos(b).
   So I can store  Sin(45/1024•1) and  Cos(45/1024•1) only.Then use this formula:

Sin(45/1024•2)=Sin(45/1024•1+45/1024•1),
    Cos(45/1024•2)=Cos(45/1024•1+45/1024•1),
  Sin(45/1024•n)=Sin(45/1024•(n-1)+45/1024•1),
    Cos(45/1024•n)=Cos(45/1024•(n-1)+45/1024•1) ,
This way maybe quicker without storing large array.

答: Given the form of the function, the natural answer is the CORDIC algorithm. It's a much cleaner approach than the breakdown in the question. On the other hand, the table it needs is far, far smaller than the table others have suggested.</p>


问:
Why does Eclipse need to be restarted after installing a plugin?
As Eclipse uses OSGi to handle modules and bundles, and therefore should be able to hot-deploy them, why does it suggest to restart after installing a plugin "for changes to take effect"?

Has Eclipse hit some OSGi limitation, or is its architecture such that even with hot-deploy, it cannot guarantee that deployments went smoothly and hence takes the safest route by offering a restart?

答: Probably because they can't force bundles to release service references, so it might be possible for one bundle to have a service reference to another that's been updated or removed.  That's why they warn that not restarting can lead to unwanted behavior.</p>


答:
As I understand it; The argument is component based architecture vs OOP. And without getting into the religious war, I think that they are both describing the same thing; just looking at it from different angles.

For example, the whole point of OOP/OOD is to make your code more modular and reusable. Yes?

Which is exactly the goal of component based architecture. So they are more alike than anything else.

I think that MVC is just the natural evolution of OOP and dare I say it; a better way to organize your objects, separation of concerns and code reuse.

Title: Isn't MVC anti OOP?


问:
Why not commit unresolved changes?
In a traditional VCS, I can understand why you would not commit unresolved files because you could break the build.  However, I don't understand why you shouldn't commit unresolved files in a DVCS (some of them will actually prevent you from committing the files).

Instead, I think that your repository should be locked from pushing and pulling, but not committing.

Being able to commit during the merging process has several advantages (as I see it):

The actual merge changes are in history.

If the merge was very large, you could make periodic commits.

If you made a mistake, it would be much easier to roll back (without having to redo the entire merge).

The files could remain flagged as unresolved until they were marked as resolved.  This would prevent pushing/pulling.

You could also potentially have a set of changesets act as the merge instead of just a single one.  This would allow you to still use tools such as git rerere.

So why is committing with unresolved files frowned upon/prevented?  Is there any reason other than tradition?

答:
I think it's best to push small changes and push often, when it's possible(and of course it isn't always), and don't commit code that doesn't build, or is half complete(we all make mistakes, but don't do it on purpose). I also come from git, and one of the best things I think is the fact that you can have a workable copy of the repo on your desktop...which you can then modify to your hearts content. When your big changes are done, send it away.

Doing a lot of open source with git the biggest frustration for me was getting half done code plopped into the repo, and trying to do a build, but couldn't, because the guy did half the work and said "I'm busy now, I'll finish it in a week". So I'd end up having to scrap it(which would annoy the guy), or take the time to finish and completely integrate it.

I guess from my perspective, keep the half ass stuff locally, send the good stuff over the wire.

Title: Why not commit unresolved changes?


问:
technique for checking modifications in configuration file while starting up a program
I'm writing a software for periodically checking a specific range of networked devices' reach-ability. I'm specifying the  address range and the time frequency for checking their reachability, in an xml file. Which technique can I use to check that xml file during the start up of the program for any modifications done in either the range or the frequency and do the necessary update in specific database?</p>

答: I´m not an expert in that topic. Maybe you can compute a hash of the file everytime you change the configuration and store it somewhere, and if you start your program you compute the hash again and compare it to the stored hash value. If you do it like that, everybody can look at the configuration file, but if anything was changed you will notice it. The question is then where to store the computed hash. This depends on the security you need.</p>


问:
Do we ethically have the right to use the MAC Address for verification purposes?
I am writing a program, or starting at the very beginning of it, and I am thinking of purchase verification systems as a final step. I will be catering to Macs, PCs, and possibly Linux if all is said and done. I will also be programming this for smartphones as well using C++ and Objective-C. (I am writing a blueprint before going head first into it)

That being said, I am not asking for help on doing it yet, but what I’m looking for is a realistic measurement for what could be expected as a viable and ethical option for purchase verification systems.

Apple through the Apple Store, and some other stores out there have their own "You bought it" check.

I am looking to use a three prong verification system.

Email/password

16 to 32 character serial number using alpha/numeric and symbols with Upper and lowercase variants.

MAC Address.

The first two are in my mind ok, but I have to ask on an ethical standpoint, is a MAC Address to lock the software to said hardware unethical, or is it smart?

I understand if an Ethernet card changes if not part of the logic board, or if the logic board changes so does the MAC address, so if that changes it will have to be re-verified, but I have to ask with how everything is today.

Is it ethical to actually use the MAC address as a validation key or no? Should I be forward with this kind of verification system or should I keep it hidden as a secret? Yes I know hackers and others will find ways of knowing what I am doing, but in reality this is why I am asking.

I know no verification is foolproof, but making it so that its harder to break is something I've always been interested in, and learning how to program is bringing up these questions, because I don't want to assume one thing and find out it's not really accepted in the programming world as a "you shouldn't do that" maneuver.

I am just learning how to program, and I am just making sure I'm not breaking some ethical programmer credo I shouldn't.

答:
This article on MAC Addresses, UDIDs, and Privacy covers your issues pretty well.

To summarize:

MAC addresses are not private.

Spoofing a MAC address is difficult enough to make it an adequate safety measure.

You can voluntarily anonymize the MAC address if privacy is a concern.

Since MAC addresses are transmitted with every IP packet that the user sends, whether you keep your checking mechanism secret or not is kind of a moot point.


问:
Need explanation of hexagonal architecture
I am reading about Alistair Cockburn's Hexagonal Architecture with interest.

One claim he makes is:

Finally, the automated function regression tests detect any violation of the promise to keep business logic out of the presentation layer. The organization can detect, and then correct, the logic leak.

I do not understand this point. Is he saying that because the test is headless, then calls to a UI layer will throw exceptions? That doesn't seem to be a very sound test!

答:
His point is that having a suite of automated tests exercising all the business logic without a UI will make it clear if you have any business logic in the UI.

To make such a test suite, you essentially have to create a very thin testing-only "non-user" interface to supply data and check results.  If any of your business logic is actually in the UI, you'll find yourself replicating that logic in this testing interface, and realize your mistake.

OwnerDisplayName: Victor Grazi

ContentLicense: CC BY-SA 4.0


答:
Don't be a slave to your tools.

The goal of a VCS is to enable you to do your job. Your job is not to keep a pristine local repository, your job is to write code. If committing early and often locally lets you work better, do it.

You shouldn't, however, push broken code upstream.

Title: Why not commit unresolved changes?

Body:
In a traditional VCS, I can understand why you would not commit unresolved files because you could break the build.  However, I don't understand why you shouldn't commit unresolved files in a DVCS (some of them will actually prevent you from committing the files).

Instead, I think that your repository should be locked from pushing and pulling, but not committing.

Being able to commit during the merging process has several advantages (as I see it):

The actual merge changes are in history.

If the merge was very large, you could make periodic commits.

If you made a mistake, it would be much easier to roll back (without having to redo the entire merge).

The files could remain flagged as unresolved until they were marked as resolved.  This would prevent pushing/pulling.

You could also potentially have a set of changesets act as the merge instead of just a single one.  This would allow you to still use tools such as git rerere.

So why is committing with unresolved files frowned upon/prevented?  Is there any reason other than tradition?


答:
MVC is an exercise in Separation of Concerns, a UI architecture.  It is a way to corral the complexity that can occur in user interfaces due to the presentation not being separated from the content.

In theory, all objects can have behavior that operate on the data they contain, and that data and behavior remain encapsulated.  In practice, a given OOP object may or may not have logic that corresponds to its data, or may not have any logic at all (a Data Transfer Object, for example).

In MVC, the business logic goes in the model, not the controller. The controller is really just a go-between to glue together the View and the Model. So in the model, you can have data and behavior in the same place.

But even that arrangement does not guarantee strict data/behavior fusion.  Objects containing only data can be operated on by other classes containing only logic, and this is a perfectly acceptable use of OOP.

I'll give you a specific example. This is a bit contrived, but let's say you have a Currency object, and that object has the ability to represent itself in any available currency, pegged to the dollar.  So you would have methods like:

```<code>public decimal Yen { get { return // dollars to yen; } }
public decimal Sterling { get { return // dollars to sterling; } }
public decimal Euro { get { return // dollars to euro; } }
</code>```

...and that behavior would be encapsulated with the Currency object.

But what if I wanted to transfer the currency from one account to another, or deposit some currency?  Would that behavior also be encapsulated in the Currency object?  No, it wouldn't.  The money in your wallet cannot transfer itself out of your wallet into your bank account; you need one or more agents (a teller or ATM) to assist in getting that money into your account.

So that behavior would be encapsulated into a Teller object, and it would accept Currency and Account objects as inputs, but it would not contain any data itself, except maybe a bit of local state (or maybe a Transaction object) to help process the input objects.

Title: Isn't MVC anti OOP?

Body:
MVC is an exercise in Separation of Concerns, a UI architecture.  It is a way to corral the complexity that can occur in user interfaces due to the presentation not being separated from the content.

In theory, all objects can have behavior that operate on the data they contain, and that data and behavior remain encapsulated.  In practice, a given OOP object may or may not have logic that corresponds to its data, or may not have any logic at all (a Data Transfer Object, for example).

In MVC, the business logic goes in the model, not the controller. The controller is really just a go-between to glue together the View and the Model. So in the model, you can have data and behavior in the same place.

But even that arrangement does not guarantee strict data/behavior fusion.  Objects containing only data can be operated on by other classes containing only logic, and this is a perfectly acceptable use of OOP.

I'll give you a specific example. This is a bit contrived, but let's say you have a Currency object, and that object has the ability to represent itself in any available currency, pegged to the dollar.  So you would have methods like:

public decimal Yen { get { return // dollars to yen; } }
public decimal Sterling { get { return // dollars to sterling; } }
public decimal Euro { get { return // dollars to euro; } }

...and that behavior would be encapsulated with the Currency object.

But what if I wanted to transfer the currency from one account to another, or deposit some currency?  Would that behavior also be encapsulated in the Currency object?  No, it wouldn't.  The money in your wallet cannot transfer itself out of your wallet into your bank account; you need one or more agents (a teller or ATM) to assist in getting that money into your account.

So that behavior would be encapsulated into a Teller object, and it would accept Currency and Account objects as inputs, but it would not contain any data itself, except maybe a bit of local state (or maybe a Transaction object) to help process the input objects.


答:
It depends but this is far more of a business question than an ethics question or a programming question.

If you sell me a 99 cent game and I find out that I have to re-purchase the game (or spend half an hour of my time dealing with tech support) because I needed to swap out my network card, I'll probably experience some minor annoyance.  If you sell me a $999 product that I depend on to do my job and I find that I have to re-purchase the product because of that same network card swap, I'm likely to be irate.

Are you going to be able to test all the ways that this sort of a check could go wrong?  For example, what happens if you purchase the product on your laptop while you're using your ethernet card and then undock and start using your wireless card?  If that causes the application to hiccup, you're going to have an unhappy customer and, hopefully, a call to support.  Then throw in users that have one or more VPN connections, virtual machines, etc. and one machine can end up with a rather large number of MAC addresses (I have 7 on my laptop right now).  Whether it is worth it to you to test all the possible configurations, to make sure that your application handles the various transitions successfully, etc. and whether you're prepared to deal with the support calls when it doesn't depends heavily on your business model.  If my new 99 cent game is flaky, I'm probably not calling support, I'll just leave a bad review.  If my server's new $100,000 piece of enterprise software needs a very specific (and well documented) network configuration in order to work correctly, I'll spend hours making sure that we're using exactly the right configuration.

From an ethical standpoint, I would argue that the only requirement of ethical behavior is transparency.  In general, if I have a license for 1 copy of a particular software product, I can install that product on one machine at a time but I can freely move it from one machine to another when I upgrade my hardware.  If you are going to restrict your software more than this, you should make that clear at the time of purchase so that your customers aren't upset 6 months later when they're setting up their new machine.

Title: Do we ethically have the right to use the MAC Address for verification purposes?

Body:
I am writing a program, or starting at the very beginning of it, and I am thinking of purchase verification systems as a final step. I will be catering to Macs, PCs, and possibly Linux if all is said and done. I will also be programming this for smartphones as well using C++ and Objective-C. (I am writing a blueprint before going head first into it)

That being said, I am not asking for help on doing it yet, but what I’m looking for is a realistic measurement for what could be expected as a viable and ethical option for purchase verification systems.

Apple through the Apple Store, and some other stores out there have their own "You bought it" check.

I am looking to use a three prong verification system.

Email/password

16 to 32 character serial number using alpha/numeric and symbols with Upper and lowercase variants.

MAC Address.

The first two are in my mind ok, but I have to ask on an ethical standpoint, is a MAC Address to lock the software to said hardware unethical, or is it smart?

I understand if an Ethernet card changes if not part of the logic board, or if the logic board changes so does the MAC address, so if that changes it will have to be re-verified, but I have to ask with how everything is today.

Is it ethical to actually use the MAC address as a validation key or no? Should I be forward with this kind of verification system or should I keep it hidden as a secret? Yes I know hackers and others will find ways of knowing what I am doing, but in reality this is why I am asking.

I know no verification is foolproof, but making it so that its harder to break is something I've always been interested in, and learning how to program is bringing up these questions, because I don't want to assume one thing and find out it's not really accepted in the programming world as a "you shouldn't do that" maneuver.

I am just learning how to program, and I am just making sure I'm not breaking some ethical programmer credo I shouldn't.


问:
Is it ever ok to have an empty catch statement?
I thought about it and could not come up with an example. Why would somebody want to catch an exception and do nothing about it? Can you give an example? Maybe it is just something that should never be done.</p>

答:
Empty catch blocks are a code smell in most languages.  The main idea is to use exceptions for exceptional situations and not to use them for logical control.  All exceptions must be handled somewhere.

As a consequence of taking this approach, when you program one particular application layer, you have several choices:

do nothing about the exception.  It will be caught and handled by a different layer

catch it and perform the corrective action.

catch it, do something, but re-throw it for another layer to handle

This doesn't really leave any room for do-nothing, empty catch blocks.

EDITED TO ADD: suppose you are programming in a language where throwing exceptions is the normal way of controlling the program logic (one of alternatives to goto).  Then an empty catch block in a program written in this language is very much like an empty else block in a traditional language (or no else block at all).  However, I believe this is not the programming style recommended by C#, Java or C++ development communities.

ContentLicense: CC BY-SA 2.5


问:
Multithreading synchronization interview question: Find n words given m threads

Is there a way this problem could benefit from a solution with multiple threads, rather than a single thread?

In an interview, I was asked to solve a problem using multiple threads. It appears to me that the multiple threads lends no benefit.

Here's the problem:

You are given a paragraph , which contain n number of words, you are
  given m threads. What you need to do is , each thread should print one
  word and give the control to next thread, this way each thread will
  keep on printing one word , in case last thread come, it should invoke
  the first thread. Printing will repeat until all the words are printed
  in paragraph. Finally all threads should exit gracefully. What kind of
  synchronization will use?

I strongly feel we cannot take any advantage of threads here, but believe the interviewer is trying to measure my synchronization skills. Am I missing something in this problem that would make multiple threads have value?

No need of code, just put some thoughts. I will implement by myself.

答:
As you said, I don't think this scenario benefits greatly, if at all from threading. It's most likely slower than a single threaded implementation.

However, my answer would be to have each thread in a tight loop attempting to access a lock which controls access to the word array index. Each thread grabs the lock, gets the index, gets the corresponding word from the array, prints it, increments the index then releases the lock. The threads exits when the index is at the end of the array.

Something like this:

```<code>while(true)
{
    lock(index)
    {
        if(index >= array.length())
          break;
        Console.WriteLine(array[index]);
        index++;
    }
}
</code>```

I think this should achieve the one thread after another requirement, but the ordering of the threads is not guaranteed. I'm curious to hear other solutions as well.

Body:
As you said, I don't think this scenario benefits greatly, if at all from threading. It's most likely slower than a single threaded implementation.

However, my answer would be to have each thread in a tight loop attempting to access a lock which controls access to the word array index. Each thread grabs the lock, gets the index, gets the corresponding word from the array, prints it, increments the index then releases the lock. The threads exits when the index is at the end of the array.

Something like this:

while(true)
{
    lock(index)
    {
        if(index >= array.length())
          break;
        Console.WriteLine(array[index]);
        index++;
    }
}

I think this should achieve the one thread after another requirement, but the ordering of the threads is not guaranteed. I'm curious to hear other solutions as well.


答:
Interview questions are sometimes actually trick questions, intended to make you think about the problem that you're trying to solve. Asking questions about a question are an integral part of approaching any problem, whether it's in the real world or in an interview. There are a number of videos circulating the internet on how to approach questions in technical interviews (look particularly for Google and perhaps Microsoft).

"Just try to answer, and get the hell out of there.."

Approaching interviews with this thought pattern will lead you to bombing any interview for any company worth working for.

If you don't think that you gain much (if anything from threading), tell them that. Tell them why you don't think there is any benefit. Have a discussion with them. Technical interviews are meant to be an open discussion platform. You may end up learning something about how it can be useful. Don't just forge ahead blindly trying to implement something your interviewer told you to.

Title: Multithreading synchronization interview question: Find n words given m threads

Body:
Is there a way this problem could benefit from a solution with multiple threads, rather than a single thread?

In an interview, I was asked to solve a problem using multiple threads. It appears to me that the multiple threads lends no benefit.

Here's the problem:

You are given a paragraph , which contain n number of words, you are
  given m threads. What you need to do is , each thread should print one
  word and give the control to next thread, this way each thread will
  keep on printing one word , in case last thread come, it should invoke
  the first thread. Printing will repeat until all the words are printed
  in paragraph. Finally all threads should exit gracefully. What kind of
  synchronization will use?

I strongly feel we cannot take any advantage of threads here, but believe the interviewer is trying to measure my synchronization skills. Am I missing something in this problem that would make multiple threads have value?

No need of code, just put some thoughts. I will implement by myself.


问:
In dependency injection, is there a simple name for the counterpart of the injected object?
In tutorials and books, I have never seen a single word describing the object that the injected object is injected into. Instead, other terms are used, like "injection point" which don't denote the object containing the injected object. And nothing I can think of sounds right, except maybe "injection target" - but I have never read it anywhere.

Is there a single word or a simple expression for it, or is it like the "He-Who-Must-Not-Be-Named" from a recent fantasy book series?

答:
There is no formal name - I usually think about it as the object that needs the dependency.

Call it the dependant object...


答:
Container sounds like a perfectly acceptable term to me. EG IThing is injected in to its container

Edit -- Comments rightly say that container is already in use in this situation. How about dependee eg The dependency is injected in to its dependee?

Title: In dependency injection, is there a simple name for the counterpart of the injected object?

Body:
In tutorials and books, I have never seen a single word describing the object that the injected object is injected into. Instead, other terms are used, like "injection point" which don't denote the object containing the injected object. And nothing I can think of sounds right, except maybe "injection target" - but I have never read it anywhere.

Is there a single word or a simple expression for it, or is it like the "He-Who-Must-Not-Be-Named" from a recent fantasy book series?


答:
First tokenize the paragraph with appropriate delimiters and add the words
to a Queue.

Create N number of threads and keep it in a thread pool.

Iterate over the thread pool and start the thread and wait for the

thread to join. And start  the next thread once the first thread ends
and so on.

Each Thread should just poll the queue and prints it.

Once all threads are used within the thread pool, start from the
beginning of the pool.


答:
The point of OOP is to group together data and functionality that belong together. A calculation that is based on some piece of data does not always belong with that data.

In MVC the functionality to display a piece of data (view) is kept separate from the data (model). Why is that? It's specifically so that the display logic can be changed without having to change the underlying data. It makes it easy to change the view whenever you need to make a different presentation of the same data: or when the characteristics of the display hardware change: or when you switch from Windows to Linux; or when you want two people to have two different ways of looking at the same data.

MVC isn't in conflict with OOP - it is actually derived from a correct application of Object Oriented Principles.

Title: Isn't MVC anti OOP?


答:
Wikipedia calls it the "Dependent Consumer," or simply the "Dependent Object."

...Dependency injection involves at least three elements:

a dependent consumer,

a declaration of a component's dependencies, defined as interface contracts,

an injector (sometimes referred to as a provider or container) that creates instances of classes that implement a given dependency interface on request.

The dependent object describes what software component it depends on to do its work. The injector decides what concrete classes satisfy the requirements of the dependent object, and provides them to the dependent.

In conventional software development, the dependent object decides for itself what concrete classes it will use. In the dependency injection pattern, this decision is delegated to the "injector" which can choose to substitute different concrete class implementations of a dependency contract interface at run-time rather than at compile time.

Being able to make this decision at run-time rather than compile time is the key advantage of dependency injection. Multiple, different implementations of a single software component can be created at run-time and passed (injected) into the same test code. The test code can then test each different software component without being aware that what has been injected is implemented differently...


问:
What causes overtime and how can it be avoided?
Today, my manager told me that I must work over time to make up for a lack of planning and project management. Instead of incentivizing this unpaid mandatory overtime, my manager has made it clear I have no choice in the matter.

This isn't a single project. We currently have a dozen projects all on the go at one time, and I simply can't get them all done. Therefore, I must work overtime so we don't have to push deadlines.

Is this a sign of an ignorant or disrespectful manager, or simply an inexperienced one?

I'm in this position because of a lack of planning and project management (I think). How might I avoid this in the future? I'm no Project Manager, it isn't my strength.

What are good ways to get an employee to work overtime if you can't directly pay them? Good incentives, etc.

From what I hear, gaining your employee's respect is the single best way to get your employees to work over time, although you should never make a habit of it.

答:
In answer to your side question, people are more willing to put extra effort out for a manager who they trust. Someone who only asks if it is a real emergency, someone who has tried to protect his employees from corporate BS, someone who rewards actual accomplishment and who says thank you and gets rid of the deadweight and someone who removes roadblocks for them. A good manager is worth his or her weight in gold (they are so rare!) and employees will often leap tall buildings to keep working for one. It's too late to ask how can I make this better at the time you need to ask for extra effort. My current boss is one of these people and I would do anything she needed that was within my power to give.

If the company will allow it, the good manager at least tries to offer offical or unoffical comp time if he can't pay for the effort. He takes the people who give that effort and makes sure they are rewarded at review time. And if the whole team is working overtime, he doesn't leave at 5 pm.


答:
My main experience lies with Mercurial, although I also use git sporadically.

Mercurial doesn't disallow you to commit unresolved files, it just discourages you. Same deal with pushing before pulling changes that you don't have.

All you need to do in Mercurial is, once you have the files the way you want to commit them:

```<code>hg resolve --mark --all
hg commit -m "I'm such a rebel"
</code>```

--mark will... mark files as resolved without prompting you with the merge tool. --all will take care of selecting all files mark with conflicts.

If you want to push without pulling (and consequently having to merge other's changes) do like a Jedi:

```<code>hg push --force
</code>```

Next guy who pulls will get +1 head (no pun intended)

I'm sure there is a way to do the same stuff with Git (although it probably is more convoluted).

Title: Why not commit unresolved changes?

Body:
My main experience lies with Mercurial, although I also use git sporadically.

Mercurial doesn't disallow you to commit unresolved files, it just discourages you. Same deal with pushing before pulling changes that you don't have.

All you need to do in Mercurial is, once you have the files the way you want to commit them:

hg resolve --mark --all
hg commit -m "I'm such a rebel"

--mark will... mark files as resolved without prompting you with the merge tool. --all will take care of selecting all files mark with conflicts.

If you want to push without pulling (and consequently having to merge other's changes) do like a Jedi:

hg push --force

Next guy who pulls will get +1 head (no pun intended)

I'm sure there is a way to do the same stuff with Git (although it probably is more convoluted).


问:
ASP.Net MVC 3: multiple versions of the site without changing of URL, is it possible?
Our website is written in ASP.NET MVC 3  and we want to change a feature in the core functionality of the site.

The problem is not every client can be moved to this new version/format (because of some technical inner restrictions) so it means that we need to keep 2 versions of the same functionality (backend and frontend) simultaneously. We don't want our clients to worry about URLs, so the ideal solution would be keep the same URL but redirect clients to the different versions.

The information about clients is stored in database. So the moment when user (client) logs in we know which version of site we should show.

I'm thinking about routing and areas but I'm not sure if it's possible for example to have 2 areas with the different versions of the same application. Or is it possible to load the assemblies on the fly? After user is logged in we can decide if (s)he should be redirected to the new or old version.

As far as all the clients have been moved to the new version we don't need this system more.

How can I do this in ASP.NET MVC?

答:
We do this very thing at The Motley Fool (TMF) with our DailyFinance and Fool Quotes pages.  They both run off of the same codebase, but we utitilze a Custom Theme View Engine to allow the differing sites to have radically different CSS and Markup where needed.  For instance, the TMF quotes page has Glassdoor integration, where the DailyFinance site does not.

In the custom Theme view engine, you can specify how you want to theme something, in our case, we use the server domain that the site runs off of, but you could just as easily replace it with the value of a cookie, or what company the user comes from (if you have that data stored in your database).

I would need to see some code or a specific example of what you're trying to do to be able to answer your problem any further.

OwnerDisplayName: Seacat

OwnerDisplayName: George Stocker


答:
It sounds to me like they are leading you toward a semaphore solution.  Semaphores are used to signal another thread that it's their turn.  They are used much less frequently than mutexes, which I guess is why they think it's a good interview question.  It's also why the example seems contrived.

Basically, you would create m semaphores.  Each thread x waits on semaphore x then posts to semaphore x+1 after doing its thing.  In pseudocode:

```<code>loop:
    wait(semaphore[x])
    if no more words:
        post(semaphore[(x+1) % m])
        exit
    print word
    increment current word pointer
    post(semaphore[(x+1) % m])
</code>```

Body:
It sounds to me like they are leading you toward a semaphore solution.  Semaphores are used to signal another thread that it's their turn.  They are used much less frequently than mutexes, which I guess is why they think it's a good interview question.  It's also why the example seems contrived.

Basically, you would create m semaphores.  Each thread x waits on semaphore x then posts to semaphore x+1 after doing its thing.  In pseudocode:

loop:
    wait(semaphore[x])
    if no more words:
        post(semaphore[(x+1) % m])
        exit
    print word
    increment current word pointer
    post(semaphore[(x+1) % m])


问:
VCS for single user using file sync service
I'm trying to setup a version control for my one man project. My project files are in sync thanks to live mesh (but I could be using dropbox for that matter), between my laptop, my home pc and my office pc. I'm now using Netbeans with local file history. Sometimes it helps to revert to a previous state of one file. But imagine a situation when multiple files have problems. Correct me if I'm wrong but I would have to go to every file and revert to previous "safe" state. I don't like this approach, so I'm considering using a version control between SVN and GIT.

I have some previous experience with SVN (TortoiseSVN) and I know that I can create a file:// repo.

So, what a want to do is setup a VCS inside my synced folder just to have the ability to "revert" to a previous version if something goes wrong. Since everything's been synced to all computers, I wouldn't ever need to run an update.

The file tree organization would be the following:

C:...\SyncedFolder\MyProject\

Inside MyProject folder are all the project files plus a directory that has SVN or GIT info of my project (the repo/master).

What VCS is best for this situation: SVN or GIT? Does SVN need to store all files from HEAD revision, thus "duplicating" all my project inside my synced folder? Does GIT eliminates this problem? Is this the best approach?

答:
I use GIT, Git Extensions http://code.google.com/p/gitextensions/ (which installs git on windows) with free private repo from https://bitbucket.org/ . I use bitbucket to transfer source code between my workstations and also keep my code offsite (for backup purposes). Just need to make sure you push the latest changes when you are done so you can pull them when you get to the new workstation.

Since with GIT, each user has the full repo on their machines, I'm not too worried about bitbucket losing my data. Just to be safe, I also sync my repos to google drive.

probably better ways to do this but it's working so far for me


问:
System that splits passwords across two servers
I stumbled upon this news article on BBC,

RSA splits passwords in two to foil hackers' attacks

tl;dr - a (randomized) password is split in half and is stored across two separate servers, to foil hackers that gained access to either server upon a security breach.

Now the main question is, how would this kind of system would be made... codespeaking, for PHP which I commonly develop on my web applications, the database password is normally stored in a configuration file, i.e. config.php with the username and password, in that case it is understandable that the passwords can be stolen if the security was compromised.

However when splitting and sending the other half to the other server, how would this go on when making a communication to the other server (keeping in mind with PHP) since the other server password would be stored in a configuration file, wouldn't it? In terms of security is to keep the other server password away from the main one, just exactly how would the main server communicate, without exposing any other password, apart from the first server.

This certainly makes me think...

答:
In this article: http://www.technologyreview.com/news/429498/to-keep-passwords-safe-from-hackers-just-break/

I´ve read that both servers have to rely on different security mechanisms, so if one system gets compromised the second might still be safe and the intruder gets only half of the password. But this is not a complete answer because I don´t know which security mechanisms get used there.


答:
This isn't for database passwords. That requires you to re-assemble the password, and since your one machine knows how to do that, attackers can just get that machine and win.

This is for user authentication. When someone submits a password, you split it and send it to two auth servers who reply yes/no on the two halves. This doesn't prevent someone from doing a dictionary attack, but does prevent the whole password from being stored in one location.

Title: System that splits passwords across two servers

Body:
I stumbled upon this news article on BBC,

RSA splits passwords in two to foil hackers' attacks

tl;dr - a (randomized) password is split in half and is stored across two separate servers, to foil hackers that gained access to either server upon a security breach.

Now the main question is, how would this kind of system would be made... codespeaking, for PHP which I commonly develop on my web applications, the database password is normally stored in a configuration file, i.e. config.php with the username and password, in that case it is understandable that the passwords can be stolen if the security was compromised.

However when splitting and sending the other half to the other server, how would this go on when making a communication to the other server (keeping in mind with PHP) since the other server password would be stored in a configuration file, wouldn't it? In terms of security is to keep the other server password away from the main one, just exactly how would the main server communicate, without exposing any other password, apart from the first server.

This certainly makes me think...


答:
Imagine that the user has a password "stack overflow" entered during registration on the website. The website will split the password in two, the first part being always four characters long:

```<code>Part 1: "stac"
Part 2: "k overflow"
</code>```

Then some random characters are appended to the first part, and prepended to the second part, given that the prepended part is of a given length, let's say 6:

```<code>Part 1: "stacd9u8BHaI1"
Part 2: "hBy47k overflow"
</code>```

The first part is salted and hashed on a first server and stored in the database. The second part uses a different salt, different hash, and a database on a different server.

Imagine a hacker gains access to the first database and successfully finds, for example through brute force, the password "stacd9u8BHaI1". The hacker tests this password on the website, and notices that it doesn't work. He may be discouraged by that, and abandon the tentative of finding other passwords. It's supplementary security, given that it's not extremely strong, but still valuable if it doesn't cost too much in terms of resources compared to the ordinary, single server authentication.

Isn't it easy to discover what part of password is stored?

Actually, no. It's possible, but not easy. If you find, through brute force, that the original password is "hBy47k overflow", you may guess that the beginning was randomized, but it's not straightforward. Random characters may also be adjusted accordingly: for example for passwords which contain only words, a word may be prepended/appended, instead of random characters:

```<code>Part 1: "stac battery" // Appending a random number of characters
Part 2: "change k overflow" // Prepending 7 characters
</code>```

or:

```<code>Part 1: "stac white unicorn"
Part 2: "global k overflow" // Still 7 characters
</code>```

You actually need to brute force several passwords to guess how much prepended/appended characters are there.

When it fails?

There is a case when this technique fails miserably: if you have an account on a hacked system, you already know your password, so by bruteforcing the two parts, you can easily see what parts were preserved. Making the number of characters in the first part and the number of characters prepended to the second part dependent on an element relative to the password itself makes it more difficult to understand the system, but still quite doable.

Do I need to implement this system right now?

No. Security which relies on the fact that you keep secret the way you store passwords is weak. Anybody who has an access to the source code knows all the elements.

The split the password technique has a tiny advantage, but still doesn't worth to be implemented in every website. Just use PBKDF2 with correct parameters, and you'll be fine. Even if you're a bank. I'm pretty sure my bank stores my password in plain in the database, as well as most websites you use daily. That sucks.

Body:
Imagine that the user has a password "stack overflow" entered during registration on the website. The website will split the password in two, the first part being always four characters long:

Part 1: "stac"
Part 2: "k overflow"

Then some random characters are appended to the first part, and prepended to the second part, given that the prepended part is of a given length, let's say 6:

Part 1: "stacd9u8BHaI1"
Part 2: "hBy47k overflow"

The first part is salted and hashed on a first server and stored in the database. The second part uses a different salt, different hash, and a database on a different server.

Imagine a hacker gains access to the first database and successfully finds, for example through brute force, the password "stacd9u8BHaI1". The hacker tests this password on the website, and notices that it doesn't work. He may be discouraged by that, and abandon the tentative of finding other passwords. It's supplementary security, given that it's not extremely strong, but still valuable if it doesn't cost too much in terms of resources compared to the ordinary, single server authentication.

Isn't it easy to discover what part of password is stored?

Actually, no. It's possible, but not easy. If you find, through brute force, that the original password is "hBy47k overflow", you may guess that the beginning was randomized, but it's not straightforward. Random characters may also be adjusted accordingly: for example for passwords which contain only words, a word may be prepended/appended, instead of random characters:

Part 1: "stac battery" // Appending a random number of characters
Part 2: "change k overflow" // Prepending 7 characters

or:

Part 1: "stac white unicorn"
Part 2: "global k overflow" // Still 7 characters

You actually need to brute force several passwords to guess how much prepended/appended characters are there.

When it fails?

There is a case when this technique fails miserably: if you have an account on a hacked system, you already know your password, so by bruteforcing the two parts, you can easily see what parts were preserved. Making the number of characters in the first part and the number of characters prepended to the second part dependent on an element relative to the password itself makes it more difficult to understand the system, but still quite doable.

Do I need to implement this system right now?

No. Security which relies on the fact that you keep secret the way you store passwords is weak. Anybody who has an access to the source code knows all the elements.

The split the password technique has a tiny advantage, but still doesn't worth to be implemented in every website. Just use PBKDF2 with correct parameters, and you'll be fine. Even if you're a bank. I'm pretty sure my bank stores my password in plain in the database, as well as most websites you use daily. That sucks.


答:
It is effective and common solution in physical world security - two keys to a safe, two PINs needed to access a room etc - Server admin passwords stored 1/2 each in two locations. Many movies make good use of it for dramatic effect.

How this translates to servers - Like the physical world, the added complexity means reliability for legitimate access can be reduced, (i.e. two people need to be at the same place at the same time and a car breaks down compared to two servers need to (securely) talk to each other and the comms fails.)

Where the differences between real world and servers is that putting a gun to one persons head does not help with the other guy - you need to have 2 guns one for each head...  Unless done simultaneously - the compromise is detected and the attach will fail. This needs good coordination and planning, and the the key to this scheme working.

Essentially for this to work you need to ensure that an attack (successful or not) on one system will not assist an attack on the other. The attacker must also not be able to successfully attack both systems "simultaneously" - so the sooner you can detect a successful attack - the less likely it is to succeed. On top of this - you need to be certain that maintaining two systems does not reduce the security of either system compared to if you maintain a single system.

At this point there is a lot of probability math and crystal ball gazing to really know if it's worth it. It's not something that will be successful if done on the cheap and with little though, but it is a way to increase security when done properly.


问:
How far should an entity take care of its properties values by itself?
Let's consider the following example of a class, which is an entity that I'm using through Entity Framework.

```<code>- InvoiceHeader
    - BilledAmount (property, decimal)
    - PaidAmount (property, decimal)
    - Balance (property, decimal)
</code>```

I'm trying to find the best approach to keep Balance updated, based on the values of the two other properties (BilledAmount and PaidAmount).

I'm torn between two practices here:

Updating the balance amount every time BilledAmount and PaidAmount are updated (through their setters)

Having a UpdateBalance() method that the callers would run on the object when appropriate.

I am aware that I can just calculate the Balance in its getter.
However, it isn't really possible because this is an entity field that needs to be saved back to the database, where it has an actual column, and where the calculated amount should be persisted to.

My other worry about the automatically updating approach is that the calculated values might be a little bit different from what was originally saved to the database, due to rounding values (an older version of the software, was using floats, but now decimals).
So, loading, let's say 2000 entities from the database could change their status and make the ORM believe that they have changed and be persisted back to the database the next time the SaveChanges() method is called on the context.

It would trigger a mass of updates that I am not really interested in, or could cause problems, if the calculation methods changed (the entities fetched would lose their old values to be replaced by freshly recalculated ones, simply by being loaded).

Then, let's take the example even further.

Each invoice has some related invoice details, which also have BilledAmount, PaidAmount and Balance (I'm simplifying my actual business case for the sake of the example, so let's assume the customer can pay each item of the invoice separately rather than as a whole).

If we consider the entity should take care of itself, any change of the child details should cause the Invoice totals to change as well.

In a fully automated approach, a simple implementation would be looping through each detail of the invoice to recalculate the header totals, every time one the property changes.
It probably would be fine for just a record, but if a lot of entities were fetched at once, it could create a significant overhead, as it would perform this process every time a new invoice detail record is fetched.
Possibly worse, if the details are not already loaded, it could cause the ORM to lazy-load them, just to recalculate the balances.

So far, I went with the Update() method-way, mainly for the reasons I explained above, but I wonder if it was right.
I'm noticing I have to keep calling these methods quite often and at different places in my code and it is potential source of bugs.

It also has a detrimental effect on data-binding because when the properties of the detail or header changes, the other properties are left out of date and the method has no way to be called.

What is the recommended approach in this case?

答:
I see that this problem is not a programming problem as much as it is a schema design problem. Where to place the properties and method may comes secondary to identifying database columns if you are mapping tables to classes in 1-1 or near 1-1 fashion.

I personally see that after the data type has been changed, you should have run a report comparing old totals and new totals and would probably want to involve management then update the database in batch and get all data consistent once and for all.

On the other issues, the correct answer will depend on answering the following questions:

Is your shop strict about normalization? If the answer is 'yes', do it the normalized way.

Do other systems update the tables involved?

Do you have less than 300 children per header? (300 is an approximate value of course)

Approximately one user would be accessing the same invoice header or detail at any time

The table below summarizes my opinion based on the different answers of the questions. Note that (-) means 'don't care'.

I personally prefer working with non-redundant data whenever possible and would place data correctness and integrity over performance if I had to and it was up-to-me, so I am biased. I made the assumption that an invoice is usually accessed only few times after its creation.

Also notice that the calculation need not be physically stored as table column, instead it could be calculated in a view and that view is used by any program wishing to access this information. Make sure your reporting software can use views before you do this.

OwnerDisplayName: Kharlos Dominguez


问:
How do programming languages benefit from being based on English?
I think the world now programs in English-based programming languages not only because of historical/economic circumstances, but because the English morphology in particular has some properties that suit algorithmic thinking best. But anyway it would be interesting to hear your opinions on this, especially if you are multilingual yourself.

I've seen some mentioning of German-based languages (see Plankalkul for example, in fact the first ever programming language we know very little about, thanks to WW2), also a Russian-based flavor of Algol which existed back in the 80's at least on paper, not sure if it ever existed in binary or not. Both looked a bit sluggish because there were more shortened words and weird abbreviations than full words like in the EN-based languages. So if you know of any other national language-based PL's, even completely archaic and irrelevant today, purely theoretical or whatever, would be interesting to take a look at them.

And back to the main question: so what, if any, makes the Shakespeare's language so good for programming?

(There is actually a list of Non-English-based programming languages on Wikipedia (of course, where else?), but it would be interesting to hear opinions of native speakers of those languages on how a given "national" programming languages really feels like.)

答:
English is the lingua franca language of programming.

From the same article:

It's nothing more than great hackers collectively realizing that sticking to English for technical discussion makes it easier to get stuff done.


问:
Mirror virtualized development environment
I work alone in some iOS projects in a local environment.

I have been thinking in a way to be able to share my development environment between my Mac Mini and my MacBook. I mostly work at home in the Mini but sometimes I need to do a demo or work outside and I would like to have the development environment mirrored in both.

I have think in using a virtual machine (via VirtualBox) with just my development tools installed. Then I could synchronize that VM with some software between both computers so I will always have the exact environment no matter what computer I use.

Is there any good reason not do do this way? I have not used virtualization too much so I have no background on the subject.

¿What about licenses?¿Is there need to have duplicated licenses in both VMs?

This are my requirements:

-Don't need to setup two environments. Just setup one and have the job done in the other(installing or updating apps, change settings, etc).

-Don't depend on having a connection when working away from my home.

My basic setup will be:

Mac Mini: i7 dual Core, 8Gb. OSX Mountain Lion Host OS:

MacBook: 2.4 Core 2 Duo. 4Gb. OSX Lion Host OS.

Virtual Box with Mountain Lion guest OS in both machines.

XCode5, Simulator, Texwrangler, MAMP, etc.

答:
You don't need to virtualize anything. Just use Screen Sharing. It's built in.

Mac OS X 10.7 (Lion) has an excellent screen sharing app built right into the operating system. The screen sharing app enable you to access and control the screen of another computer on your network. I like using in on my MacBook Air when I want to quickly access our family iMac. It’s perfect for troubleshooting the computer outside of the room or doing a function that’s not available on my notebook computer...


问:
Isn't MVC anti OOP?
The main idea behind OOP is to unify data and behavior in a single entity - the object. In procedural programming there is data and separately algorithms modifying the data.

In the Model-View-Controller pattern the data and the logic/algorithms are placed in distinct entities, the model and the controller respectively. In an equivalent OOP approach shouldn't the model and the controller be placed in the same logical entity?

答: MVC is a pattern which describes a sensible way for objects to interact; it is not itself a meta-class. At that, OO is about describing behaviours and data of entities, and how said entities interact. It isn't about unifying the entire system into one massive object.</p>

Title: Isn't MVC anti OOP?


问:
Data structures for storing finger/stylus movements in drawing application?
I have a general question about creating a drawing application, the language could be C++ or ObjectiveC with OpenGL.
I would like to hear what are the best methods and practices for storing strokes data.
Think of the many iPad apps that allow you to draw with your finger (or a stylus) or any other similar function on a desktop app.

To summarize, the data structure must:

be highly responsive to the movement

store precise values (close in space / time)

usable for rendering the strokes with complex textures (textures
based on the dynamic of the stroke etc)

exportable to a text file for saving/loading

答: I'd recommend storing it as a vector graphics image. There are data structures that do this kind of thing. As far as precision, Vector Graphics are very precise. Response will largely be a question of the implementation keeping overhead and locking to a minimum.</p>


问:
How to achieve a loosely coupled REST API but with a defined and well understood contract?
I am new to REST and am struggling to understand how one would properly design a REST system to both allow for loose coupling but at the same time allow a consumer of a REST API to understand the API.

If, in my client code, I issue a GET request for a resource and get back XML, how do I know what to do with that xml? e.g. if it contains <fname>John</fname><lname>Smith</lname> how do I know that these refer to the concept of "first name", "last name"? Is it up to the person writing the REST API to define in documentation some place what each of the XML fields mean? What if producer of the API wants to change the implementation to be <firstname> instead of <fname>? How do they do this and notify their consumers that this change occurred? Or do the consumers just encounter the error and then look at the payload and figure out on their own that it changed?

I've read in REST in Practice that using a WADL tool to create a client implementation based on the WADL (and hide the fact that you're doing a distributed call) is an "anti-pattern". But I was planning to do this-- at least then I would have a statically typed API call that, if it changed, I would know at compile time and not at run time. Why is this a bad thing to generate client code based on a WADL?

And how do I know what to do with the links that returned in the response of a POST to a REST API? What defines this contract and gives true meaning to what each link will do?

Please help! I dont understand how to go from statically-typed or even SOAP/RPC to REST!

答:
What if producer of the API wants to change the implementation

The producer should supply versions of the API.

http://blogs.gartner.com/eric-knipp/2012/08/27/catalyst-debrief/

The majority of Web API initiatives leave versioning for later. I believe this is a dangerous idea for a variety of reasons. First and foremost, if you run just one version of an API you risk introducing a breaking change anytime you extend it. While you can potentially work around this with a very robust set of test cases (which I would strongly encourage), it is easy to paint yourself into a corner when you are unable to fix a bad implementation that seemed like a good idea at the time.

If you look at the Twitter REST API, you'll see a version number in the URL:

api.twitter.com/1.1/statuses/mentions_timeline.json

This allows the producer to change the output data format as the API evolves. Applications that consume the API would then publish updates as they move towards later versions of the API.

As far as how to know what each data key means, the API should be documented to show you (1) what will be returned & how it relates to their service and (2) the data and data format required to be sent to their service.


问:
Actor library / framework for C++
In the C++ project I am working on, we have an application consisting of
several processes deployed on different machines. This network of
processes is dynamic since processes (clients or background services)
can be started and terminated during the application's lifetime.

We have already a module that allows to transport arbitrary data over
the network through RPC, and we are using it to exchange information
(such as status information, progress information, error codes, etc)
between the processes. We would like to have a more abstract layer
to handle asynchronous communication (currently, the RPC is executed
synchronously), and to allow processes to be started and terminated
dynamically and still find each other.

We recently looked for a solution and we think we can use something
like Scala actors and remote actors (see e.g. this tutorial).
Another language using the actor model that has been around longer
than Scala is Erlang (see also this question).

Actors are objects that have a behaviour and a mailbox, share no data.
Actors are executed concurrently, and communicate through asynchronous
message exchange. As part of their behaviour, actors can create other actors.
Messages are also represented as objects.

The simplest case is that actors live in the same process.
In this case they can address each other using
a handle (reference, pointer, unique identifier). The actor implementation
hides the underlying threads and any other details.
When actors live in different processes (and possibly on different
machines in a network) they are identified by an IP address, a port and
a name. In this case we speak of remote actors
(see the short example at the top of this page).

In our case, we would have one actor on each process, taking care of
all the communication, i.e. we need some kind of remote actors.

On wikipedia I have found some links to actor libraries for C++ and
I have started to look at Theron. Theron seems a very well-written
and documented library but, to my understanding, it does not support
remote actors: all actors must live within the same process. It is possible
to create several actor pools (frameworks), but all these pools must
live in the same process.

So I wanted to ask if someone knows other C++ libraries
that support the remote actor concept as sketched above.

EDIT

This question has been edited wrt the original question, following
indications from programmers-meta discussion.

UPDATE

Other frameworks I have looked at are libcppa (should support
remote actors, but it is still under development, currently version 0.1),
actor-cpp (also under development), and libactor, which is
in C (the web site says it "is usable, although it may not be ready for production").

答:
As of version 5, Theron does support remote actors. Support is still quite preliminary and there are some limitations, notably message serialization is currently just a bitwise copy (in version 5.0, and as of October 2012). But it's a start, and I intend to develop it further.

http://www.theron-library.com/index.php?t=page&p=distributed%20computing

Title: Actor library / framework for C++


问:
Convert plain text to a pdf template
I have some articles (more than 200 pages) in plain text. It needs to be converted to an given PDF markup. I got some Photoshop files for the headers for every page and a list of requirements for the different elements.

Which program would you use? And what would be your workflow?

答:
How much customization are you looking for?

Ballpark guess would be LaTeX, unless you want to do actual transformations there is no need to pull out a general purpose language.

Title: Convert plain text to a pdf template


答:
What VCS is best for this situation: SVN or GIT?

Does not matter at all. If you sync directory tree between nodes you'll have

3 working copy

3 repositories

in both cases.

Pure DVCS solution may be smaller in terms of total size, because it doesn't store WC-metadata in .svn folder(s) inside working copy, but - GIT handle binary data extremely worse, than Subversion (or Mercurial)

Title: VCS for single user using file sync service

Body:
I'm trying to setup a version control for my one man project. My project files are in sync thanks to live mesh (but I could be using dropbox for that matter), between my laptop, my home pc and my office pc. I'm now using Netbeans with local file history. Sometimes it helps to revert to a previous state of one file. But imagine a situation when multiple files have problems. Correct me if I'm wrong but I would have to go to every file and revert to previous "safe" state. I don't like this approach, so I'm considering using a version control between SVN and GIT.

I have some previous experience with SVN (TortoiseSVN) and I know that I can create a file:// repo.

So, what a want to do is setup a VCS inside my synced folder just to have the ability to "revert" to a previous version if something goes wrong. Since everything's been synced to all computers, I wouldn't ever need to run an update.

The file tree organization would be the following:

C:...\SyncedFolder\MyProject\

Inside MyProject folder are all the project files plus a directory that has SVN or GIT info of my project (the repo/master).

What VCS is best for this situation: SVN or GIT? Does SVN need to store all files from HEAD revision, thus "duplicating" all my project inside my synced folder? Does GIT eliminates this problem? Is this the best approach?


答:
Regardless of the data structure you use it may be helpful to remove unneeded data points using an algorithm like the Ramer–Douglas–Peucker algorithm. It will take a linear piecewise curve and remove points that deviate less than some small amount from the curve at large. This way, if your user draws a more or less straight line, you wont store every intermediate point where their finger has been.

The problem is how to simplify and smooth piecewise linear curves. There's a free paper here Efficient Smoothing of Piecewise Linear Paths with Minimal Deviation (there's a PDF link to the right).

As World Engineer mentioned in his answer, vector graphics are an option. SVG is a popular format and it's based on XML so it's easy to manipulate with existing tools. Along with plain old "points" it can handle paths (Bézier and elliptic), text, shapes, styling info (stroke etc.) and much more. SVG gives you the tools to render your user's drawing as exactly as you'd like. SVG images also supported in most browsers. Also, since it's a well established format I'm sure there are plenty of existing libraries for manipulating the images, ex. simple-svg. Or there's always good old bitmaps.

I imagine the process would go something like:

Wait for user to draw a curve

Simplify the curve (as much or as little as you would like)

Render the simplified curve, path, shape, etc. to the canvas using the selected style.

Title: Data structures for storing finger/stylus movements in drawing application?

Body:
I have a general question about creating a drawing application, the language could be C++ or ObjectiveC with OpenGL.
I would like to hear what are the best methods and practices for storing strokes data.
Think of the many iPad apps that allow you to draw with your finger (or a stylus) or any other similar function on a desktop app.

To summarize, the data structure must:

be highly responsive to the movement

store precise values (close in space / time)

usable for rendering the strokes with complex textures (textures
based on the dynamic of the stroke etc)

exportable to a text file for saving/loading