答:
I will try my hand at an answer, and fully expect to hear what's wrong with it soon. :)

So first, I think the problem may be more easily tackled by thinking of the pair of ranges instead as defining a rectangle. Suppose you have [(0,2), (3,4)]. Another way to view this is the rectangle in Cartesian coordinates of (0,3) to (2,4). Overlap of both ranges can then be thought of as rectangle-to-rectangle intersection.

With that in mind, I think a spatial structure is possibly most appropriate. The path my tired brain can conjure up is to use an R-tree or one of its variants. Finding the union of rectangles then becomes similar to building the tree. At each step, use the rectangle being added first as a search. If it finds any rectangles, replace all found rectangles with the "union" rectangle - the min/max of x/y coordinates, else add the rectangle as is. Once the tree is built, simply iterate through the rectangles and voila, convert them back to your ranges.

The unfortunate reality is that the runtime is not going to be easily analyzable. Let's note some of the potential issues:

R-trees themselves do not guarantee good worst-case performance (as noted by Wikipedia)

When adding a new rectangle, the number of overlapping rectangles plays a role in the complexity of the step. This seems to imply density is a sneaky factor.

R-trees are likely complex enough that any constant factor is probably pretty high, which may mean that other methods win out depending on your data set size.

Given a large enough set, I believe this approach would win out. I believe it to be quadratic only in "bad" cases. But R-trees are not simple data structures, so it needs to be thought through carefully. Good luck!

Title: algorithmic problem - Combining overlapping ranges

Body:
I'm looking for an idea to efficiently solve following problem:

I have a set of pairs of ranges (range = a pair of numbers), each range is unique (but has same size) e.g.

```<code>[
 [(0,6),(34,40)],
 [(1,7),(35,41)],
 [(3,9),(12,18)],
 [(2,8),(36,42)],
 [(13,19),(22,28)],
 [(23,29),(14,20)]
]
</code>```

Now I'd like to combine pairs of ranges, if ranges are overlapping e.g.

```<code>[(0,6),(34,40)] overlaps with [(1,7),(35,41)] -result-> [(0,7),(34,41)]
</code>```

So as a result for above set I'd like to get (now each pair may have ranges of different size)

```<code>[
 [(0,8),(34,42)],
 [(3,9),(12,18)],
 [(13,20),(22,29)]
]
</code>```

The set might be pretty big, I'd like to avoid quadratic complexity if possible.

EDIT: My best idea so far (in Python) is below. I'd like to know if you know a better(faster) way. Also I'm not sure if my idea of removing already combined pairs is valid:

```<code>def ranges_overlap(range1, range2):
    return range1[0] < range2[1] and range2[0] < range1[1]

def combine_pairs(pair1, pair2):
    return [(min(r1[0], r2[0]), max(r1[1], r2[1])) for r1, r2 in zip(pair1, pair2)]

def combine_overlapping_pairs(pairs):
    combined = []
    while pairs:
        pair1 = pairs.pop()
        already_combined = []
        for pair2 in pairs:
            for pair2_perm in itertools.permutations(pair2):
                does_overlap = True
                for range1, range2 in zip(pair1, pair2_perm):
                    if not ranges_overlap(range1, range2):
                        does_overlap = False
                        break

                if does_overlap:
                    pair1 = combine_pairs(pair1, pair2_perm)
                    already_combined.append(pair2)
                    break

        combined.append(pair1)
        # Not sure if I can do that
        for pair in already_combined:
            pairs.remove(pair)

    return combined
</code>```


问:
Efficient "Object with weights" structure
I need to find an "efficient" data structure / set of algorithms to do the following things:

I have a list of objects. I need to assign them weights and later on increase or decrease these weights.

For instance:
We have the hashmaps {o1}, {o2}, {o3}. The {o}'s don't have any particullar structure, just random json.

I am looking for a way of saying: Increase the weight of o1 by 1. Increase the weight of o2 by 1. Increase the weight of o1 by 1. Now give me the results sorted by their weight.

I am using Python. So far I have tried using a normal hashmap to store them, but the problem is that I can't just hash the {o}'s. I thought of hashing the pointer of the {o}'s in memory, but it seems I don't have access to it in Python.

答:
For sorting you can override __lt__ and others compare function:

```<code>import heapq

class Item(object):
    def __init__(self, o, weight):
        self.o = o
        self.weight = weight

    def increase_weight(self, amount=1):
        self.weight += amount

    def __lt__(self, other):
        return self.weight < other.weight

    def __str__(self):
        return '<Item o={o} weight={weight}>'.format(
            o=self.o, weight=self.weight
        )
    __repr__ = __str__

items = [
    Item('o1', 1),
    Item('o2', 5),
    Item('o3', 4),
    Item('o4', 3),
]

items.sort()
print items

items[0].increase_weight(5)
items.sort()
print items
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For sorting you can override __lt__ and others compare function:

import heapq

class Item(object):
    def __init__(self, o, weight):
        self.o = o
        self.weight = weight

    def increase_weight(self, amount=1):
        self.weight += amount

    def __lt__(self, other):
        return self.weight < other.weight

    def __str__(self):
        return '<Item o={o} weight={weight}>'.format(
            o=self.o, weight=self.weight
        )
    __repr__ = __str__

items = [
    Item('o1', 1),
    Item('o2', 5),
    Item('o3', 4),
    Item('o4', 3),
]

items.sort()
print items

items[0].increase_weight(5)
items.sort()
print items


问:
How do you track what you and your team are working on day-to-day?
I'm struggling with how to keep track of what myself and people on my team actually do each day. I get a good broad picture by going over completed cards each week and stand-ups help a bit, but I feel like I don't have a good handle on the day-to-day workings of my team. Cards will stay in progress for days on end without an update at the daily stand-up, and some engineers are my team aren't the most communicative.

I've thought about implementing some sort of daily record that everyone fills out (via a mailing list or a shared google doc) but this seems fairly cumbersome and manual.

Monitoring GitHub activity does an ok job but can be a little bit overwhelming with how many emails it sends out everyday. I've thought about trying to build a digest system for it, but don't have the time to spare.

What strategies have you implemented to stay on top of what your team is doing everyday so that you can measure work on "in progress" tasks?

答:
First of all you need to analyze yourself in terms of your time and skills. If you are a technical person with some previous hands-on experience things may different from those in case you are just a manager (not with strong technical knowledge on what your developers are actually working on) who only needs to make sure that deadlines are met.

The common point in both the cases is that you need to be able to facilitate your team and create a feeling that you trust them. You are not judging their performance but are trying to be empathetic and helpful in making their experience fun and easy.

Now assume that you are just a manager as i said above, in that case even if some developer is really facing some serious development related problem you may not be able to help her/him. The actual problem can be time consuming and will demand concentration as well. Further assuming that the developer is really sincere to his/her job and paying full time (even extra time ) to resolving that problem but unfortunately still not able to solve it. And in such a situation (when your are not even able to understand the problem fully) you keep on asking about the issue by taking progress everyday and even informally twice a day. The result would be extreme frustration and disturbance for the developer. Whether its an app for gathering daily progress or its just daily standup meeting both can be frustrating.

On the other hand, keeping all the other factors same, just assume that you have strong technical background and have worked on the same technologies in the past. In this case, taking daily progress or having standup meetings is really helpful. Developers will surely trust you and your expertise and will be comfortable in discussing the big challenge they are facing. You'll provide some suggestions which can be helpful or even if they are not directly helpful they'll help in providing some alternative approaches.

However, in any case daily standup meetings must create a sense of you being a team member not a head/lead/manager. Unless your team members consider you at the same level as they are, they won't be able to communicate their concerns/suggestions/problems/feedback etc.

Another point to be considered is the size of your team and the time you have for managing them, before thinking of using some automated progress tracking software or increasing your interaction. You need to make sure that whatever concerns have been raised by your team, you are able to resolve them asap. A major demotivating factor for a team member is that their concerns/suggestions/feedback is not taken seriously or is not valued. Knowing the daily progress is important but only in case you are fully involved in the team work. If you are involved in some side businesses as well, don't try to interact more with your team. Think of a situation in which your team's response is overwhelming and they are submitting their tasks well before time, raising concerns and queries but you are unable to provide timely feedback and reviews. In such a situation, your influence as a team lead will be greatly reduced


问:
Domain model associations that do not required the behaviour of the associated object. How to model?
I've been struggling with this question for a while.

I'm specifically thinking within the object orientated domain model.

Let's say I have two entities. A supplier and a customer. There is a relationship that a supplier can have many customers, and a customer (in this case) can only have one supplier.

The issue I have is that neither object needs any behaviour of the other object i.e. the supplier object does not need to use any behaviour of the customer object and visa versa.

There is however still an association between them. The reason is that the problem domain requires that all a suppliers customers are destroyed if the supplier is destroyed. We also need to be able to retrieve a collection of all customers associated with a supplier.

How is this managed in the OO domain model? Who is responsible for the association?

Some may say that there should be a getCustomers() method on the supplier object and this is where the association lies. I don't really like this as it makes it difficult to close the supplier class (violation of Open Closed Principle). Every time we create a new type of class which has an association to a supplier, we have to add a get method to the supplier.

One thing I think could be used to model the association are repositories (from Eric Evens Domain Driven Design book). I guess it would be the Repository that then cares about this relationship? We could call selectCustomersFor(supplier_id) etc

Edit

The only reason I can see for having the association is for object retrieval criteria or object destruction (i.e. if user is destroyed, all customers will be destroyed). To me, it is not the responsibility of either object to retrieve or destroy itself. You could argue that the supplier should retrieve/destroy a customer, but this surely violates the Single Responsibility rule, and could also lead to Open Closed violation.

Why would we then bother to add the responsibility of association to an object thats doesn't use it? Its useless to the object. The association isn't useless though, I just feel something else should be responsible for it.

答:
Sometimes an object doesn't use it's own relationships. A customer doesn't always use it's supplier in code, but others do want to use it. And by putting the relation in your domain model, you allow easy and quick access to this relationship.

When you hardly use the relationship it could be better to request the supplier from the repository.

But you also talk about deleting the customer when the supplier gets deleted. If you are using an ORM, changes are they can do this for you, but therefore you will probably need to have the relationship in you domain model (if you also map your domain model directly to the database) (This is at least true for Hibernate (java) / NHibernate (.NET)).
When you write all your database queries by hand, it doesn't matter so much.

So I think it is just a matter of convenience vs. a pure domain model.


问:
When should you call yourself a senior developer?

Possible Duplicate:

  Whats the difference between Entry Level/Jr/Sr developers?

I'm curious what senior developer means because apparently the definition doesn't mean what I thought it would. I keep seeing these teens at 22-23 years old who call themselves senior X developer or senior Y developer. To me, a senior must have 10 years or so experience in programming to call himself 'senior'. I've seen a lot of these teens here (hence the question). Am I wrong? Why?

答:
It could have something to do with money.

Some companies follow a set salary plan. They can't put you in the middle of the 'Developer'-ladder, because of some given rules. But they can put you in the bottom of the 'Senior Developer'-ladder.

Personally, I find it strange if a person is given a senior title right out of college, but on the other side - who cares? I have been an 'developer' for some ten years now, and even though I get a 'senior' title when I change workplace now, it doesn't mean anything. I will still be a freshman in the new domain - at least for a while...

ContentLicense: CC BY-SA 2.5


答:
As Robert Harvey suggests, don't micro manage your team. Give the team some prioritized tasks with concrete business value and let your team figure out best how to deliver this business value.

If the team delivers business value, then you should be happy. How they go about making sure that they deliver the requested features should be up to them.

However:

Cards will stay in progress for days on end without an update at the daily stand-up

This could indicate that there is a deficiency in the process.

It could be the team that is not really functioning as a team, and not stepping in to help each other out when they are stuck. It could also be the communication with the business. The tasks are too big, so it becomes difficult to figure out what is needed. Specifications are not clear.

It could also be that there is no real problem at all. Maybe the team just works fine with cards representing major pieces of work that takes days to complete, and maybe the team is working fine to achieve this.

I think that it is valid to use the retrospective as a platform for expressing your concern. Sometimes it's a good thing to receive observations from the outside.

But let the team figure out if there is a problem, and what is the cause of this. And be ready to accept that perhaps you need to adjust the way that tasks are delivered to the team.

Remember that the daily stand up is a tool for the team to help them organize the work; it is NOT a tool for managers to keep track on what the team is doing.

Title: How do you track what you and your team are working on day-to-day?

Body:
I'm struggling with how to keep track of what myself and people on my team actually do each day. I get a good broad picture by going over completed cards each week and stand-ups help a bit, but I feel like I don't have a good handle on the day-to-day workings of my team. Cards will stay in progress for days on end without an update at the daily stand-up, and some engineers are my team aren't the most communicative.

I've thought about implementing some sort of daily record that everyone fills out (via a mailing list or a shared google doc) but this seems fairly cumbersome and manual.

Monitoring GitHub activity does an ok job but can be a little bit overwhelming with how many emails it sends out everyday. I've thought about trying to build a digest system for it, but don't have the time to spare.

What strategies have you implemented to stay on top of what your team is doing everyday so that you can measure work on "in progress" tasks?


问:
Is there any logical reason to auto-generate code documentation?
Automatic documentation generation can be done with a variety of tools, GhostDoc being one of the more prominent.  However, by definition, everything it generates is redundant.  It takes a look at names of methods, classes, etc. and outputs English that might explain them more verbosely.  In the best case, it does what the reader could already do in their head (examples taken from here):

```<code>/// <summary>
/// Initializes a new instance of the <see cref="Person"/> class.
/// </summary>
public Person() ...
</code>```

In the worst, it can actually end up generating bizarre documentation that is actually misleading in its attempt to heuristically figure out the meaning of names:

```<code>/// <summary>
/// Riches the text selection changed.
/// </summary>
/// <param name="richTextBox">The rich text box.</param>
private void RichTextSelection_Changed(System.Windows.Controls.RichTextBox richTextBox) ...
</code>```

It seems that the attitude with GhostDoc is, "it's intrinsically better to have some kind of formal XML documentation", but when that documentation is 100% redundant, why?  Isn't it just wasting a ton of space at best?

At my workplace, we have to document everything, and almost always with GhostDoc's auto-generated docs.  Do you do this, and are there any rational reasons not to simply leave code undocumented if you aren't going to actually write the documentation yourself?

答:
As a C#-developer I use Stylecop, which mandates comments for all classes, methods etc. I autogenerate these comments using a tool. Most of the time, the comments generated by the tool are sufficient and could be inferred by the name of the object, e.g. a Person class has and ID field.

But IF I want to comment a non obvious method further, it is very easy to expand the boilerplate documentation and a few explanations about what it does. As an example: I have a method on my Person class, which returns FirstName + Lastname, but I added a little bit of docu about what's happening when one of both is missing.

In short: I think the boilerplate docu can be detrimental if you never change the text provided by the generator. In that case, it's just line noise. But if you see them as a template, they lower the bar for providing good and useful comments for yourself or your consumers. Could you write the comments without autogenerating them? Sure, but you would have to abide to the format (which in C# case is rather verbose and annoying to generate by hand) and that lowers the chance that you really provide this comment at al..


答:
[...] document everything, and almost always with GhostDoc's auto-generated docs. Do you do this, and are there any rational reasons not to simply leave code undocumented if you aren't going to actually write the documentation yourself?

No. The documentation generated by GhostDoc is boilerplate (similar to how creating a new OO class in an IDE creates the boileplate for a class with a constructor or something). The usefull part of the documentation is what would follow after adding the boilerplate.

While you have to document everything at your workplace, it seems your coleagues found the perfect way around it: just pretend.

Title: Is there any logical reason to auto-generate code documentation?

Body:
Automatic documentation generation can be done with a variety of tools, GhostDoc being one of the more prominent.  However, by definition, everything it generates is redundant.  It takes a look at names of methods, classes, etc. and outputs English that might explain them more verbosely.  In the best case, it does what the reader could already do in their head (examples taken from here):

```<code>/// <summary>
/// Initializes a new instance of the <see cref="Person"/> class.
/// </summary>
public Person() ...
</code>```

In the worst, it can actually end up generating bizarre documentation that is actually misleading in its attempt to heuristically figure out the meaning of names:

```<code>/// <summary>
/// Riches the text selection changed.
/// </summary>
/// <param name="richTextBox">The rich text box.</param>
private void RichTextSelection_Changed(System.Windows.Controls.RichTextBox richTextBox) ...
</code>```

It seems that the attitude with GhostDoc is, "it's intrinsically better to have some kind of formal XML documentation", but when that documentation is 100% redundant, why?  Isn't it just wasting a ton of space at best?

At my workplace, we have to document everything, and almost always with GhostDoc's auto-generated docs.  Do you do this, and are there any rational reasons not to simply leave code undocumented if you aren't going to actually write the documentation yourself?


问:
Providing friendly URLs for a website vs. realities of database IDs
We have a database of resources, be they products, blog posts or something. We need to design a URL scheme to address them, for the public website.

Here are two examples that are database ID bound:

https://www.youtube.com/watch?v=7FPS6llqhXw

http://www.amazon.co.uk/gp/product/B000NHOMSQ

Here's an example that's friendly:

http://en.wikipedia.org/wiki/LED_circuit

(A little glimpse into my browsing life there)

I like the friendly URLs since you have an idea about what's on the end of the URL when you hover or see it in an email or document. It's better for SEO, or it used to be.

What happens when the document or product is renamed? Either because it changed (Wiki may not change but our resources could) or due to a typo, right? Our resources are very technical, long words and error prone.

Also, we have a database ID, which is a number. Let's look at an idea for an address of a video using a pretend rental store:

http://vidsyeah.com/video/sliding-doors/287171

The ID is obvious and is used in the DB look-up. Fine.

The sliding-doors bit is non-unique and just generated from the video title, it could be verified on GET, so if gliding-doors was entered and doesn't match what's really in doc 287171 it responds 404.

Or maybe it could be ignored, allowing humans to stick whatever they like in there, if someone ever cared to. So this URL would also work:

http://vidsyeah.com/video/anything-at_all/287171

The issue with verifying the friendly part is, as mentioned, the problem of renaming or typo correction. If the name changed, and in our domain that does happen, we don't want to break the URLs that are out there, so should we:

Just not verify the friendly part.

Verify, but add a 'history' of friendly parts to the database record so any previous friendly IDs still work!

Your thoughts and ideas are welcome.

Luke

答:
What happens when the document or product is renamed?

HTTP response 301 (Moved) was designed for this purpose. If any client goes to the old URI you simply send them the new URI and they can redirect to that.

The sliding-doors bit is non-unique and just generated from the video title, it could be verified on GET, so if gliding-doors was entered and doesn't match what's really in doc 287171 it responds 404.

If I follow correctly this is duplicating work, you have both a name identifier for the resource and an id in the same URI. That doesn't serve any purpose.

If you are worried about multiple movies having the same name you can add extra information about the film into the URL

```<code>http://vidsyeah.com/video/2000/sliding_doors
http://vidsyeah.com/video/1932/sliding_doors
</code>```

or

```<code>http://vidsyeah.com/video/studios/paramount/sliding_doors
http://vidsyeah.com/video/studios/warnerbros/sliding_doors
</code>```

Having said that there is nothing wrong with using IDs if that makes sense for your data model, particularly if the only thing you are grouping by is that they are videos.

```<code>http://vidsyeah.com/video/210232
http://vidsyeah.com/video/2342
</code>```

The client, either a computer or a human user shouldn't too reliant on the URI structure in the first place, they should be looking at the content you have returned to figure out which resource to find.

There is nothing wrong with having a sensible URI system that makes it easy for someone to just guess a location of a resource or to navigate up and down the structure based on shared properties (ie all movies in 2004), but your system should not rely on that and no client should break if you change your URIs

Or to put it another way, you should be able to change over night from

```<code>http://vidsyeah.com/video/studios/paramount/sliding_doors
</code>```

to

```<code>http://vidsyeah.com/video/12323
</code>```

and no client should break because the clients should be looking at content not URLs.

Body:
What happens when the document or product is renamed?

HTTP response 301 (Moved) was designed for this purpose. If any client goes to the old URI you simply send them the new URI and they can redirect to that.

The sliding-doors bit is non-unique and just generated from the video title, it could be verified on GET, so if gliding-doors was entered and doesn't match what's really in doc 287171 it responds 404.

If I follow correctly this is duplicating work, you have both a name identifier for the resource and an id in the same URI. That doesn't serve any purpose.

If you are worried about multiple movies having the same name you can add extra information about the film into the URL

http://vidsyeah.com/video/2000/sliding_doors
http://vidsyeah.com/video/1932/sliding_doors

or

http://vidsyeah.com/video/studios/paramount/sliding_doors
http://vidsyeah.com/video/studios/warnerbros/sliding_doors

Having said that there is nothing wrong with using IDs if that makes sense for your data model, particularly if the only thing you are grouping by is that they are videos.

http://vidsyeah.com/video/210232
http://vidsyeah.com/video/2342

The client, either a computer or a human user shouldn't too reliant on the URI structure in the first place, they should be looking at the content you have returned to figure out which resource to find.

There is nothing wrong with having a sensible URI system that makes it easy for someone to just guess a location of a resource or to navigate up and down the structure based on shared properties (ie all movies in 2004), but your system should not rely on that and no client should break if you change your URIs

Or to put it another way, you should be able to change over night from

http://vidsyeah.com/video/studios/paramount/sliding_doors

to

http://vidsyeah.com/video/12323

and no client should break because the clients should be looking at content not URLs.


问:
What constitutes "improper use" of the javascript Eval feature?
Eval is a notoriously controversial language feature.  Douglas Crockford flat out rejects it. I'm wondering what specific risks Eval brings about.  According to this question, Improper use of eval opens up your code for injection attacks.

What are some improper uses of the Eval command, and what security holes do they open up?

答:
As pointed out by others, the most important thing when working with eval is to keep it safe. For that, you want to do thorough argument checking, and keep eval 'ed code simple since it is generally a lot harder to maintain and secure run-time generated code.

That being said, I enjoy using eval for two kinds of things (even though there might probably be better, less evil-ish alternatives):

Since eval is a way of "explicitly caching code", it can be used to improve performance. Note that optimizers are always being improved, but there is simply no guarantee as to what they can do for you. By making things explicit in code, you actually can help the optimizer make smarter decisions.

It can also be used to deliver basic forms of type-safety, as well as other language features that JS is lacking, without deteriorating performance.

This pre-compiled object iterator approach, for example, shows clear performance benefits when using eval for object property iteration. It also shows the beginnings of a powerful type system that can provide implicit constraint checking and a lot more, at little to no cost.

Many seasoned Javascript developers would probably point out that this is a rabbit hole, since, if you start writing Javascript this way, you essentially change the way you use the language. That however might not necessarily be a bad thing for those who enjoy Javascript but are also missing fundamental language features that can only be achieved by changing the way we use the language itself.


答:
In this form it's worse than useless but only because it relies on the public signature alone (which, in the case of Javadoc, is visible anyway to anyone reading the API doc).

But it is possible to write automated documentation tools that consider the body of the method too. As a proof of concept I wrote a lame little Eclipse plugin that adds a list of other methods called from the documented method to the Javadoc. (Not every call of course, you can define filters, by package for example.)

And I've actually found it quite handy when mentally mapping out a completely unfamiliar code base. Granted, it's a very limited use case but it was definitely a help.

Based on that experience the answer to the question is: yes, but we need much smarter tools.

Update: Of course an additional question (one that should be asked before writing any kind of documentation) is who the target audience is. If we're documenting a public API for clients of that API, adding all this implementation detail is a big no-no as anything you put in the Javadoc is technically part of the API.

But if the target audience is other developers working on the same product, automatically adding information on implementation details, such as which methods modify or read a certain field is both acceptable and fairly useful.


问:
How to design RESTful Web Api to represent Resources
I'm developing an ASP.NET Web Api 2 RESTful web api with .NET Framework 4.5.1 and C# and I'm trying to understand how to expose resources through a Web Api:

Imagine that I'm a group owner and I am the only one that can add new users to that group (I'm trying to simulate a WhatsApp group).

This is my C# class for user:

```<code>public class User
{
    public int UserId { get; set; }
    public string UserName { get; set; }

    public List<Group> Groups { get; set; }
    public List<Group> GroupsOwned { get; set; }
}
</code>```

And Group class:

```<code>public class Group
{
    public int GroupId { get; set; }
    public string GroupName { get; set; }

    public User Owner { get; set; }

    public List<User> Members { get; set; }
}
</code>```

How do I have to expose user's groups owned members in a RESTful Web Api?

I think I have to expose it this way:

```<code>"api/users/{ownerId}/groupsOwned/{groupId}/members/"
</code>```

I will allow PUT to modify the Group to add a new member, and probably GET to get all members.

Any advice?

答:
When you say 'expose user's groups owned members in a RESTful Web Api?' This could mean two things:

URI structure (you seem to have identified this already)

Resource representation (html, json etc)

If you are talking about representation, my personal preference is JSON HAL. It allows a really simple model of _links, _data, _embedded which helps drive descoverability and connectedness.

From your comments you seem to want to know how to access the members. This is simply

```<code>api/users/{ownerId}/groupsOwned/{groupId}/members/{memberId}
</code>```

Or if you want to access all members:

```<code>api/users/{ownerId}/groupsOwned/{groupId}/members/
</code>```

But be careful, you should really use nested representations of resource when you return a collection of resources like the above URI would produce. Look at the HAL spec above, that will help explain embedding resources into resources.

EDIT

I think I have to expose it this way:

"api/users/{ownerId}/groupsOwned/{groupId}/members/" I will allow POST
  to add new members, and probably GET to get all members.

Yes, that's correct

Body:
When you say 'expose user's groups owned members in a RESTful Web Api?' This could mean two things:

URI structure (you seem to have identified this already)

Resource representation (html, json etc)

If you are talking about representation, my personal preference is JSON HAL. It allows a really simple model of _links, _data, _embedded which helps drive descoverability and connectedness.

From your comments you seem to want to know how to access the members. This is simply

api/users/{ownerId}/groupsOwned/{groupId}/members/{memberId}

Or if you want to access all members:

api/users/{ownerId}/groupsOwned/{groupId}/members/

But be careful, you should really use nested representations of resource when you return a collection of resources like the above URI would produce. Look at the HAL spec above, that will help explain embedding resources into resources.

EDIT

I think I have to expose it this way:

"api/users/{ownerId}/groupsOwned/{groupId}/members/" I will allow POST
  to add new members, and probably GET to get all members.

Yes, that's correct


答:
'Push messaging' not 'pull messaging'

A developer will often get to one of the following states that matter to you:

Yaaay, I did X !

I'm working on X, but it looks like it will take a prolonged time...

I'm stuck on problem Y, am researching it but might need advice;

I'm blocked because I'm waiting for A,B and C.

Ideally, you want to have a reasonably up-to-date information on these statuses without disrupting actual productivity. Constant "Are we there yet?" is counterproductive, but it may be that you can do something useful for states 2-4, so you need to get informed about them.

What will work is a culture of 'push messaging', preferably in an automated way. You may not need to look at the whole commit-log, but you can make a "dashboard" where you see the latest commit or the latest solved ticket (for bugs or features) of every teammember. For the rest of the situations, you can get them to e-mail you proactively with such updates (hopefully they are more rare than commits) or go and ask them if you're not seeing continuous progress on whatever dashboard - if you have an internal agreement that getting stuck needs to be raised (it might be that some feature isn't needed if it turns out that it costs 80 hours not 8 hours), then either they'll keep you up to date or get bothered by you.

Alternatively, you may make a culture of something like https://idonethis.com/ daily reports going out to the whole team - this will ensure that others are on the same page as well.


问:
How does the GNU General Public License (GPL) conform to the Open Source Initiative's (OSI) Open Source Definition (OSD)?
From the OSI's OSD:

Free Redistribution

The license shall not restrict any party from selling or giving away the software as a component of an aggregate software distribution containing programs from several different sources. The license shall not require a royalty or other fee for such sale.

and

Derived Works

The license must allow modifications and derived works, and must allow them to be distributed under the same terms as the license of the original software.

If the license is GPL then point 3 would suggest that derived works must be distributed under the GPL too, which is the intention of such a 'viral' license. Taken together with point 1 though there seems to be a contradiction, as the GPL specifically restricts you from selling the software.

As the OSI lists the GPL as OpenSource I must be missing something. Can anyone explain?

EDIT:

The FAQ section of the OSI site seems to speak to this issue but I am still unsure about their answer. I think this should mean that you can use GPL code in software that you sell as long as you also provide on request the new source code. However section 9 says:

License Must Not Restrict Other Software

The license must not place restrictions on other software that is distributed along with the licensed software. For example, the license must not insist that all other programs distributed on the same medium must be open-source software.

Is the distinction here that derived software must be under the same license (point 3) but 'packaged with' is ok to be under a different license? I'm not quite sure what "distributed on the same medium" means.

答:
The GPL does not restrict you from selling software. It explicitly allows you to do so. Section 4 of the GPLv3 reads:

You may charge any price or no price for each copy that you convey

The recipient then receives the same rights, so they can also choose to give the software to another person for a price, for free, or keep it for themselves. The price they charge is completely independent from how much they paid for their copy. This is also explained in the section "Does the GPL allow me to sell copies of the program for money?" of the GPL FAQ

Regarding "9.License Must Not Restrict Other Software": The GPL doesn't do this. It is only "viral" in the sense when GPL code is combined with other code to create a new piece of software. But as long as a GPL and a non-GPL program stay independent programs which can run independently, neither affects the license conditions of the other and they can be distributed together on the same medium. The GPL FAQ says about this case:

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


答:
When constructing a REST service, I try to focus on the object in question and use the JSON to represent the structure of the data.

In this example, the object to be modified is the group. I would put this at the base of the URI and not have it buried in the middle.

```<code>/api/groups/{groupId}
</code>```

This should be valid because (hopefully) group IDs are unique across the application.

Next is the question of how to update members.

I imagine a JSON which looks something like:

```<code>{
    "groupId": "1111",
    "groupName": "A Group",
    "ownerId": "2222",
    "membersIds": [ "2222", "3333", "4444" ]
}
</code>```

The first option would be to PUT the whole object.

```<code>PUT /api/groups/1111

