问:
Suggestions needed for calculating efficiency of a task based project
I will be soon taking over management of a 10 member team. I will continue to code myself to another project and generally be available for the team
for any issues surrounding processes or escalations. I will also be responsible for code review of some of the tasks.

For some context, the team does development work on task basis. We typically get a task from a Customer Relationship Manager for, let say, a report request.
This will involve fair bit of coding in SQL and some wrapper code on top of it. The challenging part here to write the SQL, unit test, perform code review, and
then send it for testing.

We have a turn around time of 15 days for every request. 15 days include, time for estimate (1 day always), coding (including peer code review and change cycle),
and QA, patch to production on a daily build.

With this in mind, I would like to come up with a metric called "Efficiency" of the queue.

What typically happens is, when a task comes in from the CRM,
it needs to be estimated for coding effort. Once the estimate is approved (1 day max) it moves to the coding / development step.

Now, developers in my team have the habit of picking tasks as they come and typically each one has 3-4 tasks in his/her queue. This sometimes leads to a situation
where a task, though simple, sits in his / her queue in a wait state. At the same time, some of the other developers may have completed their tasks and might be waiting for another. By habit, the developer who originally picked the task doesn't let it go off his / her queue. It's not a bad thing, as we have always been able to adhere to the 15 day TAT.

However, I'm looking at ways to organizing this queue so that we avoid the unnecessary wait time and thereby increase the efficiency of the queue. This will also lead
to a gradual reduction of the TAT from 15 days to say, 12 days.

How can I calculate the efficiency of the queue?

I can fetch reports around the start and end times of each stage like: Estimate, code, code review, QA, recode (if any bugs, or customer is not happy, or change or requirements).

It would be good to handle this efficiency calculation with as much less human intervention as possible, as it would have less confusion and it will also be transparent process to anyone in management to understand the metric.

Any thoughts or suggestions from anyone of you here?

Thanks in advance.

答:
How can I calculate the efficiency of the queue?

The only queue that you mention are the individual queues of developers. Those queues are something to control, rather than something to measure. You need to restrict the number of tasks that a developer is allowed to "pick up" and add to their queue. If you want to measure something, you could measure:

Turn Around Time for each task. (recorded at task completion)

Queue size, for each developer. (recorded each time a task is completed, or added to the queue)

Tracking queue size will allow you to identify how often developers are adding more than your recommended number of task to their queue. It will also allow you to identify how often a developer's queue goes to 0, while someone else's is greater than 1. (which seems to be the main problem, from what you describe.)

If you want a simple metric from this, it might something like: "For how many person-hours, during the reporting period, did some queues equal zero while another queue was greater than one?" (having actual data and an SQL statement would be more explicit than this plain-English... but I think you get the idea.) The bigger this number... the less efficient the process.


问:
Is it good that testers are competing to see who opens more bugs?
I'm a software developer. There is a team of testers who follow and run test cases written by the analyst, but also perform exploratory testing. It seems like the testers have been competing to see who opens more bugs, and I've noticed that the quality of bug reports has decreased. Instead of testing functionality and reporting bugs related to the operation of the software, the testers have been submitting bugs about screen enhancements, usability, or stupid bugs.

Is this good for the project? If not, how can I (as a software developer), try to change the thinking and attitudes of the team of testers?

Another problem is because the deadline is estimated and cannot change, so as the deadline nears, the testers will be scrambling to finish their test cases, and this will cause the quality of the tests decrease. This will cause legitimate bugs to be in the final product received by the client.

OBS: This competition is not a practice of the company! It is a competition between only the testers organized by them, and without any prizes.

答:
Is this good for the project?

No. You have pointed out, yourself, that you have observed that it results in low-quality reports that are not targeted at required functionality, and that the testers end up, to compound the problem, scrambling to complete the work that they are actually "supposed" to be doing.

If not, how can I (as a software developer), try to change the
  thinking and attitudes of the team of testers?

Raise the issue with your Project Manager. They should consider this sort of thing to be part of their job. If your PM is unwilling or incapable of dealing with it, you are sort of stuck developing your own coping strategies. (which would be a different question)

ContentLicense: CC BY-SA 3.0


问:
Is REST only limited to optimistic concurrency control?

Context

Due to the statelessness of the REST architectural style involving that each requests stands completely alone, leading server to never store any informations about client.

Thus, pessimistic concurrency control are not suitable because it would requires that server store which client gets the lock on a resource.
Optimistic concurrency control are then used, with the help of Etag header. (btw, as I asked there https://stackoverflow.com/questions/30080634/concurrency-in-a-rest-api)

Problem

The main problem with an optimistic concurrency control mechanism is that you allow all the time, all clients, to perform any operations.

And i would like to avoid that without breaking the statelessness principle of REST. I mean that all clients cannot perform any operation at any time.

Question

In my mind, it would possible with a semi-optimistic concurrency control mechanism, like that:

Clients can request a token

Only one token can be generated and has a limited period of validity

To perform operations on resources (such as POST or PUT), client must give this token as part of the body (or header?) of the request. Client that don't have the token cannot do these operations.

It is very similar to optimistic concurrency control, except that only one client can do some operations (the one that got the token)... at the opposite of "all clients can do all operations".

Does this mechanism is compatible with a REST architectural style ? Does it break any of its constraint ?
I was thinking to ask on SO, but this seems more an high-level question, related to software design.

答:
REST alone is too primitive, really.  You can get started with REST, but eventually, your rich application will need queries with joins and updates with transactions.  Every developer attempting to add these things on their own would be error prone and inconsistent.  Fortunately, there's an emerging standard called OData that does just that.  It layers on top of REST and provides (1) query language that allows for simple joins using navigational properties (without having to expose foreign keys), and, (2) batch processing that includes atomic change sets.

See here for (1) https://stackoverflow.com/a/3921423/471129 , and,

See here and for (2) https://stackoverflow.com/a/21939972/471129


问:
How to plan your software project if you are work depend on required deliverable with unexpected delivery date
I have worked for many software projects where I am developing software solution to the customer where I need to integrate with the customer back-end using web service provided by the customer in order to retrieve information, etc...

The problem is the customer might not deliver the required web service on time. Or might deliver web service in a different sequence than the plan.

My question is how to plan the project so that my coding and implementation will start according to the delivered required web services? Should I consider using agile? an how to use it in that case?

And how to deal with the risk of the delaying from customer?

The solution can be divided into phases and might be delivered based on the readiness of the web service.

Suppose I require 16 web service. If the customer deliver three now  I can implement part of the project and go live with it. After if customer develop another two web service I can be ready to implement another part of the project. and so on
How to put that in the plan structure ?

答:
...how to plan the project so that my coding and implementation will start according to the delivered required web services?

It sounds like you already do such planning, but that the customer sometimes delivers late or out of sequence.

Should I consider using agile?

Yes, you should consider "using agile". Whether or not you actually chose to adopt agile practices, or a Scrum specifically, should depend on your careful consideration of your circumstances... and not just the problem you have described here.

...how to use it in that case?

and

...how to deal with the risk of the delaying from customer?

Here, it would be easier to answer for the case of a particular method, like Scrum, rather than agile principles more generally.

With Scrum, the aim it to deliver high quality increments of a deliverable solution. Scrum gives priority to the quality of the deliverable, rather than its timeliness. With Scrum, essentially, the risk, and consequence, of delays is accepted. The customer, and their team delivering the component you depend on, after all, should be part of the Scrum team.


问:
What is the actual value of a consistent code style
I am part of a consultant team implementing a new solution for a customer. I am
responsible for the majority of code reviews on the client-side codebase (React and javascript).

I have noticed that some team members use unique coding patterns to a point that I could pick a file at random at tell who was the author from the style alone.

Example 1 (one-off inline functions)

```<code>React.createClass({
  render: function () {
    var someFunc = function () {
      ...
      return someValue;
    };
    return <div>{someFunc()}</div>
  }
});
</code>```

The author argues that by assigning a meaningful name to someFunc the code will be easier to read. I believe that by inlining the function and adding a comment instead the same effect could be achieved.

Example 2 (unbound functions)

```<code>function renderSomePart(props, state) {
    return (
      <div>
        <p>{props.myProp}</p>
        <p>{state.myState}</p>
      </div>
    );
}

React.createClass({
  render: function () {
    return <div>{renderSomePart(this.props, this.state)}</div>;
  }
});
</code>```

This is how we usually do it (avoids having to pass state and props):

```<code>React.createClass({
  renderSomePart: function () {
    return (
      <div>
        <p>{this.props.myProp}</p>
        <p>{this.state.myState}</p>
      </div>
    );
  },
  render: function () {
    return <div>{this.renderSomePart()}</div>;
  }
});
</code>```

While these coding patterns are technically correct they are not consistent with the rest of the codebase nor with the style and patterns that Facebook (the author of React) hints at in tutorials and examples.

We need to keep a fast pace in order to deliver on time and I don't want to burden the team unnecessarily. At the same time we need to be on a reasonable quality level.

I am trying to imagine myself as the customers' maintenance developer faced with inconsistencies like these (every component might require you to understand another way of doing the same thing).

Question:

What is the value as perceived by the customer and its maintenance developers of a consistent code base vs. allowing inconsistencies like these to remain and potentially spread?

答:
As several others have pointed out, when the maintenance developers have to go behind you, a section of code in a different style is going to cause them to stop and try to figure out what is special about that section.  There's also the very real risk of the inconsistent style getting propagated to other sections, resulting in a huge mess later.

I get the impression that, deep down, you already know the answer to this question, and you wouldn't even be facing it if it weren't for this:

We need to keep a fast pace in order to deliver on time and I don't want to burden the team unnecessarily.

This always seems to be the universal trade-off... doing it quick vs doing it right.  Only you can evaluate the consequences of sacrificing good coding practices on the alter of customer deadlines. However, I have to agree with JeffO when he observes that following a (possibly unusual or counter-intuitive) coding style shouldn't slow down your team so drastically that the deadlines slip significantly.

Although I've known about the concept for years, I only recently learned the term "technical debt." You really need to consider the technical debt that will ultimately have to be paid if you don't follow a disciplined style now.

Unfortunately, as eBusiness stated, unless your customer is particularly technically savvy or is going to be maintaining the code themselves afterward, it's hard for them to appreciate the value of consistent coding standards.  However, any reasonable businessman should be able to grasp the concept that "a bit of preventative maintenance now" (in the form of good coding) "will help avoid significant repair costs later" (in the form of wasted developer time later cleaning up the mess).


问:
What's the etiquette of contributing to OSS that doesn't have a Contributing page
I'm thinking about contributing to a small R package on github that has only 1 contributor. What's the standard etiquette when there's not Contributing.md page on small projects like this?

Should I email him about whether my feature is wanted? Or just clone and then issue a pull request?

答: You can fork the project on github and then make a single commit with your change. Then you can open an issue in the project repository and provide a link to the commit and ask if (s)he would like you to make a PR.  Try to follow any code style being used and use travis etc if the project is. It is always good to include a test if appropriate.</p>


问:
ScrumMaster rotation with multiple scrum masters and teams
I'm currently working in a project where we discuss the question whether it is a good idea or not to rotate the scrum masters through all teams.

We have different teams for ONE project. The context where they work in is the same. They only switch teams for a couple of weeks. We hope to benefit from each ScrumMaster as they have new influences on other teams and maybe can resolve problems others couldn't.

In detail we want each scrum master to assist every team for a couple of weeks. I didn't find any literature about that topic, but only about rotating the scrum master role in a team.

Is this is a good/bad idea?

答:
This could be a beneficial practice if the "rotation" is done in the form of one Scrum Master "shadowing" another, rather than attempting to take over. In that fashion, the "new influences" you spoke of could be shared without the inefficiency of an actual hand-over of responsibility.

Practically speaking, this might be accomplished, for example, by a pair of SMs attending each-other's meetings, as guests, for a sprint... as long as they are at different times, of course. It will be up to you to decide if any extra time taken in accomplishing such a "rotation" justifies any benefits that accrue to the Scrum Masters and Scrum Teams involved.


问:
Early subtasking at the beginning of each sprint
I have joined a new team which is using Agile/Scrum, and their development process is as follows:

1) developers review each story before each sprint to make sure it doesn't miss anything critical. There's a formal state for that in the workflow.