{
    "groupId": "1111",
    "groupName": "A Group",
    "ownerId": "2222",
    "membersIds": [ "2222", "3333", "4444" ]
}
</code>```

This is a simple API. A client would use a GET to get the current data, make changes, then PUT the result. It would be up to the server to validate the update as a whole, or reject the update as a whole if there is some error.

I understand this may not always be desirable, so I could understand wanting a shortcut which would only update members.

To this end here is the members shortcut:

```<code>/api/groups/{groupId}/members
</code>```

with the corresponding JSON:

```<code>[ "2222", "3333", "4444" ]
</code>```

This would still be a PUT because you are updating the existing data.

```<code>PUT /api/groups/1111/members

[ "2222", "3333", "4444" ]
</code>```

The PUT would replace all the current members with the members in the array. The current members could be requested with GET /api/groups/1111/members. It would be the client's responsibility to add new members to the current members.

This is still not what you asked for. You want a shortcut to simply add members. Here my method breaks down. You are not using the URI to represent the structure of the data, you are using the URI to perform an action with the data. This is not very RESTful (IMHO), but lots of people do it.

In the past, I've use CGI parameters to explicitly show an action.

```<code>/api/groups/{groupId}?action=addMembers
</code>```

Finally, we get to something that looks like what you asked for.

```<code>POST /api/groups/1111?action=addMembers