2) during the Sprint kickoff, the entire team does an estimation (poker planning) on how many story points each story would cost.

3) finally, immediately after each sprint starts, each developer is required to eagerly break down all of assigned stories into subtasks with time estimates (as opposed to subtasking before starting each story).

The main argument for the last step is that it helps to discover if implementing a story would take longer than anticipated and warn scrum master about potential risks of missing sprint deadlines.

Yet I find this counter-productive, mainly because of the following reasons:

if the aim is to provide rough estimate, story points (step #2) is what does the job. Otherwise why bother with story points at all? - just do subtasking early on.

if the aim is to provide accurate estimates, then this is a clear example of what is described in Human Task Switches Considered Harmful. This, I think, is especially the case for fresh developers who join existing teams in big projects where understanding what needs to be done can take up to 50% of the time. You are required to get into details of story #1, then story #2, #3, etc. etc. which yields a lot of information churn.

I am also being told that such practice is "by the book" and I'm not even meant to discuss this. Can anyone provide a reference to such practice - whether this is clearly defined in Scrum bibles, and/or perhaps provide any extra insight?

答:
At some point during each Sprint, you should have a Product Backlog Refinement Meeting. At this meeting, you ensure that the top portion of the Product Backlog is broken down sufficiently for items in that portion to be added to the next Sprint Backlog.

If Product Backlog Refinement is managed well, then the Sprint Planning Meeting can be more efficient. Ideally, this would obviate the need for developers to "eagerly break down" stories after the Sprint starts.

If Product Backlog Items are added to the Sprint Backlog before being sufficiently broken down to estimate realistically, that will make it difficult to make good decisions about what to add to the Sprint.


问:
Do objects in OOP have to represent an entity?
Does an object have to represent an entity?

By an entity I mean something like a Product, Motor, a ParkingLot etc, a physical, or even a clear-cut non-physical conceptual object -- something that is well defined, with some core data clearly belonging to the object, and some functions/methods that clearly operate on the core data.

For example, I can have an object of a Demon, an entity in itself, an imaginary one perhaps and not physical but an entity nevertheless

Can an object be just a collection of methods, a common set of procedures that tie in with a common goal?

Example:  can a class be called MotorOperations or MotorActions, where there is no entity, but methods inside the class do things like

getMotorDataFromHTMLForm()

getMotorManufacturers()

selectMotorFromUserRequirements($requirements)

canMotorCanHandleOperatingConditions($conditions)

computePowerConsumptionForMotor($id)

A class is typically defined as data central to the object + operations on data.  So for a Motor there may be some motor variables relating to motor specifications, and there can be operations that combine those data to produce something.

In my case it is more like I have a class with operations on data + data that is passed through the class, there is no data centric to "Motor Operations", other than temporary pass-through-the-class data.

Question

Can classes represent entity-less objects?
If not, why they are bad/incomplete/non-OOP-centric?  Are there ways they need to be changed/improved conceptually to be in line with OOP?

答:
No, a class merely represents something that can be instantiated, has members, and can be inherited from.

In fact, your language may have static classes, which are not even instantiated more than once.

.NET's Math is a great example of a "professional" class that represent no entity (unless you want to get philosophical about what math is...), and also happens to illustrate a legitimate use case of such a class. It has only methods and 2 fields (both representing individual constants).

The class hierarchy of a similar library, Math.Net, groups mathematical/numerical methods into classes by type. Here classes represent not an entity, but a logical category.

I myself often end up creating (static) classes which are nothing more than a bag of related (static) functions, or a bunch of constants conveniently grouped in one central place. I wouldn't claim that this is good design, but sometimes it's the most straightforward solution.


问:
In Agile, what do you do with a severly underpointed story?
Our team is pretty good at planning/pointing, but once in a blue moon, we will have a severely underpointed story. I'm talking something we thought it would take a couple days and we realize its going to take the whole sprint. What is the recommended approach to fix this when we realize our error so that it doesn't make our velocity unusable for the next sprint planning?</p>

答:
What is the recommended approach to fix this when we realize our error

Estimates are estimates. I would not view it as something to be fixed, when it happens. I would view it as an opportunity to diagnose the reasons and improve your future estimates. Since the aim of Scrum is high quality increments of deliverable product, you want to stop and assess what is the best quality increment you are capable of delivering that Sprint, given that you now realize that you initially "bit off more than you could chew".

...so that it doesn't make our velocity unusable for the next sprint planning?

You don't need to be a slave to your method of calculating velocity. You could, for example, chose to consider the data from the current Sprint to be an "outlier", and not use it in your calculation (which I presume is some kind of rolling-average of the past few sprints). Beware, however, that if you find yourself wanting to ignore the current sprint's effect on velocity often... then you might be over-estimating your velocity.


问:
How do we finish all our stories by the end of the sprint and not after and why is this important?
We are running 2 weeks sprints where the team will just barely finish development by the last day of the sprint but cards are not complete because testing is not finished.  The definition of done is really "when development is complete" rather than "when the stories are complete."  We have a 1 week delay between the last day of the sprint and the release date.  The team does finish the sprint by the release date but that seems like that isn't quite meeting the objective of scrum.  The team starts the next sprint the day after the previous sprint ends.

I see the following problems:

team is not using whole team testing

team is not too interested in pair programming or piling on one card at a time.

Maybe the stories are too large and we should break them down more so that we finish at a more steady pace throughout the sprint?

Any suggestions on how we get the team bought in to finishing the sprint by the end date? Or other ideas?

Why do we think it is important to finish by the last day? Why does it matter if the team is still finishing by the release date? (I have my own answers but am curious what others think here.)

答:
Any suggestions on how we get the team bought in to finishing the sprint by the end date?

Strictly speaking, the Sprint is finished by the end date, whether the Sprint Team has completed all the Sprint Backlog items or not. You don't need "buy-in" to finish the Sprint on time... You need "buy-in" to actually follow Scrum.

Why do we think it is important to finish by the last day?

Why does it matter if the team is still finishing by the release date?

Another part of Scrum is your "definition of 'done'". The definition of "done" that you have chosen (development complete, but not testing, etc) does not allow you to achieve the main goal of Scrum ..."a high quality increment of a deliverable product".


问:
Why do we use the word "sprint"?
One of the founding principles of the Agile Manifesto is

Agile processes promote sustainable development.  The sponsors,
  developers, and users should be able  to maintain a constant pace
  indefinitely.

Scrum teams use the term sprint to refer to a work cycle (also known as an iteration).

However this doesn't make sense to me. According to Google a sprint is:

run at full speed over a short distance.

In other words it's not sustainable. Why do Scrum teams use the word sprint? It appears to me to conflict one of the basic principles of Agile.

答:
The sponsors, developers, and users should be able to maintain a constant pace indefinitely.

A sprint means... run at full speed over a short distance.

Using the term sprint is still compatible with the (Agile) ability to maintain a constant pace.

A whole group maintaining a constant pace does not necessarily mean that they are all moving at the same speed at any given moment. Consider, for example, that a relay team might run at a constant pace, collectively, while, individually, they may be either: sprinting, waiting, or recovering.

Title: Why do we use the word "sprint"?


问:
When to Assign the Scrum Tasks
Our Scrum Scenario:

We have two Sprint Planning Meetings (Part 1 and Part 2).

Part 1: What should be done during the Sprint?

Part 2: How should these things be done?

I guess there are some differences in how this is handled. This is according to Boris Gloger's German book. In practice these things can be done on the same day or even during the same meeting.

Team Size:

Developer: 3

All of them have their strengths either in Backend or Frontend development

We would like to get all familiar with all the technologies used in the project. We do not like to have private kingdoms but have a constant discussion about how things can be done.

At which point in time should Tasks be assigned? Within the Scrum Process: Sprint Planning 1, 2, [...] Review Meeting, Retrospective Meeting, etc.?

Who is responsible for the assigning tasks? The Product Owner, the Scrum Master, the developers?

答:
At which point to the tasks get assigned?

Product backlog items are added to the sprint backlog by sprint team members during the sprint planning meeting, in order of priority (which is determined by the Product Owner)

What does that actually mean for the sprint 1 and 2 planning? (i.e. the what to do and how to do it topics of sprint planning)

The above applies to the first topic, "what to do".

Does that mean that we can start without task assignment and every developer starts on one end and then assigns a new tasks to himself when he finished the first one?

After the sprint backlog has been decided on, yes ...sprint team members complete an item and then pick another one from the top of the sprint backlog. (note: not out of the product backlog)

Title: When to Assign the Scrum Tasks


答:
The answers to your questions ultimately hinge on how precisely one defines terms like "class" and "entity." You did a good job of defining the latter, allowing both physical and conceptual entities. But the term "class" to purists will always be "a factory for instantiating objects with a particular internal representation" and to pragmatists the term will encompass those Java or C++ things despised by purists. Ditto for the term "OOP," which pragmatists might say Java and C++ do, but which purists would take to mean what Alan Kay meant when he remarked ["I invented the term object-oriented, and I can tell you I didn't have C++ in mind"](
So what *did* Alan Kay really mean by the term "object-oriented"?).

If you take the pragmatist view, you can accept your instance-less utility classes. But the purist view is more interesting. OOP, according to Kay, was always more about the messages than the classes. So to your questions:

Can classes represent entity-less objects?

No. Classes classify objects. Classes are by definition those entities to which you send a message such as new to produce an object. An object is an entity made from a class. Classes exist to manufacture, and indeed classify, objects. That's what classes do. Classes make objects. We use classes to classify objects. So if C is just a bundle of methods that does not permit instantiation or subclassing, there cannot be any objects classified by C, so C is not a class.

If not, why they are bad/incomplete/non-OOP-centric?

They're not bad. Just don't call them classes. A bundle of methods is OOPable: something you could send a message to in order to invoke a method, but it's not a class unless it can instantiate an object. Do you know Ruby? In Ruby a module is a bundle of methods. A class is a module that can instantiate objects. There is nothing bad about a module. But the thing that makes a class different from a module (in pure OOP terms) is that a class can have instances. A module is just some methods. The confusion is that C++ and Java and other languages use the term "class" for both class and module.

Now, to look at one of your specific examples, you ask about a MotorOperations class to which you could send the message computePowerConsumptionForMotor with argument id. Is that bad? At least it does not violate the Tell Don't Ask Principle. Do we have to make a motor class and send it the powerConsumption message? Maybe not 100% of the time, but maybe trying to do such things will lead to some nice insights about your code. Or, it can lead to an explosion of little classes which would be bad.

Are there ways they need to be changed/improved conceptually to be in line with OOP?

If "doing OOP" is important to you, then you will want to look for ways to architect a system into components that communicate by sending messages to each other. That is just what OOP is, or at least what the coiner of the term had in mind. Utility classes are not OOP in this view. But to some people, they may be.

Trying to make an entire large system out of millions of living, breathing, objects, all instantiated from classes, may work for some projects. But if you find yourself creating artificial, wrong-sounding classes, then modules should be introduced. Try to emphasize classes, and use modules when instantiable classes would be ridiculous.

TL;DR - method bundles are not always bad. Try to use instantiable classes first. Fall back to "modules" only when needed.

Title: Do objects in OOP have to represent an entity?

Body:
Does an object have to represent an entity?

By an entity I mean something like a Product, Motor, a ParkingLot etc, a physical, or even a clear-cut non-physical conceptual object -- something that is well defined, with some core data clearly belonging to the object, and some functions/methods that clearly operate on the core data.

For example, I can have an object of a Demon, an entity in itself, an imaginary one perhaps and not physical but an entity nevertheless

Can an object be just a collection of methods, a common set of procedures that tie in with a common goal?

Example:  can a class be called MotorOperations or MotorActions, where there is no entity, but methods inside the class do things like

getMotorDataFromHTMLForm()

getMotorManufacturers()

selectMotorFromUserRequirements($requirements)

canMotorCanHandleOperatingConditions($conditions)

computePowerConsumptionForMotor($id)

A class is typically defined as data central to the object + operations on data.  So for a Motor there may be some motor variables relating to motor specifications, and there can be operations that combine those data to produce something.

In my case it is more like I have a class with operations on data + data that is passed through the class, there is no data centric to "Motor Operations", other than temporary pass-through-the-class data.

Question

Can classes represent entity-less objects?
If not, why they are bad/incomplete/non-OOP-centric?  Are there ways they need to be changed/improved conceptually to be in line with OOP?


问:
Using a rules engine to manage client and server side validation of business rules?
Has anyone managed to use a common rules system between their frontend and backend?

Similar to this question:
Managing client-side and server-side validations in one place, I'm trying to find a way to have consistent business rules applied on the front (JS) and back end (Java).  Unlike this question though, I'm not interested in a general cross-platform field validation system (I'm not out to validate the field length).

An example of a business rule can be something like:

If the user's age is under 18, then a parent's email is required.

In this case the nullability of a form field changes based on input from another part of the form.

So that the system would allow:

```<code>{"user":"Bob","age":33}

{"user":"Carol","age":15,"parent_email":"foo@bar.com"}
</code>```

But deny:

```<code>{"user":"Alice","age":16}
</code>```

A rules engine like Drools can create and apply business rules on the backend, but only in a JVM (or CLR).

The default solution seems to be having two different sets of rules which will never stay in sync and cause all kinds of validation problems and edge cases.

I'd love to hear some successes, failures, or better techniques for tackling this problem.

答:
This is related to constraint-programming. Prolog is an example of such a system. There exists javascript implementations of prolog http://yieldprolog.sourceforge.net/ . You could then make your prolog program and use it on both the server and client.

Another approach is having all the logic on the server side but expose it as an api which the client could then query using ajax. It would feel almost the same to the user with the exception of a possible small delay.


问:
Pattern to share fields in inheritance
I'm trying to figure out the best way to solve a design issue. I have to be able to clone (I'm cloning them to Apache HttpClient) different types of HttpServletRequest (POST, GET...) and then send them. I want a super class with the common logic and then some subclasses for each method.

```<code>public abstract class ClonedRequest {

public ClonedRequest() {
    // Common logic
    ...
}

public static ClonedRequest GET() {
    return new ClonedGetRequest();
}

public static ClonedRequest POST() {
    return new ClonedPostRequest();
}

public abstract ClonedRequest clone(HttpServletRequest request);

public abstract void send();

protected void send(HttpUriRequest clonedRequest) {
// Common logic
...
}
}

public class ClonedGetRequest extends ClonedRequest {

private HttpGet httpRequest;

public ClonedGetRequest() {
    this.httpRequest = new HttpGet();
}

@Override
public ClonedRequest clone(HttpServletRequest request) {
    ...
}

@Override
public void send() {
    super.send(httpRequest);
}
}

public class ClonedPostRequest extends ClonedRequest {

private HttpPost httpRequest;

public ClonedPostRequest() {
    this.httpRequest = new HttpPost();
}

@Override
public ClonedRequest clone(HttpServletRequest request) {
    ...
    cloneBody(request);
}

private void cloneBody(HttpServletRequest request) {
    StringBuilder sb = new StringBuilder("");
    BufferedReader br = request.getReader();
    String line = "";
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }
    br.close();
    httpRequest.setEntity(new StringEntity(sb.toString(), "UTF-8"));
}

@Override
public void send() {
    super.send(httpRequest);
}
}
</code>```

Both HttpGet and HttpPost inherit from HttpUriRequest. Instead of having them as instance variables in subclasses, I could declare protected HttUriRequest request in superclass so it wouldn't be necesary to pass the instances to the superclass method all the time for common logic (as in protected void send(HttpUriRequest clonedRequest)). The problem is in ClonedPostRequest. The line httpRequest.setEntity(new StringEntity(sb.toString(), "UTF-8")); needs an instance of HttpPost and HttpUriRequest needs to be casted to it. It might be ok if it's only one time, but if you have this issue on serveral points, it might clutter the code with so much casting.

So my question was if is there a common pattern to approach this kind of design.

答:
Three points:

The implementation of "parallel specialisation" is a classic problem in strictly-typed OO languages

I suspect your inheritance hierarchy of cloned requests is not the best way to model your problem anyway, but...

even if you really need such a hierarchy, there are ways to solve it, e.g. using generics in Java.

I suspect you are really only specialising on the actual activity of cloning, not general specialisation of sub-types of (cloned) requests: your class naming hints at that. So I would rather abstract a RequestCloner concept, using generics to fix the sub-type casting problem, e.g.:

```<code>interface RequestCloner<T extends HttpUriRequest> {
    public T clone(T request);
}

class GetCloner implements RequestCloner<HttpGet> {

    @Override
    public HttpGet clone(HttpGet request) {
        //How to clone a GET request
        //(no casting needed, the generic T is fixed to an HttpGet)
        ...
    }
}

class PostCloner implements RequestCloner<HttpPost> {

    @Override
    public HttpPost clone(HttpPost request) {
        //how to clone a POST request
        //(no casting needed, the generic T is fixed to an HttpPost)
    }
}
</code>```

Title: Pattern to share fields in inheritance

Body:
Three points:

The implementation of "parallel specialisation" is a classic problem in strictly-typed OO languages

I suspect your inheritance hierarchy of cloned requests is not the best way to model your problem anyway, but...

even if you really need such a hierarchy, there are ways to solve it, e.g. using generics in Java.

I suspect you are really only specialising on the actual activity of cloning, not general specialisation of sub-types of (cloned) requests: your class naming hints at that. So I would rather abstract a RequestCloner concept, using generics to fix the sub-type casting problem, e.g.:

interface RequestCloner<T extends HttpUriRequest> {
    public T clone(T request);
}

class GetCloner implements RequestCloner<HttpGet> {

    @Override
    public HttpGet clone(HttpGet request) {
        //How to clone a GET request
        //(no casting needed, the generic T is fixed to an HttpGet)
        ...
    }
}

class PostCloner implements RequestCloner<HttpPost> {

    @Override
    public HttpPost clone(HttpPost request) {
        //how to clone a POST request
        //(no casting needed, the generic T is fixed to an HttpPost)
    }
}


问:
Can static and dynamically typed languages be seen as different tools for different types of jobs?
Yes, similar questions have been asked but always with the aim of finding out 'which one is better.'

I'm asking because I came up as a dev primarily in JavaScript and don't really have any extensive experience writing in statically typed languages.

In spite of this I definitely see value in learning C for handling demanding operations at lower levels of code (which I assume has a lot to do with static vs dynamic at the compiler level), but what I'm trying to wrap my head around is whether there are specific project contexts (maybe certain types of dynamic data-intensive operations?) involving things other than performance where it makes a lot more sense to go with Java or C# vs. something like Python.

答:
It's 2015 now, which adds some interesting snippets to the conversation:

Significant parts of the enterprise backend world is considering or starting to use Python (dynamic) in lieu of Java (strict static)

The enterprise frontend world is seeing things like AngularJS v2, based on TypeScipt: a typed extension of Javascript.

So the backend guys are tired of the unnecessary straight-jacket of strict typing, while the frontend guys are tired of the chaos of dynamic typing.

Quite ironic: I wonder if they'll meet in the middle, or rush past each other with the sonic boom of an deadline passing over...? ;)

OwnerDisplayName: Erik  Reppen


问:
Java desktop app with mysql database
I'm currently in the process of learning Java and swing and in doing so am trying to create a desktop app.

As part of this app I have set up a mysql database which the app is connected to, however I'm uncertain as to how this would work if I was to distribute the app for other users, how would I create a database that they are able to use on their system if they don't have mySQL installed or the database initiated.

答:
You should look into one of the many embeddable pure java SQL dbs which you can embed and distribute with your app. Your existing SQL should work with those either as is or with minor modifications. Take a look at:

http://hsqldb.org

and

http://db.apache.org/derby/

Title: Java desktop app with mysql database


问:
When to implement WCF Rest Service and WebApi
I have gone through many articles to understand why we need WebApi's when we can create restful architecture using WCF rest services but could not find some solid reason. Can we use these interchangeably? Are these just two approaches to solve similar type of problems.
Or else there are some things/features which each of these can do but other can't. Please help me to understand, how I can decide which one to use based on given scenario.</p>

答:
From here

Although WCF provides some support for writing REST-style services,
  the support for REST in ASP.NET Web API is more complete and all
  future REST feature improvements will be made in ASP.NET Web API

So for REST services it's preferable to use Web API, not WCF

That link also provides some useful info (like whether they are interchangeable, features of technologies)


问:
What is a good Design Pattern for a bundle of methods that comprises an algorithm?
This is a Design question relating to finding out a good OO design pattern or design structure or class combination that can house an algorithm that processes user selection to produce product recommendations.

Scenario

User specifies Motor and Product requirements and hits Submit.  Algorithm processes input, loads various motors and products, selects relevant motors and products as per specifications.  It then combines them, computes various parameters of the combos, and also notes any discrepancies.  Then, it provides an output in a form of valid product-motor combinations with computed specs, and also any discrepancies noted as warnings.

Question

Can I have an object called Algorithm, that is essentially a bundle of methods that loads Products, Motors, combines them, does computations on them, sets up various flags, etc?  Or is there a better design?

Current Design

My current design came from procedural background and used to be just a series of functions, now housed in a couple of classes.  Simplified algorithm is something like this (where Algorithm is a bundle of methods related to driving the algorithm, and BundleOfComputationalMethods that focuses on computational needs):

class Algorithm
{
    public $bundle;

    function __construct()
    {
        $this->bundle = new BundleOfComputationalMethods();
    }

    function getRequestDataFromPOST()
    {
        $this->bundle->options = $_POST;
    }

    function loadMotors(){}

    function loadProducts(){}

    function combineProductsAndMotors()
    {
        $this->getRequestDataFromPOST();

        $this->loadMotors();
        $this->loadProducts();

        for ($k = 1; $k <= $this->bundle->spec->max; $k++)
        {
            $this->bundle->computeRotationalSpeed();
            $this->bundle->checkIfSpeedWithinLimits();
            if ($this->bundle->speedIsOkay)
            {
                //bundle contains a "selection" to be presented back to the user
                //(Motor, Product, computed specifications, pricing, any warnings/errors)
                $result .= json_encode($this->bundle);
            }
        }

        return $result;
    }
}
```

答:
The pattern that comes in to my mind when reading this is the "Method Object".

If you have a big method you transfer it into an object. The state of the method (e.g. arguments) can be part of the object attributes.

Changes I see immediately:

Do not name the class Algoritm but CombineMotorsAndProducts

rename the method combineProductsAndMotors to compute.


答:
If you're just learning, I recommend that you put the details of deployment to one side at first and just assume that the database will always be there and will always be in the correct format. Once you've got your application to a state where you're reasonably happy with it, then you can address your concerns regarding the database.

When you do get to addressing these concerns, a general approach would be for your application to have a database setup script, this will be a set of SQL statements for creating the tables, indexes, permissions etc. Assuming that you're using JDBC, your application settings should specify the JDBC connection details (for example, JDBC Url, username and password). Your application should connect to this source and then run the setup script.

One caveat with your setup script is that it should work regardless of the state of the database. Suppose you have lots of statements of the form

```<code>CREATE TABLE FOO (id int....)
</code>```

If the table FOO already exists, you'll get an SQLException which you'll need to catch and ignore (but only for the specific case where the table exists, you can't ignore other errors).

Suppose a later version of your application needs a slightly different definition of FOO. In that case, you can't just change the CREATE statement, you'll need to keep your original CREATE statement followed by some ALTER statements.

This approach assumes that it will be possible for your application to connect to the JDBC data source. If you are planning for your application to use a standalone DBMS such as MySQL, Postgres, Oracle, SQL Server etc. then I would consider installing the DBMS to be the responsibility of the user of your application. The user will also need to figure out what the JDBC URL should be and provide that to your application.

If you want to avoid the user having to install a DBMS then it's possible to embed a pure Java DBMS with your application. JavaDB (AKA Derby) is one example, HSQLDB and H2 can also be used in this way. To take Derby as an example, you would need to include the derby libraries (jars) with your application and your application would need to create the database when it starts up. If you're using Derby in "embedded mode" your URL would look something like:

jdbc:derby:/home/fred/myapplicationdb

As far as I remember, the Derby library will create the database if it doesn't exist.

Title: Java desktop app with mysql database

Body:
I'm currently in the process of learning Java and swing and in doing so am trying to create a desktop app.

As part of this app I have set up a mysql database which the app is connected to, however I'm uncertain as to how this would work if I was to distribute the app for other users, how would I create a database that they are able to use on their system if they don't have mySQL installed or the database initiated.

Body:
If you're just learning, I recommend that you put the details of deployment to one side at first and just assume that the database will always be there and will always be in the correct format. Once you've got your application to a state where you're reasonably happy with it, then you can address your concerns regarding the database.

When you do get to addressing these concerns, a general approach would be for your application to have a database setup script, this will be a set of SQL statements for creating the tables, indexes, permissions etc. Assuming that you're using JDBC, your application settings should specify the JDBC connection details (for example, JDBC Url, username and password). Your application should connect to this source and then run the setup script.

One caveat with your setup script is that it should work regardless of the state of the database. Suppose you have lots of statements of the form

CREATE TABLE FOO (id int....)

If the table FOO already exists, you'll get an SQLException which you'll need to catch and ignore (but only for the specific case where the table exists, you can't ignore other errors).

Suppose a later version of your application needs a slightly different definition of FOO. In that case, you can't just change the CREATE statement, you'll need to keep your original CREATE statement followed by some ALTER statements.

This approach assumes that it will be possible for your application to connect to the JDBC data source. If you are planning for your application to use a standalone DBMS such as MySQL, Postgres, Oracle, SQL Server etc. then I would consider installing the DBMS to be the responsibility of the user of your application. The user will also need to figure out what the JDBC URL should be and provide that to your application.

If you want to avoid the user having to install a DBMS then it's possible to embed a pure Java DBMS with your application. JavaDB (AKA Derby) is one example, HSQLDB and H2 can also be used in this way. To take Derby as an example, you would need to include the derby libraries (jars) with your application and your application would need to create the database when it starts up. If you're using Derby in "embedded mode" your URL would look something like:

jdbc:derby:/home/fred/myapplicationdb

As far as I remember, the Derby library will create the database if it doesn't exist.


问:
Event logging: record a whole message, or a list of properties and generate?
I've written a simple event logging system, which I write to with a function similar to:

```<code>void IIncidentLogic.ReportIncident(
  string code,
  string noun,
  string hostname,
  DateTimeOffset occurredAt)
</code>```

Where code is derived from a set of constants such as VOL_SIZE_INCREASE, noun would be the path of the volume, hostname the computer where it occurred, and occurredAt when it was detected.

Since code is a known value, I can automatically set other properties, such as the severity of the event, e.g. is it a warning or an error? I also use code to query a resource dictionary for a friendly error message to display to users. Right now for this example the error message would be A volume has increased in size, with the noun clumsily appended to the error message.

I am looking to improve the readability of the error messages, e.g. in this scenario to be something like The volume system (c:) on computer-name has increased in size from 100GB to 200GB.

I can think of a couple of ways to do this, and am wondering what is the better practice.

I could pre-build the error message, and pass to the logging function, storing in it's own field. However I want to programmaticly force the message to the be the same, no matter where it's generated. A string message parameter is too open.

So I could record a dictionary of properties against the report, e.g. {originalSize: '100GB', newSize: '200GB', volume: 'system (c:)'}.
I could still use resource strings to generate the messages, but format them, e.g. The volume {0} on {1} has increased in size from {2} to {3}.
This allows for i8ln, which is a likely future requirement. But it has a possibility to break legacy data if any part changes, e.g. an additional property is required.

And I could do both: use the properties and string formatting, and store the generated string at the same time.

I could also go as far as having a class per event type, or code, with different constructor parameters, but this certainly feels like overkill.

Or is there a different established pattern for this kind of logging?

答:
If you want consistency, then using a class for each error condition gives you just that - wherever you want to mention that a volume has grown in size, you create an instance of a VolumeSizeIncreased class, passing whatever values you need into its constructor.

To me, it's the next step after rigidly codifying your errors (your VOL_SIZE_INCREASE value).

```<code>VolumeSizeIncreasedMessage vsim
   = new VolumeSizeIncreasedMessage( "PC123456", "system (C:)", 100, 200, DateTime.Now )
Console.WriteLine( vsim.toString() );
</code>```

Are you intended to do anything with these errors afterwards (other than physically reading them)?  If so, objects are a far better option, because you can query their properties and take actions based on those (but I'm veering into Exception Handling here).

Body:
If you want consistency, then using a class for each error condition gives you just that - wherever you want to mention that a volume has grown in size, you create an instance of a VolumeSizeIncreased class, passing whatever values you need into its constructor.

To me, it's the next step after rigidly codifying your errors (your VOL_SIZE_INCREASE value).

VolumeSizeIncreasedMessage vsim
   = new VolumeSizeIncreasedMessage( "PC123456", "system (C:)", 100, 200, DateTime.Now )
Console.WriteLine( vsim.toString() );

Are you intended to do anything with these errors afterwards (other than physically reading them)?  If so, objects are a far better option, because you can query their properties and take actions based on those (but I'm veering into Exception Handling here).


问:
Saving to Registry vs. CustomFile
I've been using the usual My.Settings... method when it came to saving settings for my program but I was just wondering, If I wanted to save program settings into the Registry and load those settings, are there any benefits when comparing with saving settings to a custom written file and loading those settings from the file.

Which would you prefer and why?

答:
I would suggest that the Windows Registry is best left to Windows itself to play with.

Parts of it are inaccessible to regular users.

Parts of it are inaccessible to certain types of application (32-bit processes running on 64-bit versions of Windows).

It's a completely proprietary storage mechanism, which can change, without warning, with any upgrade or security patch.

It's not easy to backup or restore parts of the Registry; it's really all or nothing.

Values held therein aren't portable; they're fixed onto one particular machine.

Contrast that with a simple, text file held in the user's Roaming profile directory:

They are accessible to the user (with no security or U.A.C. complications), the format and content of that file are completely under your control, they get captured by a regular, file system backup, they can get carried, seamlessly, onto every machine that the user logs onto and they're less likely to get lost if you have to reinstall your operating system.

Title: Saving to Registry vs. CustomFile


问:
Algorithm to solve this "treefarm" puzzle
How would I go about writing a program to solve this kind of puzzle:
The green squares represent trees, and you have to plant them in such a way, so that:

Trees do not touch each other at all (not even diagonally)

Each row and column contain a specific number of trees, which is denoted in the corresponding cell to the right of or below the main grid respectively

The numbers within cells of the main grid are irrelevant.

I can immediately eliminate rows and columns with a required tree amount of 1 that have a tree in them, and 9x9 squares around each of the trees. After that, I got stuck.

Thanks for any ideas.

答:
When solving a puzzle like this, there are two things you can do:

Look for places where you can apply some pattern to cross out a square or plant a tree there with certainty

Make a guess, and proceed until it either comes to an unsolveable situation (in which case you backtrack to your previous guess), or you finish.

For this particular puzzle, the operations falling into the first category that I can see would be:

Mark off all cells in rows or columns containing an equal number of trees to the number required (including 0).

Mark off all cells adjacent to a planted tree

In any row or column with only one remaining cell and one more tree required, plant a tree in that cell

In any row or column with two remaining cells and two more trees required, plant a tree in both of those cells

In any row or column with three remaining cells which are all connected, and two more trees required, plant a tree in the cells at either end of the group of three.

In any row or column with three remaining cells where two are connected, and two more trees required, plant a tree in the disconnected cell.

These all need to be checked for every row, column and tree when first starting. After that, the first two can be done immediately when planting a tree.

If row and column numbers greater than 2 are allowed you'll have to work out a more general version of the final 4 rules. Alternatively, a simple brute force which checks all valid combinations to see if any of them either always have a tree or never have a tree would work.

For the second category, you're going to be doing a depth-first tree search. For each node, you'll want to do the following:

If this is a leaf node, check if it's terminal (the game is unwinnable or won). If so, either you're done or you need to backtrack up to the parent

If this is a leaf node, apply the identities above to see if you can instantly mark off or plant trees in any more tiles.

If this is a leaf node, add children corresponding to some unfilled tiles which are not marked off.

Pick a child which has not already been fully expanded, and expand it.

A naive method for 3. and 4. would be to add all unmarked children, then pick one at random (or in an arbitrary order) to expand. But you can almost certainly do better with a heuristic.

One that springs immediately to mind is for the third step, pick the row or column with the least possible combinations of tree placements satisfying it in isolation. For example, the fifth row from the top has five possible combinations satisfying it. Then only add one child for each of these combinations. You know that one of them will definitely be correct, so you now only have 5 children to expand, one of which will for sure get to the right answer.


问:
using GNU GPL v2 software as pointers to solution to problem
I am coding a PHP serial access class and have been taking pointers from the PHP-serial class on Google Code (here).  That class is based on PHP 4 and I'm creating a PHP 5 class that allows more functionality and is specific to some business demands I have.

There is no code copied and I have done all the coding.  Does the class I'm writing fall under the Google Code's GPL or am I free to select a license that I feel is appropriate?  I'm not sure of the standard that applies to licensing when you are only looking to another work for pointers.

答:
The GNU GPL is a source code license. The reciprocal (viral) clause only applies to derivative code. Derivative code only. It is not a patent license, and thus you can take and reimplement all ideas or algorithms. Reimplement, not verbatim code duplication. And whichever license you want to distribute your independently written code under, is up to you. Not that another FLOSS developer would mind anyway. - If you are very uneasy and want a reaffirmation, you can also contact info@fsf.org (patience).

But btw, the GNU GPL v2 is already more permissive on PHP code than on compiled languages. Unless your library was incorporated as core dependency in some proprietary/obfuscated code, it would work akin the LGPL.

As a side note, it's not sensible to rewrite something from PHP4 to PHP5. It's the same friggin language. If you just add syntactic sugar (private, protected, etc.) but use no real new functionality (ArrayAccess, SPLSomething, etc.) then pointless. So I hope there is really new functionality in your reimplementation.

ContentLicense: CC BY-SA 2.5


答: This looks like variation of nonogram puzzle. You can find some inspiration from existing nonogram solvers. It seems that you would need to add constraint about boxes not touching diagonally.</p>

Title: Algorithm to solve this "treefarm" puzzle

Body:
How would I go about writing a program to solve this kind of puzzle:
The green squares represent trees, and you have to plant them in such a way, so that:

Trees do not touch each other at all (not even diagonally)

Each row and column contain a specific number of trees, which is denoted in the corresponding cell to the right of or below the main grid respectively

The numbers within cells of the main grid are irrelevant.

I can immediately eliminate rows and columns with a required tree amount of 1 that have a tree in them, and 9x9 squares around each of the trees. After that, I got stuck.

Thanks for any ideas.


答:
A good starting point is Jeff Atwood's article: Was The Windows Registry a Good Idea?

It gives a lot of good reasons not to use the registry. Among them:

The registry is a single point of failure. That's why every single registry editing tip you'll ever find starts with a big fat screaming disclaimer about how you can break your computer with regedit.

The registry is opaque and binary. As much as I dislike the angle bracket tax, at least XML config files are reasonably human-readable, and they allow as many comments as you see fit.

The registry has to be in sync with the filesystem. Delete an application without "uninstalling" it and you're left with stale registry cruft. Or if an app has a poorly written uninstaller. The filesystem is no longer the statement of record-- it has to be kept in sync with the registry somehow. It's a total violation of the DRY principle.

The registry is monolithic. Let's say you wanted to move an application to a different path on your machine, or even to a different machine altogether. Good luck extracting the relevant settings for that one particular application from the giant registry tarball. A given application typically has dozens of settings strewn all over the registry.

Probably the only applications that may require the registry are:

COM applications. Without a central repository it'd be much harder to get the class ID (CLSID)

large scale applications that need to administer the configuration network-wide (storing the data in the registry gives you the possibility to use Admin Templates in a Group Policy).

Title: Saving to Registry vs. CustomFile

Body:
I've been using the usual My.Settings... method when it came to saving settings for my program but I was just wondering, If I wanted to save program settings into the Registry and load those settings, are there any benefits when comparing with saving settings to a custom written file and loading those settings from the file.

Which would you prefer and why?


问:
Function name in parentheses after function call in Python
I ran into these lines of code in the QPYTHON Android app. They are part of a sample that uses the Bottle module to create a simple Web server that seems to work fine.

```<code>app = Bottle()
app.route('/', method='GET')(home)
app.route('/__exit', method=['GET','HEAD'])(__exit)
app.route('/__ping', method=['GET','HEAD'])(__ping)
app.route('/assets/<filepath:path>', method='GET')(server_static)
</code>```

Now, I know that all the functions in parentheses after the call have already been wrapped with the @route decorator above this. For example:

```<code>@route('/__ping')
def __ping():
    return "ok"
</code>```

But I have no idea what putting things in parentheses after other things does in Python, and after trying a hundred different permutations of "functions in parentheses after functions" I gave up.

I throw myself on the mercy of the Exchange.

答:
This:

```<code>app.route('/', method='GET')(home)
</code>```

... Is the same as this:

```<code>func = app.route('/', method='GET')
func(home)
</code>```

In other words, app.route(...) returns a function, which is then called.

ContentLicense: CC BY-SA 4.0

Body:
This:

app.route('/', method='GET')(home)

... Is the same as this:

func = app.route('/', method='GET')
func(home)

In other words, app.route(...) returns a function, which is then called.


问:
Namespace by topic or by purpose?
The project I'm working on has quite a few classes. These classes can be grouped in two different ways. I'm trying to decide which grouping is best as for namespacing. Currently I a set of user facing classes that look like:

JamJar

HoneyJar

PeanutButterJar

etc...

These are all similar in that they all inherit from SpreadableJar, each spreadable prefix could be considered a 'topic' within in the project.

I also have a set of objects relating to these topics, each topic usually has a set of constant definitions and message classes associated with it so I end up with a bundle of files such as:

JamDefinitions

PeanutButterSpreadMessage

HoneyDefinitions

JamRemoveMessage

etc...

I can think of two ways to organise these files:

By Topic
First level is namespace, second is class/file name.

Jam

Jar

Definitions

RemoveMessage

etc...

Honey

Jar

Definitions

etc...

PeanutButter

Jar

Definitions

SpreadMessage

etc...

This seems tidy (removes duplicated names) and is useful to the user of the library but means that all the Jar files look the same in the project structure, and each Jar class no longer has a descriptive name. It also means that related objects are grouped together so they will not need to scope into each others namespaces

By Purpose

Jars

JamJar

HoneyJar

PeanutButterJar

Definitions

JamDefinitions

HoneyDefinitions

PeanutButterDefinitions

Messages

JamRemoveMessage

etc...

This way is clear to the user if they know that they need to use Jars (the rest of the objects won't be needed by external users) and it separates the large number of messages and the separate definitions files from the main functionality, but now the Jars will need to scope into the other namespaces for their own definitions and messages and the file naming becomes more awkward. The 'Jar' from JamJar can't really be removed because the class is not just 'Jam'.

What is the best approach here? Am I missing some obvious solution or error in my structure?

答:
Which of the two is more likely:

Somebody is working with a jam jar, and while doing so, they want to look at a jam definition

Somebody is working with a jam jar, and while doing so, they want to look at a honey jar?

You're best placed to answer this, given your knowledge of the project, but in general I would say that the first of these two seems far more common. When working on jam-related functionality, your work may well span several interdependent classes. It seems much less likely that you're going to want to work on a lot of classes for unrelated functionality/features just because the purpose they serve is similar (though it may occasionally come up, e.g. when dealing with cross-cutting concerns).

Given this, I'd say the top level namespace should be topic, allowing easy grouping of related code.

As for:

(removes duplicated names) ... but means that all the Jar files look the same in the project structure, and each Jar class no longer has a descriptive name.

This is a trade-off you're choosing to inflict on yourself. There's nothing stopping you from having Jam.JamJar, for example.

While I can see the argument for not wanting to duplicate names like that, overall removing the Jam part from the name seems like a poor trade-off. It doesn't play well with namespace imports/usings at all. If you import a single namespace, your classes end up with less descriptive names. If you import multiple namespaces, you end up with ambiguities which are annoying to resolve.

You could perhaps import the base namespace then do Jam.Jar, etc., but this is atypical, people won't really be used to doing it, and you may suddenly find yourself writing a new class that doesn't fit well into this more rigid naming scheme.

Title: Namespace by topic or by purpose?


问:
Should instance of Employee contain a reference to instance of Office, or should Office contain an array of Employee?
Title is an abstraction of what I am actually doing, but in essence the same.

The main entity I will be dealing with are the Employees themselves; "Send package to employee John Doe". In order to work with a given Employee, I need to use the IOffice they belong to, and each office has a different way of delivering that package to that Employee. I am not really interested in how the package is delivered, just that it gets there.

In the first way mentioned in the title, it would look something like this:

```<code>public class Employee
{
    private IOffice _office;

    public Name { get; set; }

    public void Send(Package package)
    {
        _office.Send(package, this)
    }
}

public class SomeOffice : IOffice
{
    public void Send(Package package, Employee employee)
    {
        // Implementation of how this office gets the package to employee
    }
}
</code>```

Doing it this way, I can simply have a list of all employees, and employees in the same office can share the same IOffice object.

The second approach like so:

```<code>public class Employee
{
    public Name { get; set; }
}

public class SomeOffice : IOffice
{
    public List<Employee> Employees { get; set; }

    public void Send(Package package, Employee employee)
    {
        // Implementation of how this office gets the package to employee
    }
}
</code>```

This makes it harder to have instance of Employee and send a package to it. You must get the instance you want from the Employees-collection, and pass it into the office's Send-method. However, it keeps the Employee-class simpler, and makes the IOffice take care of everything.

There are probably other ways to go about this also. How would you do it?

Edit:
For concrete example, replace IOffice with a CommunicationInterface, such as SerialPort, UdpClient, TcpClient etc.

At the end of each endpoint there are different Devices (Employees). These devices all behave similarly, but how to send them a request (Package) and get a response back differs.

From my program, I want to have a list of all available devices, across all CommunicationInterfaces, and send requests to them, and get responses back.

答:
One thing I see with the first example that could lead to confusion is that the Employee is not sending the package, they are receiving the package. I think the send method leads to confusion that the Employee is sending the package, when the Employee is receiving the package.

I think the second example is better. The SomeOffice class has a reason to keep a list of Employees and is the entity that will perform the Send() if you think about it in terms of an actual office that might send a physical package to an employee.


答:
I find it hard to give general solutions of this kind since system architecture is always highly depending upon the entire domain.

If routing packages to employees is a main concern in your system, maybe neither Office nor Employee have to know about how they relate to each other.

You could also think about an additional Entity of your system, like an EmployeeRegister for example, which can look-up the Office for an Employee instance. Than you can deliver this Package to the Office.

In an additional step, you can encapsulate this specific step into a Postmaster Entity, which just accepts a Package and an Employee. It utilizes such a register to find the Office and then delivers it.

Title: Should instance of Employee contain a reference to instance of Office, or should Office contain an array of Employee?

Body:
Title is an abstraction of what I am actually doing, but in essence the same.

The main entity I will be dealing with are the Employees themselves; "Send package to employee John Doe". In order to work with a given Employee, I need to use the IOffice they belong to, and each office has a different way of delivering that package to that Employee. I am not really interested in how the package is delivered, just that it gets there.

In the first way mentioned in the title, it would look something like this:

```<code>public class Employee
{
    private IOffice _office;

    public Name { get; set; }

    public void Send(Package package)
    {
        _office.Send(package, this)
    }
}

public class SomeOffice : IOffice
{
    public void Send(Package package, Employee employee)
    {
        // Implementation of how this office gets the package to employee
    }
}
</code>```

Doing it this way, I can simply have a list of all employees, and employees in the same office can share the same IOffice object.

The second approach like so:

```<code>public class Employee
{
    public Name { get; set; }
}

public class SomeOffice : IOffice
{
    public List<Employee> Employees { get; set; }

    public void Send(Package package, Employee employee)
    {
        // Implementation of how this office gets the package to employee
    }
}
</code>```

This makes it harder to have instance of Employee and send a package to it. You must get the instance you want from the Employees-collection, and pass it into the office's Send-method. However, it keeps the Employee-class simpler, and makes the IOffice take care of everything.

There are probably other ways to go about this also. How would you do it?

Edit:
For concrete example, replace IOffice with a CommunicationInterface, such as SerialPort, UdpClient, TcpClient etc.

At the end of each endpoint there are different Devices (Employees). These devices all behave similarly, but how to send them a request (Package) and get a response back differs.

From my program, I want to have a list of all available devices, across all CommunicationInterfaces, and send requests to them, and get responses back.


问:
How do I best query for user-owned data when using NoSQL
Say I have a typical website which provides authenticated users access to their stored ('owned') data. Authorised users must be able to perform CRUD operations on their data. If I were using a RDBMS-based solution I would use a series of joins based on the user_id retrieved from the session in order to make sure that I only serve users data which belongs to them, for example;

```<code>select comments.* from comments
inner join blogs on blogs.id = comments.blog_id
inner join clients on clients.client_id = blogs.client_id
inner join users on users.client_id = clients.client_id
where users.user_id = X;
</code>```

This pseudo-SQL example gives me all the comment data which belongs to the user.

If I were taking a NoSQL approach I'd have a blog document which embedded a comments array and exposed a client_id field which I could populate in Mongoose, but the issue comes in when I have to run a separate query to fetch all the clients which belong to the user.

Is there a more efficient way to do this? I'm worried I'm missing a basic concept. I suppose the answer may be to store more related data within documents, so have a base client document which stores arrays of users and blogs with nested comments, but this seems design seems too rigid.

答:
As far as the SQL side of things goes, there is opportunity to optimize, but it depends on what you want to optimize around. If you are seeking to simplify queries or speed up performance, denormalization is one way to achieve this. For example, you could include the client_id in the comment table in addition to the blog_id given that it appears that blogs can have only one associated client_id. Once you do that, the query above becomes:

```<code>select comments.* from comments
inner join users on users.client_id = comments.client_id
where users.user_id = X;
</code>```

This is less complex, and depending on the size of the tables could have some performance benefit. The tradeoff is that you will end up with a somewhat more complex data model with redundant data across tables making it potentially harder to maintain data integrity.

Note, in your original example above, it is possible to simplify the query.  without denormalizing.  You aren't actually using any of the "clients" table data in the result, so including it in the join is extraneous given that the "users" table includes the client_id and can be joined directly to the blogs table.

For the NoSQL side of things, there is a lot of variability across platforms with respect to how they treat the individual fields within a document and how they can be indexed and/or made searchable. For example, you could still keep each post as a separate document and, in MongoDB at least, you could index the client_id field to make it faster to search for and retrieve the right posts, but the optimal approach might be different on another platform.

One concern with building a large document that contains all of the blog posts and comments for the client, as you suggest above, is that you could run into challenges with performance. On a query, you might have to retrieve the whole document, move it over the network, and navigate through the document to get to the item you want. This could be slow. If multiple users are adding comments at the same time, you could run into more lag as the requests are queued waiting for write locks to be released.

Decomposing into multiple documents/collections with MongoDB, for example, carries, the additional complexity of having to run multiple queries to retrieve the item you want, but it lets you read and update at a smaller grain and could result in improved performance and probably lower overall complexity in your code as you no longer need to manage the entire set of blog posts for the client as one large, complex, collection.

Body:
As far as the SQL side of things goes, there is opportunity to optimize, but it depends on what you want to optimize around. If you are seeking to simplify queries or speed up performance, denormalization is one way to achieve this. For example, you could include the client_id in the comment table in addition to the blog_id given that it appears that blogs can have only one associated client_id. Once you do that, the query above becomes:

select comments.* from comments
inner join users on users.client_id = comments.client_id
where users.user_id = X;

This is less complex, and depending on the size of the tables could have some performance benefit. The tradeoff is that you will end up with a somewhat more complex data model with redundant data across tables making it potentially harder to maintain data integrity.

Note, in your original example above, it is possible to simplify the query.  without denormalizing.  You aren't actually using any of the "clients" table data in the result, so including it in the join is extraneous given that the "users" table includes the client_id and can be joined directly to the blogs table.

For the NoSQL side of things, there is a lot of variability across platforms with respect to how they treat the individual fields within a document and how they can be indexed and/or made searchable. For example, you could still keep each post as a separate document and, in MongoDB at least, you could index the client_id field to make it faster to search for and retrieve the right posts, but the optimal approach might be different on another platform.

One concern with building a large document that contains all of the blog posts and comments for the client, as you suggest above, is that you could run into challenges with performance. On a query, you might have to retrieve the whole document, move it over the network, and navigate through the document to get to the item you want. This could be slow. If multiple users are adding comments at the same time, you could run into more lag as the requests are queued waiting for write locks to be released.

Decomposing into multiple documents/collections with MongoDB, for example, carries, the additional complexity of having to run multiple queries to retrieve the item you want, but it lets you read and update at a smaller grain and could result in improved performance and probably lower overall complexity in your code as you no longer need to manage the entire set of blog posts for the client as one large, complex, collection.


答:
I feel I can contribute to this given answer.

The concept Phill is describing comes very close to the EventSourcing Pattern. If your systems contains several types of Events, consider such an implementation. The overal flexibility, as mentioned by Phill, will drastically increase since you don't have to know yet what you will do with the data.

Title: Event logging: record a whole message, or a list of properties and generate?

Body:
I've written a simple event logging system, which I write to with a function similar to:

```<code>void IIncidentLogic.ReportIncident(
  string code,
  string noun,
  string hostname,
  DateTimeOffset occurredAt)
</code>```

Where code is derived from a set of constants such as VOL_SIZE_INCREASE, noun would be the path of the volume, hostname the computer where it occurred, and occurredAt when it was detected.

Since code is a known value, I can automatically set other properties, such as the severity of the event, e.g. is it a warning or an error? I also use code to query a resource dictionary for a friendly error message to display to users. Right now for this example the error message would be A volume has increased in size, with the noun clumsily appended to the error message.

I am looking to improve the readability of the error messages, e.g. in this scenario to be something like The volume system (c:) on computer-name has increased in size from 100GB to 200GB.

I can think of a couple of ways to do this, and am wondering what is the better practice.

I could pre-build the error message, and pass to the logging function, storing in it's own field. However I want to programmaticly force the message to the be the same, no matter where it's generated. A string message parameter is too open.

So I could record a dictionary of properties against the report, e.g. {originalSize: '100GB', newSize: '200GB', volume: 'system (c:)'}.
I could still use resource strings to generate the messages, but format them, e.g. The volume {0} on {1} has increased in size from {2} to {3}.
This allows for i8ln, which is a likely future requirement. But it has a possibility to break legacy data if any part changes, e.g. an additional property is required.

And I could do both: use the properties and string formatting, and store the generated string at the same time.

I could also go as far as having a class per event type, or code, with different constructor parameters, but this certainly feels like overkill.

Or is there a different established pattern for this kind of logging?


答:
As pvg has mentioned, a good option to use is an embedded database. The reason here is that the database can be included as a single JAR file, rather than needing to be installed on the system's user. Usually, you can access the databases using the standard JDBC API, so it really can act as a replacement for your current MySQL DB. The library will manage creation of DB files so you don't have to install anything.

Of course, these options are typically less robust than something like Oracle, however, it may suit your needs just fine.

For example, I recently utilized the H2 database, a 100% Java embedded DB, in a project of mine. http://www.h2database.com/html/main.html

Here is some example code which shows how using something like H2 would differ than MySQL when you want to get a connection object, but note, interacting with the DB to run queries would be the same as with MySQL:

```<code>import org.h2.jdbcx.JdbcDataSource;
import java.sql.*;

/**
 * Sets and returns a DB connection, if not already done
 */
private static Connection getDBConnection() {
    if (mDBConnection != null)
        return mDBConnection;

    Connection conn = null;
    try {
        JdbcDataSource ds = new JdbcDataSource();
        ds.setURL("jdbc:h2:C:/MyDBDirectory/");
        conn = ds.getConnection();
    } catch (SQLException e) {
        mLogger.severe("Error opening DB connection or creating tables: " + e.getMessage());
    }
    mDBConnection = conn;
    return mDBConnection;
}
</code>```

Title: Java desktop app with mysql database

Body:
As pvg has mentioned, a good option to use is an embedded database. The reason here is that the database can be included as a single JAR file, rather than needing to be installed on the system's user. Usually, you can access the databases using the standard JDBC API, so it really can act as a replacement for your current MySQL DB. The library will manage creation of DB files so you don't have to install anything.

Of course, these options are typically less robust than something like Oracle, however, it may suit your needs just fine.

For example, I recently utilized the H2 database, a 100% Java embedded DB, in a project of mine. http://www.h2database.com/html/main.html

Here is some example code which shows how using something like H2 would differ than MySQL when you want to get a connection object, but note, interacting with the DB to run queries would be the same as with MySQL:

import org.h2.jdbcx.JdbcDataSource;
import java.sql.*;

/**
 * Sets and returns a DB connection, if not already done
 */
private static Connection getDBConnection() {
    if (mDBConnection != null)
        return mDBConnection;

    Connection conn = null;
    try {
        JdbcDataSource ds = new JdbcDataSource();
        ds.setURL("jdbc:h2:C:/MyDBDirectory/");
        conn = ds.getConnection();
    } catch (SQLException e) {
        mLogger.severe("Error opening DB connection or creating tables: " + e.getMessage());
    }
    mDBConnection = conn;
    return mDBConnection;
}


问:
C++ using shared_ptr with API
I'm building a library that generates a couple of types of objects that can be used by user code and the library. To keep track of these objects, I'd like to use shared_ptr's, so I can build in some run-time clean up. Since these are consumed by user code, I was curious if it would be worth typedefing the shared_ptr type to simplify the user code. So instead of std::shared_ptr<Foo>, user code could use FooPtr or something.

Would that be a reasonable thing to do, or is the risk of unclear code too much?

答:
With C++ it's best if there is explicit documentation about who owns what pointer and is responsible for cleanup. shared_ptr tend to muddle that and it's possible that a shared_ptr ownership-loop emerges across the user and API which can lead to leaks.

Let the user hold a small section of objects by unique_ptr and let other objects be owned (and cleaned up) by them and referenced by the user with raw pointers or references.

Title: C++ using shared_ptr with API


问:
Cookie name security
Is it a security hole to name each session with the username of the user currently logged in?

example:

```<code>//Alice has login
sessions_name('Alice'); sessions_start(); //Alice has login
//When Bob Logs in
sessions_name('Bob'); sessions_start(); //code follows for Bob
</code>```

etc....

答:
Generally, your session name with be PHPSESSID (unless you rename it with session_name - like you've proposed). This really gives no extra benefit in terms of security, here's why;

You've mentioned that you're aware sessions can get stolen, which is correct (session hijacking), though the name itself (Alice, Bob) introduces no security measure in this (not even by having different names for each user).

The session_name is something that will allow your application to reference the session with a more obvious meaning. (Ie: It makes no sense if PHPSESSID to hold session data about a form in terms of scanning code - PHPSESSID doesn't reference form in any way - this is a vague example, but you understand).

So we have identified the risk, but why having dynamic session_name not help with security?

Generally, a session hijack will be done via XSS exploit. This vulnerability will execute Javascript on the clients/targets machine and send you (the attacker) their cookies (session values and session names are included. Having the session value makes it a full cake).

The attacker will send themselves the cookies by creating a request (usually HTTP) to a webserver they own with post data of document.cooke

In conclusion

Naming the session dynamically isn't a security flaw in itself. The session won't "work" without the correct value & name. Your main concern should be binding the session value to the client, by;

Binding the session value to the users user-agent

Binding the session value to the users IP

You should also look into session_regenerate_id() so that if an attacker did get your session id, they'd have to be quick enough to hijack it before the value regenerates.

Title: Cookie name security


答:
For a desktop application, it's usually better to deliver everything the end user will need in a single package.  End users tend to dislike dependency requirements, because it only takes one or two conflicting packages requiring different versions of the same thing to completely ruin your day.

For a single-user application, you're probably best off using an embedded database.  In fact, the more recent releases (from 6 onwards) of the JDK include one (JavaDB, aka Apache Derby.)

You should also bear in mind that maintaining a database server on your computer isn't a trivial task.  Ask yourself if you really think your end users will bother with your application if you've added that burden to it.  A server will also consume system resources, meaning the end user will either feel their system is being unnecessarily bloated, or will be stuck with the task of stopping and starting it in order to use your application.

If you're unsure of the environment the end user is working with, a good compromise is to bundle an embeddable DB engine with your application, use that as the default, and allow the user an option to configure a connection to an external database if they prefer.  Individual end users can then use, say, Derby/JavaDB, while the power users and networked multiuser customers can connect to a database server such as MySQL or Oracle.  The downside here is you'll need to watch your usage of SQL to ensure it works on all supported database engines, or to use an abstraction library.

Title: Java desktop app with mysql database


答:
The best logging is just to format it as a readable string and persist that. Possibly including the data as a block of data that is accessible to programs as well.

The reason I say this is that I am continually looking at Windows Event logs, which uses a "we write the data and a link to a resource dll containing format strings" pattern, and invariably the dll is only present on the host computer - not on mine where I analyse the logs. Hence, I can never see the full text of what was written, just the raw data.

Its also very easy and simple to write text, and that is what you will want written when you come to look at the logs later, making it the ideal pattern.

Note also that there is a huge controversy in the linux world at the moment as systemd writes its logs using a binary format, meaning you need a special viewer to read them. People were used to using any old text editor to read and/or parse logs written in text formats. There's a good reason text logs with plain formatted strings have been used for logging.

So think of the end-user of your logs and how they will interact with them, and fit your solution to give them the best experience.


问:
What can go wrong with composing a method name out of a string?
I have a piece of code that composes method name to call from a string parameter. I don't feel it's a good thing to do but I'm not sure what can go wrong with this.

Here is a simplified snippet of that code:

```<code>switchToFilter = function(filter){
    var filterMethod = 'switchTo' + filter;
    myObject[filterMethod]();
}
</code>```

答:
If the string comes from an insecure source (user input etc. ) it is absolutely, totally unacceptable. You voluntarily added a code injection vulnerability to your code. </p>

<p>You can write some code that will map a list of known function names to known functions, where you have verified yourself that each of those functions may be called without negative side effects. </p>

Body:
If the string comes from an insecure source (user input etc. ) it is absolutely, totally unacceptable. You voluntarily added a code injection vulnerability to your code.

You can write some code that will map a list of known function names to known functions, where you have verified yourself that each of those functions may be called without negative side effects.


问:
Do objects in OOP have to represent an entity?
Does an object have to represent an entity?

By an entity I mean something like a Product, Motor, a ParkingLot etc, a physical, or even a clear-cut non-physical conceptual object -- something that is well defined, with some core data clearly belonging to the object, and some functions/methods that clearly operate on the core data.

For example, I can have an object of a Demon, an entity in itself, an imaginary one perhaps and not physical but an entity nevertheless

Can an object be just a collection of methods, a common set of procedures that tie in with a common goal?

Example:  can a class be called MotorOperations or MotorActions, where there is no entity, but methods inside the class do things like

getMotorDataFromHTMLForm()

getMotorManufacturers()

selectMotorFromUserRequirements($requirements)

canMotorCanHandleOperatingConditions($conditions)

computePowerConsumptionForMotor($id)

A class is typically defined as data central to the object + operations on data.  So for a Motor there may be some motor variables relating to motor specifications, and there can be operations that combine those data to produce something.

In my case it is more like I have a class with operations on data + data that is passed through the class, there is no data centric to "Motor Operations", other than temporary pass-through-the-class data.

Question

Can classes represent entity-less objects?
If not, why they are bad/incomplete/non-OOP-centric?  Are there ways they need to be changed/improved conceptually to be in line with OOP?

答:
In layman's words

What you describe is called an utility class.

It has no state, meaning you will not ever really need to have several instances of it

All methods are static, meaning you have to pass everything as parameters

Such classes do exist, for example the Java SDK has the Collections class which consists exclusively of static methods that operate on or return collections.

So the answer would be no, not all classes need to be modelled from a domain entity.

In the other hand, such classes are only a few or should be only a few in a program made in a OOP language, since the real power of OOP lays in polymorphism and encapsulation.

It would be like using a plane to go from one place to another not by flying but by driving it around on freeways. Planes have wheels like cars do, but they are intended to fly.


问:
Connect to MS SQL database from client side
I had a software that was written on VB .Net and used Crystal Report to print out reports. It was a pain to maintain in my case, so I want to move the report to webpage version.

I did some researches and found out that it was more safe to connect database from server side on webpage. However, I want to know if there is any way to connect database from client side and it hides the connection string. Any mix way is fine. (I tried using java applet to connect database, but it didn't allow me to run from local file on webpage).

Is there any way I can connect to database from client side and hide the connection string?

Thanks

P.s. I use Firefox as a main browser.

答:
No

Technically, it looks like there are some ways to connect directly to your database via HTTP (google "sql server http endpoint deprecated" and "ado.net data services") but you cannot hide the connection information if it is on the client.

This is a crazy bad idea -- don't do it.

One of the first rules of web app programming is that the client cannot be trusted - all client code can be (fairly easily) hacked.  Put the important bits (like connection strings) on the server where the bad guys have to at least work a little harder to get to them.

Your best approach would be to do what just about everyone else does - write a server based web app that connects to the database and delivers just the data to the client.

On a side note, within reason, which browser you're using shouldn't matter.


问:
OODesign: Data Structure which calls algorithm on insert
I have a data structure which has an add function.
When the user instantiates a new data structure object, she can specify an algorithm which will be executed each time the add function is called and alters the newly inserted value based on the previous values in the data structure. The algorithm needs to have access to all the data in the data structure.

Thus the data structure needs to store an algorithm object (since this is called each time the add is executed). On the other hand the algorithm needs access the data structure, and thus needs to store the data structure object.

I think situations where class A has an instance of class B and class B has an instance of class A are usually undesirable.

Does anybody have an idea how to solve this recurrence here?

答:
If you have a cyclic dependency like this, this hints at one of two problems:

the two objects should really be one object

the two objects should really be three objects (with the inter-related parts extracted into the third)

What you have here, is highly unusual. Adding an element to a data structure is one of the primary responsibilities of a data structure, outsourcing that to the client, especially in a way that requires privileged access to the data structure's private internals, just seems wrong somehow.

This is very different from, say, a SortedSet which needs both an Ordering and an Equality algorithm, but neither of those two algorithms needs to know anything about the Set, it only needs to know how to compare two elements. Or a HashMap which needs a Hash algorithm that can hash a single element. That's the typical case for a data structure parameterized by an algorithm.