[ "3333", "4444"]
</code>```

To me, it doesn't look very RESTful, but utility trumps ideology and if this is exactly what you need, then here it is.

Title: How to design RESTful Web Api to represent Resources

Body:
I'm developing an ASP.NET Web Api 2 RESTful web api with .NET Framework 4.5.1 and C# and I'm trying to understand how to expose resources through a Web Api:

Imagine that I'm a group owner and I am the only one that can add new users to that group (I'm trying to simulate a WhatsApp group).

This is my C# class for user:

```<code>public class User
{
    public int UserId { get; set; }
    public string UserName { get; set; }

    public List<Group> Groups { get; set; }
    public List<Group> GroupsOwned { get; set; }
}
</code>```

And Group class:

```<code>public class Group
{
    public int GroupId { get; set; }
    public string GroupName { get; set; }

    public User Owner { get; set; }

    public List<User> Members { get; set; }
}
</code>```

How do I have to expose user's groups owned members in a RESTful Web Api?

I think I have to expose it this way:

```<code>"api/users/{ownerId}/groupsOwned/{groupId}/members/"
</code>```

I will allow PUT to modify the Group to add a new member, and probably GET to get all members.

Any advice?

Body:
When constructing a REST service, I try to focus on the object in question and use the JSON to represent the structure of the data.

In this example, the object to be modified is the group. I would put this at the base of the URI and not have it buried in the middle.

/api/groups/{groupId}

This should be valid because (hopefully) group IDs are unique across the application.

Next is the question of how to update members.

I imagine a JSON which looks something like:

{
    "groupId": "1111",
    "groupName": "A Group",
    "ownerId": "2222",
    "membersIds": [ "2222", "3333", "4444" ]
}

The first option would be to PUT the whole object.

PUT /api/groups/1111

{
    "groupId": "1111",
    "groupName": "A Group",
    "ownerId": "2222",
    "membersIds": [ "2222", "3333", "4444" ]
}

This is a simple API. A client would use a GET to get the current data, make changes, then PUT the result. It would be up to the server to validate the update as a whole, or reject the update as a whole if there is some error.

I understand this may not always be desirable, so I could understand wanting a shortcut which would only update members.

To this end here is the members shortcut:

/api/groups/{groupId}/members

with the corresponding JSON:

[ "2222", "3333", "4444" ]

This would still be a PUT because you are updating the existing data.

PUT /api/groups/1111/members

[ "2222", "3333", "4444" ]

The PUT would replace all the current members with the members in the array. The current members could be requested with GET /api/groups/1111/members. It would be the client's responsibility to add new members to the current members.

This is still not what you asked for. You want a shortcut to simply add members. Here my method breaks down. You are not using the URI to represent the structure of the data, you are using the URI to perform an action with the data. This is not very RESTful (IMHO), but lots of people do it.

In the past, I've use CGI parameters to explicitly show an action.

/api/groups/{groupId}?action=addMembers

Finally, we get to something that looks like what you asked for.

POST /api/groups/1111?action=addMembers

[ "3333", "4444"]

To me, it doesn't look very RESTful, but utility trumps ideology and if this is exactly what you need, then here it is.


问:
Should every member of scrum team be universal?
We have a scrum team where there are 5 developers, 2 automated testers, 1 manual tester. Our tasks are completely independent.

Shouldn't there be 8 people, every one should be able to do every task: write code, write tests for it, sometimes manually test something?

答:
They should be cross-functional, but not universal.

Understanding something of the domain of the person to whom you deliver artifacts or from whom you receive them is very helpful, but understanding it as well as they do is almost always far too difficult; if one person could easily master both domains (or all three), then they wouldn't have developed into different domains in the first place! Therefore, understanding enough to conduct a meaningful conversation about issues in it is what you should aim for.

A helpful metaphor is the evolution of human handedness. Wouldn't it be better if both our hands were as dexterous as the dominant hand is? Sure, but it would require more cognitive effort to control twice as many nerve connections at the same level of detail. Nothing is free, so something else would have to give. Since most tasks are very well doable with one dominant hand and one ancillary hand (e.g. holding something steady + carving intricate designs on it), we have to assume that overall the handed paradigm delivers more value for effort, so that's what mother nature went for.


答:
Aiming for a universal team is nice, but it might be easier (and more feasible) to aim for a team whose members are simply not too specialized. For example, among the programmers, you could try to ensure that you don't end up with one person who only does back-end coding, one person who only does JavaScript, and one person who only maintains the database. Try to ensure that all developers get some exposure to everything else. This ensures that if the UI needs a ton of work, and all is quiet on the database front, the DB guy can step in and lends a hand.

Similarly, you might want to get your automated testers and manual testers to cross-train on each other's work, so they can help each other when necessary.

Of course, there may be times where you need a large testing effort (and not so much programming) and you can try to press your programmers into helping with the testing and generally, they should be able to do it. In my experience, asking testers to write code (if there's a huge code push) is more difficult unless they have prior experience.

Title: Should every member of scrum team be universal?

Body:
We have a scrum team where there are 5 developers, 2 automated testers, 1 manual tester. Our tasks are completely independent.

Shouldn't there be 8 people, every one should be able to do every task: write code, write tests for it, sometimes manually test something?


答:
I wouldn't get too extreme (pardon the pun) in either direction.

If manual testing can only be done by one person, you have a problem. There could be parts of the app that don't require manual testing, but chances are you're going to delay a release eventually.

You need experts. Don't risk not having any experts in anything because they get spread too thin trying to learn everything or hopping from one cool framework to the other without getting anything shipped. Some people can get away with knowing just enough to work with and coordinate efforts with the person doing a different job. Not all devs are going to be experts at all the automated testing tools, but there are probably some coding practices to avoid because they make testing a living hell.

With Scrum, you're trying to create working software that is going to probably change often. Do what it takes to avoid any bottleneck in the process. If that means some people become more proficient at some things or someone else has to take-over when someone else is not available, then you have to do what it takes. Going too far in ether direction has its own set of problems.


问:
Which is a better pattern (coding style) for validating arguments - hurdle (barrier) or fence?
I don't know if there are any accepted names for these patterns (or anti-patterns), but I like to call them what I call them here. Actually, that would be Question 1: What are accepted names for these patterns, if any?

Suppose there is a method that accepts a bunch of parameters, and you need to check for invalid input before executing actual method code:

```<code>public static void myMethod (String param1, String param2, String param3)
</code>```

Hurdle Style

I call it so because it's like hurdles a track runner has to jump over to get to the finish line. You can also think of them as conditional barriers.

```<code>{
    if (param1 == null || param1.equals("")) {
        // some logging if necessary
        return; // or throw some Exception or change to a default value
    }

    if (param2 == null || param2.equals("")) {
        // I'll leave the comments out
        return;
    }

    if (param3 == null || param3.equals("")) {
        return;
    }

    // actual method code goes here.
}
</code>```

When the checks are for a certain small section in a larger method (and the section cannot be moved to a smaller private method), labelled blocks with break statements can be used:

```<code>{
    // method code before block

    myLabel:
    {
        if (param1 ... // I'll leave out the rest for brevity
            break myLabel;
        if (param2 ...
            break myLabel;
        ...

        // code working on valid input goes here

    } // 'break myLabel' will exit here

    // method code after block
}
</code>```

Fence Style

This surrounds the code with a fence that has a conditional gate that must be opened before the code can be accessed. Nested fences would mean more gates to reach the code (like a Russian doll).

```<code>{
    if (param1 != null && !param1.equals("")) {
        if (param2 != null && !param2.equals("")) {
            if (param3 != null && !param3.equals("")) {

                // actual method code goes here.

            } else {
                // some logging here
            }
        } else {
            // some logging here
        }
    } else {
        // some logging here
    }
}
</code>```

It could be re-written as follows too. The logging statements are right beside the checks, rather than being after the actual method code.

```<code>{
    if (param1 == null || param1.equals("")) {
        // some logging here

    } else if (param2 == null || param2.equals("")) {
        // some logging here

    } else if (param3 == null || param3.equals("")) {
        // some logging here

    } else {

        // actual method code goes here.

    }
}
</code>```

Question 2: Which style is better, and why?

Question 3: Are there any other styles?

I personally prefer hurdle style because it looks easier on the eyes and does not keep indenting the code to the right every time there's a new parameter. It allows intermittent code between checks, and it's neat, but it's also a little difficult to maintain (several exit points).

The first version of fence style quickly gets really ugly when adding parameters, but I suppose it's also easier to understand. While the second version is better, it can be broken accidentally by a future coder, and does not allow intermittent code between conditional checks.

答:
Your first “hurdle” style is superior in any respect.

It saves you many levels of indentation. This alone makes it much more straightforward to understand.

It's diff friendly: Adding another constraint doesn't require you to re-indent all your code.

Validation is located at one place – at the top of the function. With the other style, it is before and after the main code. Putting all validation code into one place reduces cognitive load.

Multiple exit points don't matter very much in a language with garbage collection. Striving for a single return is a relic from olden times where everything had to be deallocated manually.


答:
I think the best answer was given by Darknight.

I feel the need to point out the following.

2-3 years of programming experience (working + personal together) is just not enough for one to have seen sufficient number of projects and have dealt with a sufficient amount of problems. Just won't work. You need time to let things go through your head, to reflect on your experience and to move mentally to a higher level of thinking. Doesn't happen overnight.

I'd say under 5-7 years of practice (again working + personal together) a miracle is not to expect. One might get a lot of experience with certain languages and frameworks, but not yet jump to a new level of thinking.

The other thing is the overall maturity of an individual. In my opinion it first comes closer to 30 years old. Prior to that our brain may be working at a higher clock rate, but it would be processing junk, because it lacks sufficient data in the memory to see a bigger picture. Our general life experience adds something subtle but real to the way we think and work, so to programming as one other kind of work as well.

My personal acceptance of a senior: somebody at least 27 y.o. with at least 7 years of practice. Prior to that I'd personally be skeptical (but still open-minded, it'll just take more proof to me).

Title: When should you call yourself a senior developer?

Body:
Possible Duplicate:

  Whats the difference between Entry Level/Jr/Sr developers?

I'm curious what senior developer means because apparently the definition doesn't mean what I thought it would. I keep seeing these teens at 22-23 years old who call themselves senior X developer or senior Y developer. To me, a senior must have 10 years or so experience in programming to call himself 'senior'. I've seen a lot of these teens here (hence the question). Am I wrong? Why?


答:
Your example is specifically dealing with checking that the calling code is conforming to the contract.  If that's the case then the hurdle style is typically cleaner and easier to read, usually because you will throw an exception so there's no expectation that there's some other piece of code lower down in the method that will miss being executed.

There is another case where you're decomposing the function into two parts (similar to pattern matching in functional languages).  Consider the case of a recursive function:

```<code>int sum(int upTo)
{
    if(upTo<= 0) return 0;

    int previousSum = sum(upTo-1);
    return previousSum + upTo;
}
</code>```

If you're only checking for stopping criteria, then the hurdle style is still typical.

There is another case where you have to do something else after your decision (this is less common):

```<code>int sum(int upTo)
{
    int result;
    if(counter <= 0)
    {
        result = 0;
    }
    else
    {
        int previousSum = sum(upTo-1);
        result = previousSum + upTo;
    }

    Console.WriteLine("Intermediate sum result: {0}", result);

    return result;
}
</code>```

In that case it's typical to use the fence style.  Note that using the hurdle style here would produce a different result, because you either need to write the Console line twice or it won't spit out the line when the value is zero.

The style you choose communicates to the reader what type of function it is.  If you find that the function or method becomes so long that it's not clear, then consider breaking it up into multiple functions to make it clearer.

Typically this should be changed to a hurdle style with a helper function:

```<code>int sum(int upTo)
{
    int result = sumHelper(upTo);
    Console.WriteLine("Intermediate sum result: {0}", result);
    return result;
}

int sumHelper(int upTo)
{
    if(upTo<= 0) return 0;

    int previousSum = sum(upTo-1);
    return previousSum + upTo;
}
</code>```

TL;DR - Hurdle is the most common, but choose the appropriate style for your specific situation and make sure your functions are short/simple enough to be obviously correct either way.

Title: Which is a better pattern (coding style) for validating arguments - hurdle (barrier) or fence?

Body:
I don't know if there are any accepted names for these patterns (or anti-patterns), but I like to call them what I call them here. Actually, that would be Question 1: What are accepted names for these patterns, if any?

Suppose there is a method that accepts a bunch of parameters, and you need to check for invalid input before executing actual method code:

```<code>public static void myMethod (String param1, String param2, String param3)
</code>```

Hurdle Style

I call it so because it's like hurdles a track runner has to jump over to get to the finish line. You can also think of them as conditional barriers.

```<code>{
    if (param1 == null || param1.equals("")) {
        // some logging if necessary
        return; // or throw some Exception or change to a default value
    }

    if (param2 == null || param2.equals("")) {
        // I'll leave the comments out
        return;
    }

    if (param3 == null || param3.equals("")) {
        return;
    }

    // actual method code goes here.
}
</code>```

When the checks are for a certain small section in a larger method (and the section cannot be moved to a smaller private method), labelled blocks with break statements can be used:

```<code>{
    // method code before block

    myLabel:
    {
        if (param1 ... // I'll leave out the rest for brevity
            break myLabel;
        if (param2 ...
            break myLabel;
        ...

        // code working on valid input goes here

    } // 'break myLabel' will exit here

    // method code after block
}
</code>```

Fence Style

This surrounds the code with a fence that has a conditional gate that must be opened before the code can be accessed. Nested fences would mean more gates to reach the code (like a Russian doll).

```<code>{
    if (param1 != null && !param1.equals("")) {
        if (param2 != null && !param2.equals("")) {
            if (param3 != null && !param3.equals("")) {

                // actual method code goes here.

            } else {
                // some logging here
            }
        } else {
            // some logging here
        }
    } else {
        // some logging here
    }
}
</code>```

It could be re-written as follows too. The logging statements are right beside the checks, rather than being after the actual method code.

```<code>{
    if (param1 == null || param1.equals("")) {
        // some logging here

    } else if (param2 == null || param2.equals("")) {
        // some logging here

    } else if (param3 == null || param3.equals("")) {
        // some logging here

    } else {

        // actual method code goes here.

    }
}
</code>```

Question 2: Which style is better, and why?

Question 3: Are there any other styles?

I personally prefer hurdle style because it looks easier on the eyes and does not keep indenting the code to the right every time there's a new parameter. It allows intermittent code between checks, and it's neat, but it's also a little difficult to maintain (several exit points).

The first version of fence style quickly gets really ugly when adding parameters, but I suppose it's also easier to understand. While the second version is better, it can be broken accidentally by a future coder, and does not allow intermittent code between conditional checks.

Body:
Your example is specifically dealing with checking that the calling code is conforming to the contract.  If that's the case then the hurdle style is typically cleaner and easier to read, usually because you will throw an exception so there's no expectation that there's some other piece of code lower down in the method that will miss being executed.

There is another case where you're decomposing the function into two parts (similar to pattern matching in functional languages).  Consider the case of a recursive function:

int sum(int upTo)
{
    if(upTo<= 0) return 0;

    int previousSum = sum(upTo-1);
    return previousSum + upTo;
}

If you're only checking for stopping criteria, then the hurdle style is still typical.

There is another case where you have to do something else after your decision (this is less common):

int sum(int upTo)
{
    int result;
    if(counter <= 0)
    {
        result = 0;
    }
    else
    {
        int previousSum = sum(upTo-1);
        result = previousSum + upTo;
    }

    Console.WriteLine("Intermediate sum result: {0}", result);

    return result;
}

In that case it's typical to use the fence style.  Note that using the hurdle style here would produce a different result, because you either need to write the Console line twice or it won't spit out the line when the value is zero.

The style you choose communicates to the reader what type of function it is.  If you find that the function or method becomes so long that it's not clear, then consider breaking it up into multiple functions to make it clearer.

Typically this should be changed to a hurdle style with a helper function:

int sum(int upTo)
{
    int result = sumHelper(upTo);
    Console.WriteLine("Intermediate sum result: {0}", result);
    return result;
}

int sumHelper(int upTo)
{
    if(upTo<= 0) return 0;

    int previousSum = sum(upTo-1);
    return previousSum + upTo;
}

TL;DR - Hurdle is the most common, but choose the appropriate style for your specific situation and make sure your functions are short/simple enough to be obviously correct either way.


答:
I am looking for a way of saying: Increase the weight of o1 by 1. Increase the weight of o2 by 1. Increase the weight of o1 by 1. Now give me the results sorted by their weight.

This seems like a job for a priority queue, where the priority_number is the weight you want to assign.

Title: Efficient "Object with weights" structure

Body:
I need to find an "efficient" data structure / set of algorithms to do the following things:

I have a list of objects. I need to assign them weights and later on increase or decrease these weights.

For instance:
We have the hashmaps {o1}, {o2}, {o3}. The {o}'s don't have any particullar structure, just random json.

I am looking for a way of saying: Increase the weight of o1 by 1. Increase the weight of o2 by 1. Increase the weight of o1 by 1. Now give me the results sorted by their weight.

I am using Python. So far I have tried using a normal hashmap to store them, but the problem is that I can't just hash the {o}'s. I thought of hashing the pointer of the {o}'s in memory, but it seems I don't have access to it in Python.


问:
Microchip XC8: How to pack code against an upper limit?
I have a project for a PIC16F1454 that needs some custom linking.  Basically, I've separated my code into two parts that can be downloaded separately in the field and thus update (almost) all of the flash memory, including the bootloader.  As part of the plan to avoid bricking itself, I have this structure:

Lower, protected by hardware, not field-updateable:

Startup and image-copy code, written in assembly

Middle:

Application space

Also used to download new images

Upper:

Bootloader space

And there's some code in various places that enforces that structure.

The bootloader includes a USB stack, a main loop, and some helper functions that add up to slightly more than one page of flash, which causes some problems for the linker.  For example, the help file says that this option is supposed to concatenate the entire list and put it against the specified upper limit (note the negative address):

-L-pUSBCode=-1FFEh,USBConst,BootloaderCode,BootloaderConst

But when I do that, all four psects overlap, with the usual, unintended consequences.  I did this:

-L-aBootloader=1400h-17FFh,1800h-1FFDh -L-dBootloader=2 -L-pUSBCode=Bootloader -L-pUSBConst=Bootloader -L-pBootloaderCode=Bootloader -L-pBootloaderConst=Bootloader

which defines a class with 2-byte elements that crosses a page boundary at 1800h and puts all four psects in that class.  While they didn't overlap, I got a big hole next to the page boundary, big enough for several of the helper functions to fit in.

I could assign functions more granularly to more than four psects, and that would probably make things fit better, but I'd rather not make it any more complicated than I have to.  Someone else (could be me after a few months) is probably going to modify it later, and I don't expect him to be intimately familiar with the details.

How can I pack the entire bootloader section as tightly as possible into upper memory, accounting for the springboard to main() at 1FFEh-1FFFh, without requiring a future developer to change anything outside of the C source files?

答:
I solved the problem, but not in the way I was thinking originally.  I realized that it was okay to have some application code in the bootloader section, just not the other way around.  So if the boot section is bigger than it needs to be and the linker fills in some of the gaps with app code, that's fine.  The app code just won't run until the app section is verified.

So now I have:

-L-pUSBConst=1200h -L-aBootloader=1200h-17FFh,1800h-1FFDh -L-dBootloader=2 -L-pBootloaderText=Bootloader -L-pUSBText=Bootloader -L-pISRText=0220h

and it seems to work.  0x1200 is the halfway point of the space left by the startup code, rounded up to the nearest 0x0100 so it doesn't complain about the constants being there.  This, then, is the biggest bootloader / USB driver I can have without causing other problems anyway.

As a side-note, the optimizer only works on sections named *text* (wildcards, not case-sensitive).  It took a while to figure out why my carefully-timed ISR was optimized even worse than the free version.

Thanks for your help!


问:
Defining error codes
We are designing an error-handling framework for a cryptographic library written in C.

The approach we are taking is that relatively few errors are propagated back to the user since on most occasions he cannot do anything about them (notable exception: parameter validation errors. Of course we tell the user if a call succeeded. We'd also create log entries for fault investigation.) In short, just because we have an error condition somewhere inside the library it does not mean that we need a public (user-facing) error code for it.

Also, from past experience we think that a significant portion of error conditions that require error codes pertain to very narrow areas of code, it is often the case that a particular error is only returned from (or set by) one function.

Therefore we would like to define error codes at the lowest possible level. For example, if only one function can return/set a particular error code we would define that code in the .h file where the function prototype is declared.

However, in such case we might get error code conflicts - the same error code value for different errors. Can someone please propose an elegant approach to avoid such conflicts? Or at the very least an automated mechanism to check for such conflicts (which can then be fixed by hand)?

答:
we would define that code in the .h file where the function prototype is declared.

I would recommend against this as you don't have anything to reduce the space for potential numbering conflicts.

Instead, use a common header file providing error codes for both your client and server applications.  As an alternative, the client file can simply be a subset of the server error code file.

Within the common header file, each major area of your application will get a sequence of error numbers.  And from within each major area, you can assign subsets of error code ranges to the modules within that layer.

For example, say you have a session manager, a business logic, and a database access layers in your server application.  Your header file might be broken down like this:

```<code>/*
 * our error.h file
 */
/* Common Errors 0 - 99 */
#define SUCCESS 0
#define GENERIC_ERROR 1
/* Session Manager errors 100 - 199 */
    /* Login issues 100 - 110 */
#define BAD_PASSWORD 101
    /* session issues 120 - 125 */
    /* other session issues 150 - 162 */
#define SOMETHING_ELSE 150
/* Business logic errors 200 - 299 */

/* Database errors 300 - 399 */
#define INVALID_CONNECTION 300
</code>```

The advantage of this approach is it cuts down the overall space where conflicts in numbering can occur.  Potential conflict is limited to the areas where two or more developers are working simultaneously.

By having a common error header file, your developers can check out the file as needed to create a new error and make sure they are claiming an unused number at that point in time.

Potential pitfalls with this approach are when developers don't frequently commit their local copy of the error header.  But that's a process issue that will usually work its way out once those developers have had to deal with it a few times.  And since they are referring to the error number through the #define it's not that big of a change.

Another pitfall is when you misjudge the range required for a layer or sub-module.  The easiest way to avoid this is to pre-allocate really large ranges for each layer and sub-module.  And from there, you should be able to trim from one sub-module in order to give greater range to another.  And there's nothing that says the ranges have to be contiguous.

Title: Defining error codes

Body:
we would define that code in the .h file where the function prototype is declared.

I would recommend against this as you don't have anything to reduce the space for potential numbering conflicts.

Instead, use a common header file providing error codes for both your client and server applications.  As an alternative, the client file can simply be a subset of the server error code file.

Within the common header file, each major area of your application will get a sequence of error numbers.  And from within each major area, you can assign subsets of error code ranges to the modules within that layer.

For example, say you have a session manager, a business logic, and a database access layers in your server application.  Your header file might be broken down like this:

/*
 * our error.h file
 */
/* Common Errors 0 - 99 */
#define SUCCESS 0
#define GENERIC_ERROR 1
/* Session Manager errors 100 - 199 */
    /* Login issues 100 - 110 */
#define BAD_PASSWORD 101
    /* session issues 120 - 125 */
    /* other session issues 150 - 162 */
#define SOMETHING_ELSE 150
/* Business logic errors 200 - 299 */

/* Database errors 300 - 399 */
#define INVALID_CONNECTION 300

The advantage of this approach is it cuts down the overall space where conflicts in numbering can occur.  Potential conflict is limited to the areas where two or more developers are working simultaneously.

By having a common error header file, your developers can check out the file as needed to create a new error and make sure they are claiming an unused number at that point in time.

Potential pitfalls with this approach are when developers don't frequently commit their local copy of the error header.  But that's a process issue that will usually work its way out once those developers have had to deal with it a few times.  And since they are referring to the error number through the #define it's not that big of a change.

Another pitfall is when you misjudge the range required for a layer or sub-module.  The easiest way to avoid this is to pre-allocate really large ranges for each layer and sub-module.  And from there, you should be able to trim from one sub-module in order to give greater range to another.  And there's nothing that says the ranges have to be contiguous.


答:
Universal is a great concept, and certainly the gap between testers and developers is narrowing. However...... Nobody is going to be an expert in everything, so it does make sense to push user stories to someone who can move them through reasonably quickly.  I had a team where everyone was supposed to be able to do everything, and it was really slow.  Turns out my team members were spending the first two days in every user story refactoring the code to suit their personal style.

It's a balance.  If you have loads of areas that only one person can deal with, you've got a big problem.  But you probably aren't going to get to the stage where everyone can deal with everything.


问:
What is the benefit of passing a delegate to the constructor instead of just having the client code create and pass the ParserSettings?
When answering a question on Stack Overflow, the library appeared to have a weird way to specify configuration, through an Action passed to the constructor:

```<code>public Parser(Action<ParserSettings> configuration)
{
    if (configuration == null) throw new ArgumentNullException("configuration");
    this.settings = new ParserSettings();
    configuration(this.settings);
    this.settings.Consumed = true;
}

internal Parser(ParserSettings settings)
{
    this.settings = settings;
    this.settings.Consumed = true;
}
</code>```

So to specify the settings you provide a Action<ParserSettings> that modifies the settings:

```<code>var parser = new Parser( s => { s.CaseSensitive = false; } );
</code>```

I don't understand what this pattern accomplishes. What is the benefit of passing a delegate to the constructor instead of just having the client code create and pass the ParserSettings to the constructor?

答:
Passing a delegate allows the caller instantiating the object to inject custom initialization behavior.  Note the configuration(this.settings) call in the constructor code, which executes the behavior provided by the constructor delegate.

I can think of a number of reasons why this might be handy.  One hypothetical example might be that of providing platform independence.  This is a command line parser; if the parser can be called on Windows or Unix systems, passing a first-class function to the constructor allows the initialization to detect the platform, and adjust the parser settings based on which platform it is running on.

Further Reading

Open-Closed Principle

Inversion of Control


答:
I would recommend to use a common error code file, exactly like @GlenH7, but I would also recommend to write self-contained functions or modules which don't need the global error file at all. For example, if a `connect´ function can just fail (or not), return a boolean indicator. The caller of that function may decide to map the boolean return value to a global constant, but not the connect function itself:

```<code>  success = connect(parameters);
  if(!success)
      return INVALID_CONNECTION;

  success = check_password(paramaters);
  if(!success)
      return BAD_PASSWORD;

  //...
  return SUCCESS;
</code>```

For bigger software consisting of many different modules or libs, maybe developed by different teams, it is often better to avoid any global error codes at all, and instead use only local per-module or per-library error codes. To distingiush those, for example, in a central log file, you always have to add the module name or some kind of module ID to the error code. You can enforce the usage of these two values by designing your logger API right that way - with a "log" function expecting a module ID and an error code as parameters, not just one error code.  If you really have to pass the error codes around your program in a globally distinguishable manner, you may create a struct "ErrorCode", with two attributes "ModuleID" and "LocalErrorCode". That way you can avoid the need for having global error codes at all.

Title: Defining error codes

Body:
We are designing an error-handling framework for a cryptographic library written in C.

The approach we are taking is that relatively few errors are propagated back to the user since on most occasions he cannot do anything about them (notable exception: parameter validation errors. Of course we tell the user if a call succeeded. We'd also create log entries for fault investigation.) In short, just because we have an error condition somewhere inside the library it does not mean that we need a public (user-facing) error code for it.

Also, from past experience we think that a significant portion of error conditions that require error codes pertain to very narrow areas of code, it is often the case that a particular error is only returned from (or set by) one function.

Therefore we would like to define error codes at the lowest possible level. For example, if only one function can return/set a particular error code we would define that code in the .h file where the function prototype is declared.

However, in such case we might get error code conflicts - the same error code value for different errors. Can someone please propose an elegant approach to avoid such conflicts? Or at the very least an automated mechanism to check for such conflicts (which can then be fixed by hand)?

Body:
I would recommend to use a common error code file, exactly like @GlenH7, but I would also recommend to write self-contained functions or modules which don't need the global error file at all. For example, if a `connect´ function can just fail (or not), return a boolean indicator. The caller of that function may decide to map the boolean return value to a global constant, but not the connect function itself:

  success = connect(parameters);
  if(!success)
      return INVALID_CONNECTION;

  success = check_password(paramaters);
  if(!success)
      return BAD_PASSWORD;

  //...
  return SUCCESS;

For bigger software consisting of many different modules or libs, maybe developed by different teams, it is often better to avoid any global error codes at all, and instead use only local per-module or per-library error codes. To distingiush those, for example, in a central log file, you always have to add the module name or some kind of module ID to the error code. You can enforce the usage of these two values by designing your logger API right that way - with a "log" function expecting a module ID and an error code as parameters, not just one error code.  If you really have to pass the error codes around your program in a globally distinguishable manner, you may create a struct "ErrorCode", with two attributes "ModuleID" and "LocalErrorCode". That way you can avoid the need for having global error codes at all.


答:
Instead of having to provide a full configuration, the caller has the option of modifying a given configuration. He might decide to just tweak the existing configuration.

```<code>var parser = new Parser( s => {
    s.IgnoreUnknownArguments = s.IgnoreUnknownArguments || s.CaseSensitive;
} );
</code>```

The delegate could be stored by the Parser and be called again whenever changes are made to the configuration.

Title: What is the benefit of passing a delegate to the constructor instead of just having the client code create and pass the ParserSettings?

Body:
When answering a question on Stack Overflow, the library appeared to have a weird way to specify configuration, through an Action passed to the constructor:

```<code>public Parser(Action<ParserSettings> configuration)
{
    if (configuration == null) throw new ArgumentNullException("configuration");
    this.settings = new ParserSettings();
    configuration(this.settings);
    this.settings.Consumed = true;
}

internal Parser(ParserSettings settings)
{
    this.settings = settings;
    this.settings.Consumed = true;
}
</code>```

So to specify the settings you provide a Action<ParserSettings> that modifies the settings:

```<code>var parser = new Parser( s => { s.CaseSensitive = false; } );
</code>```

I don't understand what this pattern accomplishes. What is the benefit of passing a delegate to the constructor instead of just having the client code create and pass the ParserSettings to the constructor?

Body:
Instead of having to provide a full configuration, the caller has the option of modifying a given configuration. He might decide to just tweak the existing configuration.

var parser = new Parser( s => {
    s.IgnoreUnknownArguments = s.IgnoreUnknownArguments || s.CaseSensitive;
} );

The delegate could be stored by the Parser and be called again whenever changes are made to the configuration.


问:
Version control workflow for semi-bespoke software
I have a web app product (PHP, MySQL) for which I offer a bespoking service. That is, you can buy the main product, which is quite extensive, and then have it customised however you like. This might include new features, adjusting fundamentally how existing features work, disabling features, making changes which require a different database schema, etc.

I want to find a sensible way of managing a large number of different releases of the product in version control such that I can make changes to the core and pull changes out to the releases as required, and also make changes to a release independently. Sometimes I might want to pull a change from release back into the core.

My instinct was to use Git, and have the releases as branches. It is possible to pick specific commits to merge back into the trunk, so I think this could work.

However everywhere I have looked suggests that it is a bad idea to have permanently separate code in branches. The suggestion is to use a single codebase and have all the differences in features configurable, so that each release can behave separately. This sounds fine for software which is sold in multiple editions, which have different features enabled, but I think it would be a complete mess for my software.

I'm looking for a good development workflow for a setup like this, which may or may not be based on version control.

答:
Create one massive application with features being something you can turn on and off using configuration files or database settings. The display of the site, and the processing of user requests just becomes a matter of permissions management within the larger system. You'd have two basic levels of permissions:

Package Settings - This is where you can turn features on or off depending on how much money the client forks over

User Roles - This is subservient to Package Settings, and is where you define a "role" for a person (for example, an "Editor" vs a "Writer" vs an "Administrator"). "Writers" can create and edit content. "Editors" can publish it. "Administrators" can change settings.

Each feature should be its own "module". Every module could have one or more roles associated with it. For example, having a shopping cart module might not need an "Editor", but a "Product Manager" might be just the ticket.

Keeping this information in a database and creating a management system for these permissions would give you tons of flexibility for repackaging this software in the future. During the Great Recession, many companies saw their existing product offerings get rejected for cheaper alternatives. The companies that survived took the same features and repackaged them in different combinations to bring the cost down.

You should bear this in mind. If your market's price point suddenly shifts up or down, you should be able to easily repackage your software to take advantage of the price shift (or just survive and pay the bills until things improve).


答:
Having branches for different version can work.

I think the main chore is keeping branch version up-to-date.  So this approach suggest frequent merging/rebasing of changes in master and version branches to keep them up-to-date as required.

Title: Version control workflow for semi-bespoke software

Body:
I have a web app product (PHP, MySQL) for which I offer a bespoking service. That is, you can buy the main product, which is quite extensive, and then have it customised however you like. This might include new features, adjusting fundamentally how existing features work, disabling features, making changes which require a different database schema, etc.

I want to find a sensible way of managing a large number of different releases of the product in version control such that I can make changes to the core and pull changes out to the releases as required, and also make changes to a release independently. Sometimes I might want to pull a change from release back into the core.

My instinct was to use Git, and have the releases as branches. It is possible to pick specific commits to merge back into the trunk, so I think this could work.

However everywhere I have looked suggests that it is a bad idea to have permanently separate code in branches. The suggestion is to use a single codebase and have all the differences in features configurable, so that each release can behave separately. This sounds fine for software which is sold in multiple editions, which have different features enabled, but I think it would be a complete mess for my software.

I'm looking for a good development workflow for a setup like this, which may or may not be based on version control.


答:
When you have mentored many, and most thanked you for it years later after disagreeing with you at first, feel free to append 'Senior' to any title that you may command.

Until then, 'lead' is probably a more descriptive term.

To me, the term 'senior' denotes a culmination of practical experience AND wisdom when dealing with people and their arbitrary expectations. Take this scenario into consideration:

16 programmers on a team, each with exactly 1 year more experience than the rest. This means, the 16'th programmer has 16+ years of experience. Eight of the most experienced members are tragically killed when a bus slams into a store. Would the guy with half the experience now be considered a senior developer? I'd hope not, I'd hope the company quickly replaces the voids with people of equal or more caliber than they just lost.

I hate to bring the term 'journeyman' into programming, but some of it applies. The term 'senior' isn't something I'd hand to anyone with less than 15 years experience, because it goes way beyond technical knowledge.


问:
What should I expect from a developers guide?
I'm willing, with some friends, to make a developers guide for an open source point of sale written in Java.

The thing is I have never written anyone and so I don't know exactly what to put in there to meet standards. I'm thinking about putting UML, and using Java doc but still I don't know what are the expectations of developers towards a developers guide.

How can we say a developer's guide is truly worth?

答:
I would put in such a guide an architecture overview, and coding rules (like these). Some building instructions (like this), some "contribute how-to" (like this).

I gave an example thru links related to GCC to explain what I mean. I don't claim it is the best example.

I'm not sure that UML will bring a lot (and then you should have to maintain the UML).

Particularily if your software is a library or is extensible via plugins, give some code examples (how to use that library, or of a typical plugin).

The most important is to stay in sync with the code base.


答:
A good developer's guide should be able to guide developers who want to use your product/library.

It should give them an overview of what the product/library is.

It should have an overview of any special concepts necessary to use it. For example, if you have a library creates formatted documents of a very specific type, an overview of the document structure might be a good idea. If it's a graphics rendering library, an overview of the rendering pipeline would be useful.

It should contain a complete listing of all public components (classes, functions, whatever) that a developer could use. Javadoc can probably generate all of this.

Examples of common uses of programming with the product are also very good to have, including working code examples.

Special instructions for setup/getting started with development.

One way to think about it might be to put yourself in your target users' shoes and ask yourself what you would want to see if you knew nothing about this product, and suddenly had to write code for it.

Title: What should I expect from a developers guide?

Body:
I'm willing, with some friends, to make a developers guide for an open source point of sale written in Java.

The thing is I have never written anyone and so I don't know exactly what to put in there to meet standards. I'm thinking about putting UML, and using Java doc but still I don't know what are the expectations of developers towards a developers guide.

How can we say a developer's guide is truly worth?


问:
Could the creation of many methods in Java affect performance?
I was told by a colleague that in Java, the performance may be worse if we create more methods, stacking many methods calling over them in JVM, specially in a Java EE environment.

This seems to somewhat defeat the concept of object oriented programming. Like if we write long methods - what isn't good for code readability - we can achieve more performance due to less methods in JVM stack.

So, write many methods who call and interact with each other is worse to performance than write a few long methods to use less stacks in JVM? Is this is a correct affirmation?

答:
It's probabbly an wrong assumption, first as common sense nested calls shouldn't have any (measurable) performance hit at all. After doing some research you'll find that the JVM can do some optimizations in your code "automagically":

Adaptive Optimization

And more importantly:

Inline Expansion

As you can see:

In computing, inline expansion, or inlining, is a manual or compiler
  optimization that replaces a function call site with the body of the
  callee

So probabbly, if you as programmer can say "hey, one big method is better than nesting tons of other methods", the JIT/JVM/javac can figure that for you and fix it >>IF<< it's worth.

I think that unless you get some numeric statistics, you are fine with tons of methods instead a monolithic piece of software.


答:
The JVM have this thing called JIT, which would optimize the application's code with various techniques.

One of those is called "inline optimization". In this particular optimization, the JIT will automatically inline methods when needed, so, you might lost some processor cycles in this particular instant, even if it does, it's not sufficient to justify this kind of argument in my opinion.

It's always nice to remember that usually the performance hotspots are the I/O and database access. Also nice to remember that, nowadays, machine time is cheap and developer's time are expensive.

Further reading:

http://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/geninfo/diagnos/underst_jit.html

https://stackoverflow.com/questions/6495030/java-how-expensive-is-a-method-call

http://java.dzone.com/articles/how-expensive-method-call-java

Title: Could the creation of many methods in Java affect performance?

Body:
I was told by a colleague that in Java, the performance may be worse if we create more methods, stacking many methods calling over them in JVM, specially in a Java EE environment.

This seems to somewhat defeat the concept of object oriented programming. Like if we write long methods - what isn't good for code readability - we can achieve more performance due to less methods in JVM stack.

So, write many methods who call and interact with each other is worse to performance than write a few long methods to use less stacks in JVM? Is this is a correct affirmation?


问:
Where should user permission checks take place in and MVC and by who?
Should user permission checks take place in the model or the controller? And who should handle the permission checks, the User object or some UserManagement helper?

Where should it happen?

Checking in the Controller:

```<code>class MyController {
  void performSomeAction() {
    if (user.hasRightPermissions()) {
      model.someAction();
    }
  }
  ...
</code>```

Having the checks in the Controller helps making the Models simple actions, so we can keep all logic to the Controllers.

Checking in the Model:

```<code>class MyModel {
  void someAction() {
    if (user.hasRightPermissions()) {
      ...
    }
  }
  ...
</code>```

By putting the checks in the Model, we complicate the Model, but also make sure we don't accidentally allow users to do stuff they aren't supposed to in the Controller.

And by who?

Once we've settled on the place, who should do the checks? The user?

```<code>Class User {
  bool hasPermissions(int permissionMask) {
    ...
  }
  ...
</code>```

But it's not really the user's responsibility to know what he or she can acccess, so perhaps some helper class?

```<code>Class UserManagement {
  bool hasPermissions(User user, int permissionMask) {
    ...
  }
  ...
</code>```

I know it's common to ask just a single question in, well, a question, but I think these can be answered nicely together.

答:
In both Model and View

In the View - because the UI should not show the UI-elements that are restricted to the current user

(like, say, the "Delete" button should be shown to people with appropriate permissions)

In the Model - because your app probably has some kind of API, right? The API has to check permissions as well and probably re-uses the Model.

(like, say, you have the "Delete" button in the UI and the "http:/server/API/DeleteEntry/123" API method at the same time


答:
The entire industry is looking for a good workflow for this. You have stumbled on a very common problem that most of systems design has been trying to solve for decades. How do you customize software without writing a whole thing from scratch each time?

Unfortunately, you've chosen php, which isn't very well-designed, so it won't have a lot of features to help you keep everything organized and abstracted out to the proper level of abstraction for each purpose. I will give you some general-purpose advice gathered from a couple of decades spent trying to solve this problem.

Set firm boundaries. It's OK that your software isn't infinitely customizable. Infinitely customizable systems are also known as "development systems" which is what you yourself will be using to write your software: PHP, etc. Take it too far and you'll end up re-inventing the system you're using to write the system in the first place.

Not everything has to be stored as a database setting. It's ok to offer customizations as files, like .css files or a set of module files in php dropped into a folder. You can also "hard code" your changes too.

Don't use if-then statements with clientId or customerName to decide on what to do inside your software. Allow for file system directories or database values to key into the customer name, not control-of-flow statements.

Most of the changes clients want will be in the UI, be it web pages or email messaging. Make those parts of the system easiest to change and count on making custom ones for each customer.

Don't be afraid to white-label service offerings like Wordpress, MailChimp and the like. They have already made their systems multi-tenant, saving you time.

Good luck!


答:
From your object-model I conclude, that you have at least two distinct ressources:

users

groups

So there are two base-URLs:

(1)/api/users/ and (2)/api/groups/

(1) offers:

/api/users/ GET show all users available Response: the representation of all users

/api/users/?group=someGroup GET show all users which are members of someGroup available Response: the representation of all users of the group

/api/users/{id} GET to show individual user Response: the representation of one user

/api/users/{id}/groups GET to show individual user's groups Response: the representation of one user's groups

/api/users/ POST to create a new user Response: the URI of the new user

/api/users/{id} PUT/PATCH to update an existing user Response: No content

/api/users/{id} DELETE to delete an individual user Response: No content

(2) offers:

/api/groups/ GET show all groups available Response: the representation of all groups

/api/groups/{id} GET to show individual group Response: the representation of one group

/api/groups/{id}/members GET to show individual group's members Response: the representation of one group's member

/api/groups/ POST to create a new group Response: the URI of the new group

/api/groups/{id} PUT/PATCH to update an existing group Response: No content

/api/groups/{id} DELETE to delete an individual group Response: No content

Usually you respond to every request, if not otherwise advised, with 200 OK.

Imagine that I'm a group owner and I am the only one that can add new users to that group

This doesn't matter for your API. That a user is allowed to do something or not is a secondary problem. If you want to add a user to a group, your API could provide either one (or both) of the two ways

/api/groups/{id}/members PUT/PATCH Add group members

/api/users/{id} PUT/PATCH update single user

If a user isn't allowed to do the chosen action, the server should respond with 403 Forbidden

Because I need to pass the ID for the user that is modifying the group. If the user is the owner, he can add more members to the group.

Since the user is logged in, you have his ID. You could easily save this along with the updated information.