答:
You can use a nested diagnostic context (NDC) to push the information in before you enter the ORM module (or at whatever level is appropriate).

This idea is referred to in the log4net documentation as Context Stacks but most loggers have a similar concept.

Title: Logging page/session ID in an inner module

Body:
We have a C# ORM module that generates queries. It logs generated queries and other information into the error/trace file. It is used by our web application. Most of our queries are generated dynamically (based on dynamic business rules and user interactions) which we have little control over.

Obviously the ORM module is completely decoupled from the web application, and therefore completely unaware of web sessions, page hits etc. The downside is that the log entries it generates cannot be traced back to the original page hit. When we notice a non-performant query in the log, we cannot easily determine which page hit generates that query.

How can I keep the ORM module decoupled from the web application, but still allow it to log enough relevant information for me to correlate each log entry to a session/page hit?

(I know we can pass the logger object around, and the logger object can preserve that session information. However, some of these function calls are nested 10 levels deep, so passing the logger around is cumbersome).


问:
When to use tools vs custom development?
To learn dependency injection in a current side-project, I am writing my own dependency injection container. </p>

<p>But this has lead me to wonder, at what point is it worthwhile to use a third party product vs "roll my own"? What would be the kind of questions you would ask to figure this out? </p>

答:
The "buy vs build" decision comes down to a number of factors.  Can you maintain the tool that you are buying (even if it's open-source)?  Is there adequate support for it, if you run into a problem?  Do you have the resources to build it yourself, and are you smart enough to generalize it so it can be reused in a variety of scenarios?  And so on.

Regarding dependency injection: DI containers are not needed for most applications.  Unless your application is a large, enterprise-type application, you don't need a DI container, and if you do need one, there are a number of containers already available that would serve the purpose well.

Smaller applications benefit more from a simpler form of DI, like injecting your dependencies directly through the constructor methods of your objects.  You would only use a DI container if you needed to provide a central place to manage your dependencies in, say, an XML file describing them.

In the vaguest of terms, there is a "rule of three." If you find yourself doing the same thing three times in a software application, you either refactor it into its own tool or method, or find an off-the-shelf tool that replaces those three things with one generalized thing.  Knowing when to do this comes with experience.

ContentLicense: CC BY-SA 3.0


答:
To really understand a tool, I do like to create my own version of said tool. It helps me understand what the tool is actually doing and the hard parts of the problem it is trying to solve. Understanding those things can help you make better decisions about how to use the tool.

That being said I would rarely recommend using the roll-your-own over the tool in a real project. A few reasons for this are:

Your version has only had you use and test it

It's hard to hire people that have knowledge of your custom tool

You're the only person who can fix it if there's a problem

Title: When to use tools vs custom development?

Body:
To learn dependency injection in a current side-project, I am writing my own dependency injection container. </p>

<p>But this has lead me to wonder, at what point is it worthwhile to use a third party product vs "roll my own"? What would be the kind of questions you would ask to figure this out? </p>


答:
Weigh time constraints versus specific project needs. Does the
    tool do exactly everything you need it to, or is it worth the extra
    x amount of hours required to complete your custom solution?

If this is a group project: Licensing cost. Is there room on your departments budget to afford allocating resources towards developing an in-house solution? Internal projects take a long time - and therefore cost money.


问:
Linked list clarification
This is a pretty simple question but I'm new to java.

The linked list found in java.util.LinkedList.

I saw elsewhere that Java does not use pointers...

When I create a new list and add new elements to it, does the list contain references to the data and to the next/previous elements or does it also contain the object itself.

答: You can check out the OpenJDK LinkedList implementation on GrepCode.  The LinkedList class itself contains a reference to an Entry named header, which contains references to two more Entry objects for the next and previous elements in the list.

Title: Linked list clarification


问:
How many programming languages is a programmer expected to be an expert at?
Do most programmers specialize on a single stack, leaving other things be, or are they expert at multiple languages at the same time? If it's more than one, how many is standard?

By expert, I mean more than simply knowing the syntax of a language - an expert knows enough of standard libraries, tools, environments and syntax to be able to write non-trivial programs without having to constantly look things up or read books/tutorials.

答:
You have a very interesting question:

I dont think that any programmer should be an "expert" on a specific language. My believe is that as programmers we are meant to be experts at programming, designing algorithms, thinking in clear steps, but a programming language is something that you just learn.

A "good" programmer, by good I mean that handles development projects without scaring behind the classic "I've never worked with that before", should learn a language in less than 5 working days. You learn best practices, tools and libraries mainly from 2 ways, 1: reading and 2: working. Either you bounce your head against the code or read a bunch of books.

In a few years following the premisse of "Good programmers write just code" no C# code or C++ code or Java code, you will realize that after you learn to develop programs, the language and the techonologies are not that important. Sure, you'll know how to move around C# better than PHP, but if you've learnt well, you'll find you'll way through Python if you have to.

Hope my ideas like you!

ContentLicense: CC BY-SA 2.5


问:
How to document the high-level structure of a Java program?
Background:
My collaborators and I are writing an article for an academic journal.
In the course of our research,
we wrote a simulation program in Java.
We want to make the simulation program freely available for others to use.
We have decided on hosting the code on a GitHub repository.
In order to make it easy for others to use,
we want to write good documentation for our program, including:

Javadocs for each class and method

How to use the code

Describing the high-level structure of the code

My high-level question is:
Could you provide a good example of the words and diagrams
    that can be used to describe the high-level structure of a program?
This includes as sub-questions:

How do we show what classes are contained in which packages?

How do we show what packages depend on other packages?

How do we show how the objects/classes in the program work together?

We have tried to use domain-driven design principles
in the design of my code.
How do we show the correspondence between the objects in the domain
and the particular source code files encoding these objects?
(See my "ubiquitous language" description of the project below.)

What I have done so far

Ubiquitous language

We put a "ubiquitous language" description of the code
in a file ubiquitous-language.md,
contents below.

The purpose of this project is to study how well a replenishment policy
performs in a simple supply chain with a single facility,
under different lead time models, report delays and demand models.

In each period, the following events occur:

If a shipment is scheduled to arrive at the facility at the
current period, then the inventory level of the facility is
incremented by X units.

If the schedule indicates that the current period is a reporting
period, then the facility submits a report to the
supplier.  The supplier may receive the report
instantaneously, or with a delay of several weeks, as specified by
the schedule.

If the supplier has received a report, then based on the
replenishment policy, it will calculate a replenishment
quantity of X units.  A shipment of X units of the product will
be scheduled to arrive after a lead time of l periods.

Customers arrive at the facility and demand X units of the
product.  Any unmet demand is lost.

Source Code Structure

We put an incomplete "high-level" description of the code
in a file structure.md,
contents below.

Package Level Structure

At the highest level, the source code is organized into three packages

com.gly.sfs
The main class with the main method resides in this package.

com.gly.sfs.model
The domain model classes reside in this package.

com.gly.sfs.util
Helper classes reside in this package.

答:
If you're having difficulty describing things like how the high-level structure of your program works, and how the classes work well together, consider the following maxim:

```<code>A picture is worth a thousand words.
</code>```

The way you paint a picture about code is to provide code examples.  Lots of them.  This is how you create a new customer (code).  This is how you process an order (code).  Not only does this give the consumer of your code a place to start, it illustrates how all of the objects connect together and interact.  If I were using your code, the biggest favor you could do me is to provide lots of code samples.

The way you paint a picture for an end-user is to provide screenshots.  Lots of them.  Screenshot after screenshot that illustrates, if you want to do this task, this is what you do first, this is what you do next, etc.

Body:
If you're having difficulty describing things like how the high-level structure of your program works, and how the classes work well together, consider the following maxim:

A picture is worth a thousand words.

The way you paint a picture about code is to provide code examples.  Lots of them.  This is how you create a new customer (code).  This is how you process an order (code).  Not only does this give the consumer of your code a place to start, it illustrates how all of the objects connect together and interact.  If I were using your code, the biggest favor you could do me is to provide lots of code samples.

The way you paint a picture for an end-user is to provide screenshots.  Lots of them.  Screenshot after screenshot that illustrates, if you want to do this task, this is what you do first, this is what you do next, etc.


答: UML, while often used to model software before it is created, could be useful. There are several different diagrams that illustrate use-cases, class-interactions, etc. etc. You can see more about it here.</p>

Title: How to document the high-level structure of a Java program?

Body:
Background:
My collaborators and I are writing an article for an academic journal.
In the course of our research,
we wrote a simulation program in Java.
We want to make the simulation program freely available for others to use.
We have decided on hosting the code on a GitHub repository.
In order to make it easy for others to use,
we want to write good documentation for our program, including:

Javadocs for each class and method

How to use the code

Describing the high-level structure of the code

My high-level question is:
Could you provide a good example of the words and diagrams
    that can be used to describe the high-level structure of a program?
This includes as sub-questions:

How do we show what classes are contained in which packages?

How do we show what packages depend on other packages?

How do we show how the objects/classes in the program work together?

We have tried to use domain-driven design principles
in the design of my code.
How do we show the correspondence between the objects in the domain
and the particular source code files encoding these objects?
(See my "ubiquitous language" description of the project below.)

What I have done so far

Ubiquitous language

We put a "ubiquitous language" description of the code
in a file ubiquitous-language.md,
contents below.

The purpose of this project is to study how well a replenishment policy
performs in a simple supply chain with a single facility,
under different lead time models, report delays and demand models.

In each period, the following events occur:

If a shipment is scheduled to arrive at the facility at the
current period, then the inventory level of the facility is
incremented by X units.

If the schedule indicates that the current period is a reporting
period, then the facility submits a report to the
supplier.  The supplier may receive the report
instantaneously, or with a delay of several weeks, as specified by
the schedule.

If the supplier has received a report, then based on the
replenishment policy, it will calculate a replenishment
quantity of X units.  A shipment of X units of the product will
be scheduled to arrive after a lead time of l periods.

Customers arrive at the facility and demand X units of the
product.  Any unmet demand is lost.

Source Code Structure

We put an incomplete "high-level" description of the code
in a file structure.md,
contents below.

Package Level Structure

At the highest level, the source code is organized into three packages

com.gly.sfs
The main class with the main method resides in this package.

com.gly.sfs.model
The domain model classes reside in this package.

com.gly.sfs.util
Helper classes reside in this package.


问:
UX designers working one Sprint ahead
Our UX designers usually have a story in Sprint X that the developers will implement in Sprint X+1 (The UX designers and the devs/testers are on one team). I think this makes sense because if you don't have screen mockups and clear specifications you can't really estimate the work during Sprint Planning.

However in Scrum you are only supposed to have user stories that provide value to the user. In our case the UX design stories don't provide such value (they are more like a backlog grooming activity). Also usually Scrum coaches don't recommend having complete specifications before the start of the Sprint, a recommendation which I find hard to understand.

So do you see any disadvantages in our approach? It seems to work for us, but it goes somewhat against Scrum principles.

答:
There are two issues here, one about user centered design and the other about sprint alignment.

First: User stories should be aligned with user needs, not just backlog. The UX stories need to have clear value to users.  This does not require complete specification, and a short statement such as,

"Users will have easier access to account activity on a single page rather than divided between multiple pages"

is amenable and adaptable to various implementations and yet still clear about the value to the user (easier access to account activity).

Second: Sprint alignment. UX designs features in sprint X that developers implement in spring X+1.  In practice, this happens in many shops and sometimes it may be more like implementation in sprint X+2 or X+3.  With a tight nit and experienced team this setup can work. It becomes challenging if you have a new team or new members who are not familiar with the skill sets, preferences, habits, work styles, and tendencies of other members of the team. If you've been working together for less than 6 months this is likely to be an issue.

Take a step back, and reassess. On the positive side you have the UX designers and developers working side by side, which is a boon. Start by making sure that your stories have clear value to users.

Title: UX designers working one Sprint ahead


问:
Adding svn support to our git repo
We have been using SVN for several years.

Recently, we switched over to git, since some members of the organization pointed out that if our SVN server dies our team is toast.

So far, we've got something worked out with the git workflow, however some team members really do not like this git process. They want to simply right-click on a file and then hit SVN Commit (we're using tortoiseSVN) without having to worry about all this pushing and pulling.

I've been asked to provide SVN support for our repository while keeping the git repo (hosted on github) updated. The workflow I'm imagining is that we'll all just do the normal SVN things as before, and then once in awhile I'll just do a push to github to backup our files.

What are some options for using git purely for backup purposes (one person would manage the git repo), while everyone uses the SVN repo?

I've read about git-svn, but it seems like a completely different tool. Perhaps someone can clarify this? If I checked out a svn repo using git-svn, would I be able to operate on it using tortoiseSVN? Or can everyone else use a regular SVN checkout, while I maintain a git-svn checkout?

答:
Most git clients I am aware of can do push on commit for the SVN-style workflow so you can keep git for the modern guys and let the dinosaurs keep their SVN-style workflow without rolling back to SVN.

Having made the same transition myself I would try and fight the dinosaurs as one day git will dwan on them and all will be much better.

Title: Adding svn support to our git repo


答:
I find https://www.websequencediagrams.com/ an extremely useful tool for describing the interaction between components within an application, or between services in a distributed application. It just makes the process of creating and maintaining UML sequence diagrams much easier.

The nice thing is, if you consider each lifeline to be the interface or class in your application (I usually just model the big players), then each line flowing into that class represents a method that you must support.

Additionally, there are some download options to get the image. There are also some easy ways to embed the diagram in a wiki. So it's a great communication tool to describe the interaction between components or services in a system, as well as communicating that with the team.


问:
What are the use cases for these relationship types?

Use Case

What are the use cases for creating a one-to-one relationship where the parent points to the child compared to a child pointing to the parent? If there is no difference, is one preferred over the other?

Example

```<code>+---------+     +-------+       +--------+     +----------+
+ Parent  +     + Child +       + Parent +     + Child    +
+---------+     +-------+  vs.  +--------+     +----------+
+ idChild + --> + id    +       + id     + <-- + idParent +
+---------+     +-------+       +--------+     +----------+
</code>```

I suspect that you'd choose between these relationships depending on which entity is used first in the application. i.e. If the parent object always appears before the child object, then the relationship should be mapped from the parent to child.

答:
It can effect the representation of your structure if you marshal it to XML or JSON. For example, do you want "parent" to be the top element or object, or do you want "child" to be the top element or object?

A lot of times it depends on how the application uses the data. If the primary users of a system are children, it may be more convenient to represent child -> parent because you're doing the lookup starting with the child ID.


问:
Should one create underlying architecture to increase flexibility - in advance or when needed?
In this question I asked: Is the cost of designing more levels of abstraction to allow loose coupling worth the benefits, or not?

People said that it's often worth the cost, but one should sense whether his/her application will actually be using this underlying design later on, or if it's just going to be a waste of time.

My new question is:

Should one create the infrastructure to allow flexibility and maintainability in advance - thus making the development 'cleaner' and more 'organized', as things are developed on existing infrastructure and abstraction levels?

With this approach, you desing the underlying infrastructure while not having much knowledge on how things will actually be implemented later. Thus, you might be coding things that might not be used later, and waste your time. But, the development will be cleaner and more organized.

Or should one create infrastructure to increase flexibility and make things more loosely coupled, during the implementation of something - thus wasting less time on things that might not actually be used later?

This approach prevents you from coding things that won't be used, but forces you to design underlying abstraction levels and designs for existing code, thus modifying existing code, instead of coding the underlying designs before coding the code that uses these designs.

Example for approach 1: "Okay, now we start making this relatively large part of the application. This part will generally have to do with reacting to a couple of GUIs. Let's make an underlying level of abstraction for this part of the program, to later use when we implement it."

Example for approach 2: "Okay, I'm in the middle of designing this part of the program. While working on it, I see this part better be loosely coupled. Let's make another level of abstraction to allow it, and modify this code to use that level of abstraction".

Which approach makes more sense, or is more common?

答:
The Python community has this wonderful artifact: "Guido's Time Machine". That is, many marvel at Guido Van Rossum's foresight in setting up syntax and mechanisms in Python that just proved to work very cleanly and intuitively over time.

Not everyone has a time machine, though, and anticipating requirements can be tricky.

In agile, the rule is "program close to the requirements". In TDD it's "the simplest solution that works."

However, there's a balance between brute force implementation, and abstracting to anticipate future requirements.

IMHO it's important to a) keep an eye out for nice abstractions to provide for clean, flexible, extendible code, and b) watch out for turning your project into a swamp of over-generalized infrastructure that doesn't actually do anything.

A lot of time, I'll work on the broad-minded stuff in my spare time in my side projects. But I still wince in meetings when an engineer, at any level of experience, gets excited about some mechanism that's going to Solve the World's Problems.

At the end of the day, make sure you're putting functionality in front of customers. But keep your powers of abstraction sharp with targeted application.


答:
However in Scrum you are only supposed to have user stories that
  provide value to the user. In our case the UX design stories don't
  provide such value (they are more like a backlog grooming activity).

The way I see it, they are providing lots of value to their user. The thing is: their user is not the company's final user, their user is the development team that will implement the feature at sprint X+1.

Title: UX designers working one Sprint ahead

Body:
Our UX designers usually have a story in Sprint X that the developers will implement in Sprint X+1 (The UX designers and the devs/testers are on one team). I think this makes sense because if you don't have screen mockups and clear specifications you can't really estimate the work during Sprint Planning.

However in Scrum you are only supposed to have user stories that provide value to the user. In our case the UX design stories don't provide such value (they are more like a backlog grooming activity). Also usually Scrum coaches don't recommend having complete specifications before the start of the Sprint, a recommendation which I find hard to understand.

So do you see any disadvantages in our approach? It seems to work for us, but it goes somewhat against Scrum principles.


答:
Frankly, both.

It's neigh impossible to add in abstraction layers after all of the code is written and tied together in dozens of places. Sadly, it's also neigh impossible to get all of the abstraction layers just right without actually doing it and seeing where things go.

So in practice, you end up doing both. You add some abstraction in at the beginning, trying to toe the line between being flexible and over-engineering. You create flexibility where it's very likely to be necessary, or where it'd be catastrophic should you be wrong in your guess. Long story short, you mitigate risk.

And then, you add or remove abstraction over time. Refactoring is key to making code "fit". Sometimes you find that things are way too complex. Sometimes you find that things are too coupled. Clean it up over time.

This sort of feel for how much is "enough", and where that abstraction lies is the key skill that develops over time as you make designs and see how they succeed (or more often, fail).

Title: Should one create underlying architecture to increase flexibility - in advance or when needed?

Body:
In this question I asked: Is the cost of designing more levels of abstraction to allow loose coupling worth the benefits, or not?

People said that it's often worth the cost, but one should sense whether his/her application will actually be using this underlying design later on, or if it's just going to be a waste of time.

My new question is:

Should one create the infrastructure to allow flexibility and maintainability in advance - thus making the development 'cleaner' and more 'organized', as things are developed on existing infrastructure and abstraction levels?

With this approach, you desing the underlying infrastructure while not having much knowledge on how things will actually be implemented later. Thus, you might be coding things that might not be used later, and waste your time. But, the development will be cleaner and more organized.

Or should one create infrastructure to increase flexibility and make things more loosely coupled, during the implementation of something - thus wasting less time on things that might not actually be used later?

This approach prevents you from coding things that won't be used, but forces you to design underlying abstraction levels and designs for existing code, thus modifying existing code, instead of coding the underlying designs before coding the code that uses these designs.

Example for approach 1: "Okay, now we start making this relatively large part of the application. This part will generally have to do with reacting to a couple of GUIs. Let's make an underlying level of abstraction for this part of the program, to later use when we implement it."

Example for approach 2: "Okay, I'm in the middle of designing this part of the program. While working on it, I see this part better be loosely coupled. Let's make another level of abstraction to allow it, and modify this code to use that level of abstraction".

Which approach makes more sense, or is more common?


问:
Is better Show() + Hide() or SetVisible(bool visible)?
What is better and why? (From interface-design point of view) :

a) To have two Show() and Hide() functions

b) To have one SetVisible(bool visible) function

EDIT: For example some object have visibility state and this functions is used to change it.

c) To have all three Show(), Hide(), SetVisible(bool visible) functions

答:
It depends on what showing and hiding means in the context. First you want to figure out which one is your "main way", and focus on developing that:

Reasons to pick setVisible(bool)

It is just a simple bit-flip, or your object is mainly holding state

Your object is going to spend most of its time in a CRUD framework

There is a lot of easily-shared code between showing and hiding

Reasons to pick show() and hide()

There are a important side-effects or lots of logic being run, such as when the object has to check all of its containers for their visibility state, or triggers a transition animation.

Is it part of a domain model where expressing intent is important

OK, so now that you've coded the "gold standard" core of it, you need to figure out whether it it worth adding thin convenience-methods in the other style, to make life easier for whomever is going to use your object.

Convenience of setVisible(bool)

Lets you avoid if-statements that have trivial conditions and only affect visibility (ex. setVisible(a==b))

Can be wired into certain getter/setter frameworks, if that's somethign you expect to happen

Convenience of show() and hide()

Useful in a language with first-class functions and callbacks (ex. onSuccess(widget.show))

Much easier to read with stack-traces and performance profiling, since you can quickly see what the program was trying to do

TLDR: Find out which one is most important, implement it, and then ask yourself whether it's worth adding the other style as thin convenience methods.


问:
reloading singleton classes and dependency
I have a singleton object.  It's a DAO that looks somewhat like this (pseudoish code):

```<code>class UsersDAO {
  public usersDAO init(string sDSN){
    variables.sDSN = sDSN;

    return this;
  }

  public array getUsers(){
    //do a query to get users, make into array

    return aUsers;
  }
}
</code>```

my applications makes an instance of this and uses it throughout the codebase, but I also have another DAO that requires it:

```<code>class OrganisationsDAO {
  public OrganisationsDAO init(UsersDAO oUsersDAO,string sDSN){
     variables.sDSN = sDSN;
     variables.oUsersDAO = oUsersDAO;

     return this;
  }

  public array getUsersOrganisations(){
    variables.aUsers = variables.oUsersDAO.getUsers();

    //getOrganisations for the returned users

    return aOrganisations;
  }
}
</code>```

so to make the OrganisationsDAO object I need to pass it the UsersDAO.

At a later point in my applications life, I need to update the UsersDAO to include a public user getUser(int userid) function.

I'm wondering, is there a way of passing through the new UsersDAO to objects that depend on it, without having to restart the application.  In this instance the application is a website rather than a desktop based application.

答:
Don't pass an object to the client classes. Pass a function that gives them the object they need (a factory, a provider). Convince them that calling this function is cheap, because it immediately returns a cached value when possible, so that they don't keep their own long-lived cached values.

Do away with variables.oUserDao and replace it with some variables.oUserDaoProvider. Then something likevariables.oUserDaoProvider.getDao().getUsers() allows you to control what getDao() returns from the outside, while your clients always get the correct DAO.


问:
Where should CMS data logic go
We have a large web site written in WebForms and have begun implementing some new modules in MVC. We have a custom CMS in place. I put the data structure to hold CMS data in a BaseModel class. Now I`m wondering where would be the best palce to put the logic which calls the CMS data manager to get data relevant to the page.

On one hand, I can create a BaseModel, which in its constructor receives a page Id, and calls the CMS manager. Then build all models on that model.

On the other hand, I can do the same in a BaseController.

I can't decide which is more correct, since I cannot think of any advantage one will have over the other. Most of my experience is in WebForms, so I am wondering what would be the more ASP.NET MVC way of placing this logic.

答:
As with many options, both would work. Between those two I think the base controller is the more correct option. The "models" you tend to see in MVC projects these days are leaner with just properties and few to no methods.

If you want a more correct alternative, consider putting this logic in a separate "repository" class.  This way you can keep the controller code lean as well. Download this sample mid-sized ASP.Net MVC sample solution which is a good tutorial on how the repository pattern can be implemented. See how the Student model is populated using the StudentRepository.

Sample ASP.NET MVC Repository Pattern Solution

OwnerDisplayName: Elad Lachmi

Title: Where should CMS data logic go

OwnerDisplayName: James Lawruk


答:
I prefer show() and hide(), in fact, every method that receive one boolean can be changed for two methods tan express better the intention of the API. For example Robert Martin in clean code recommend prefer methods wit zero arguments over methods with one argument.

Another important argument for me is readability, in my opinion good code can be read like prose, its really strange prose something like "main_window setVisible false" instead of "main_window hide", you write or talk like that normally?, why use this strange language construction in software programs when is perfectly possible use a more natural language?.

Title: Is better Show() + Hide() or SetVisible(bool visible)?

Body:
What is better and why? (From interface-design point of view) :

a) To have two Show() and Hide() functions

b) To have one SetVisible(bool visible) function

EDIT: For example some object have visibility state and this functions is used to change it.

c) To have all three Show(), Hide(), SetVisible(bool visible) functions


问:
Do RESTful APIs tend to encourage anemic domain models?
I'm working on a project in which we are trying to apply both domain-driven design and REST to a service-oriented architecture. We aren't worrying about 100% REST compliance; it would probably be better to say we are trying to build resource-oriented HTTP APIs (~Level 2 of Richardson's REST maturity model). Nevertheless, we are trying to stay away from RPC-style use of HTTP requests, i.e. we attempt to implement our HTTP verbs according to RFC2616 rather than using POST to do IsPostalAddressValid(...), for example.

However, an emphasis on this seems to be at the expense of our attempt to apply domain-driven design. With only GET, POST, PUT, DELETE and a few other rarely used methods, we tend to build CRUDdy services, and CRUDdy services tend to have anemic domain models.

POST: Receive the data, validate it, dump it to the database. GET: Retrieve the data, return it. No real business logic there. We also use messages (events) between the services, and it seems to me that most of the business logic ends up being built around that.

Are REST and DDD at tension at some level? (Or am I misunderstanding something here? Are we maybe doing something else wrong?) Is it possible to build a strong domain model in a service-oriented architecture while avoiding RPC-style HTTP calls?

答:
Several reasonably successful implementations I have seen/built answer the question in how they mix the verb+noun metaphor using coarse-grained 'business friendly' methods that act on the entities.

So instead of the (doomed) getName() method/service, expose getPerson(), passing in things like identifier-type/ID, returning the entire Person entity.

Since behaviors of the Person entity in such a context cannot be adequately conveyed (nor perhaps should they be in a data-centric context as this), it is perfectly reasonable to define a data (versus Object) model for the request/response pairs of the service/s.

The services and defined verbs themselves will add some domain-allowed behaviors, controls and even state-transition rules for the entities. For example, there would be domain-specific logic as to what happens in the transferPerson() service call but the interface itself would only define the inputs/output entities/data without defining THEIR internal behaviors.

I would disagree with authors that would say, for example, a transfer verb implementation belongs in the Person class or associated with a Person-centric service. Indeed, the method of transfer for a Person and options thereof (in this simple example) would be better defined by a Carrier, wherein the Person may have no knowledge of even what transfer methods are available or how transfer even takes place (who knows how jet engines work anyway).

Does this make the Person entity anemic? I don't think so.

There can/should be logic about Person-specific things that are internal to Person like their state of health, which should not be defined by an external class.

However, depending on the use-cases, it is entirely acceptable that an entity class have no important/relevant behaviors in certain systems, such as a seat-assignment service in a transport system. Such a system may well implement REST-based services that deal with Person instances and associated identifiers but never define/implement their internal behaviors.

ContentLicense: CC BY-SA 4.0


答:
I disagree with all posters suggesting multiple functions to do the same thing is a good thing. Whilst three functions instead of one may not seem like much bloat, remember that your class is likely to end up with many such functions (e.g. setEnabled, enable, disable) and thus this approach will end up with a much larger class interface. Moreover, it's likely that you'll end up with a bunch of similar sounding functions/properties/whatever in your class and the multiplication of functions will further obscure which one goes with what.

In languages which support properties, these should be preferred but since neither Java nor C++ do, I guess that's a moot point.

I think setVisible() should be preferred for these reasons:

It's immediately obvious what the inverse function is. To reverse setVisible(false) you call setVisible(true) whereas the opposite of hide() could easily be reveal().

It's programmatically simpler whenever you're determining which state it should take in code, i.e. you can call setVisible(wantToSee) rather than using an if statement.

Once you have multiple similar functions the setX() format generalises so you can have a set of consistent functions whereas the verbed approach spawns a host of functions that can be difficult to locate if you don't know what you're looking for. Consistency in APIs makes them considerably easier to learn and remember.


答:
I do believe that the more the method is expressive, the more readable, and consequently, maintainable the code will be. Consider the following two cases:

Case 1:

```<code>void showCustomerData(customerId){
  Customer customer = getCustomer(CustomerId);
  customerPanel.setVisible(customer.isCustomerEnabled());
}
</code>```

Case 2:

```<code>void showCustomerData(customerId){
  Customer customer = getCustomer(CustomerId);
  //always show customer panel
  customerPanel.setVisible(true);
}
</code>```

In the first case, it is clear what the function "setVisible" is doing, but if you want to read it, you would say:

set the customer panel to visible if the customer is enabled or set it
  to hidden if the customer is disabled.

While its more descriptive to say:

check the status of the customer:

if the customer is enabled then show the customer's panel

otherwise, hide it

which will change the "Case 1" function into the following:

```<code>void showCustomerData(customerId){
  Customer customer = getCustomer(CustomerId);
  if(customer.isCustomerEnabled()){
    customerPanel.Show();
  }
  else{
    customerPanel.Hide();
  }
}
</code>```

it produces more code, but is more readable.

The second case has an obvious flaw, which is, you already know that you want to show the panel, so why not use the "Show" function ?

I am not saying that using "setVisible" is absolutely wrong, but it gets confusing when you try to read code not written by you over time, and it does not conform with the "A function should perform only one operation" rule.

Body:
I do believe that the more the method is expressive, the more readable, and consequently, maintainable the code will be. Consider the following two cases:

Case 1:

void showCustomerData(customerId){
  Customer customer = getCustomer(CustomerId);
  customerPanel.setVisible(customer.isCustomerEnabled());
}

Case 2:

void showCustomerData(customerId){
  Customer customer = getCustomer(CustomerId);
  //always show customer panel
  customerPanel.setVisible(true);
}

In the first case, it is clear what the function "setVisible" is doing, but if you want to read it, you would say:

set the customer panel to visible if the customer is enabled or set it
  to hidden if the customer is disabled.

While its more descriptive to say:

check the status of the customer:

if the customer is enabled then show the customer's panel

otherwise, hide it

which will change the "Case 1" function into the following:

void showCustomerData(customerId){
  Customer customer = getCustomer(CustomerId);
  if(customer.isCustomerEnabled()){
    customerPanel.Show();
  }
  else{
    customerPanel.Hide();
  }
}

it produces more code, but is more readable.

The second case has an obvious flaw, which is, you already know that you want to show the panel, so why not use the "Show" function ?

I am not saying that using "setVisible" is absolutely wrong, but it gets confusing when you try to read code not written by you over time, and it does not conform with the "A function should perform only one operation" rule.


问:
User session timeout handling in SaaS apps - discussing several approaches
I know this has a great chance of being marked as duplicate, but couldn't find exactly what I'm looking for

This is a common problem and I'm sure it has some well defined best practice solution

Background

A single page SaaS app, has lot's of drag and drop, user can
interact with it without much server communication for periods of
time

Server session only holds user object, using a non persistent session cookie

Session expires on the server after X hours

Some things are loaded only during log-in

Problem

User works on the app, when done, user doesn't log out, just keeps the browser open

User comes back after more than X hours (session is invalidated on server)

User interacts with the app without needing a server connection (drags and drops things, text edits...)

Only on the next server interaction (let's assume there is no auto save) user is thrown to login page and loses some of their work

Possible solutions

Here are some solutions I have in mind, would like to hear if there are any others, and if there is anything fundamentally wrong with any of them.

1. Never log the user out

How? either keep a long session, keep a persistent cookie, or javaScript "keep alive" ping

Pros: user doesn't need to worry about anything, fixes the problem for them

Cons: not PCI compliant, not secure, and needs development changes, e.g. things loaded to session only on user log in need to move to either a pub sub model (listening on event changes) or have cache timeout.

2. Local Storage

How? use new local storage to temporarily store state if logged out, redirect to login page, persist once logged in

Pros: Also base for "work offline" support, not just handling session timeout

Cons: harder to implement, need to do state merge of data tree, not all browsers support

3. Auto save

Every user action that changes the model, should persist immediately (or via some sort of a client side queue), e.g. if they check a checkbox,  change a text field, or drag and drop something, once they are done, persist the changes.

How? Use an MV** framework (Backbone.js / Knockout.js / Ember.js / Angular.js etc) to bind the model, and persist on changes.

Pros: Seems like a clean solution, session is active as long as user is active, no client side work is done without persisting it.

Cons: The last action user is doing after a session timeout is lost.

4. Log the user out after session expires

this can have several approaches

Ask the server "has session expired" - this is a bit of a catch 22 / Schrodinger's cat, as the mere question to the server extends the session (restarts the timeout),

How? Either have a server that supports such question (I don't know of any, but I come form Java land)  or, one can just keep a table of session IDs, and last access time manually, and ask the server by passing the session ID as a parameter instead of the cookie, I'm not sure if this is even possible, but it sounds dangerous, insecure and bad design whatsoever.login page, persist once logged in

Pros: If there was such native support in servers, sounds like a clean, legitimate question (asking if user X still has a session or not without renewing it if they do)

Cons: If the server doesn't support it (and again, I don't know if any server or framework has this functionality) then the workaround has huge security risks potentially.

One workaround I've heard is have a short session on the server side, and a keep alive client side ping, that has a maximum number of pings

How? Short session on server, client pings every sessionTimeOut/2, has max retries of Y.

Pros: Kind of fixes the problem, quick and dirty

Cons: Feels like a hack, handling the session renewal yourself instead of letting the server do it

Client side timer

How? Have a timer on the client side and sync it with the server one by restarting it on every request to be equal to the max server session timeout minus some padding, after user is not sending any request to the server, UI shows a "sessions is about to time out, do you want to continue?" (like you have on online banking )

Pros: Fixes the problem

Cons: Can't think of any except the need to make sure the sync works

The Question

I'm probably missing something in the above analysis, might have some silly mistakes, and I would like your help to correct them. What other solutions I can have for this?

答:
In my case, I'm using something similar to 4.1. After the user logs in a very lightweight angular driven AJAX json request occurs to the REST API at set intervals against the server. Because of security requirements, the proprietary UI anticipates the server will maintain a session for the user which stores some protected information, templates, data, etc on the server side. This is still my preferred method from a security perspective. When dealing with sensitive data(not just hashed passwords and such), IMO storing it client side in Local Storage, etc poses a greater risk than server side(I'm sure somebody would debate that with me). Third parties use the same API when communicating with the system, but must send authentication credentials on every request.

The session on the server does have a max idle lifetime applied to it, and the session storage engine is memcached(which also has a max lifetime applied at which point the memory session will be marked expired). The lifetime need only be greater than whatever session lifetime you abstract in your application(and doesn't have to be my much). E.G. The session may not expire until it has been idle for 48 hours insofar as the server is concerned, but your code controls the actual lifetime. This could lead to resource issues if that lifetime is too great, and you do a poor job of managing the sessions.

In my case, different users can have different session idle timeouts based on their roles within the organization. The server places maximum limits on the session lifetime but as long as the user defined limits are less than those, it works just fine. Once the server expires the session, it's a moot issue as the session expiration process would have already been handled by the application gracefully. This is a requirement of the kind of business application I built.

Once the users session has been idle and is within an application specified threshold, the API will instruct the UI to display a countdown dialog(like the banks do), and once it is within a specific margin of distance in time from the expiration it gracefully logs the user out. This functionality persists across browser windows(because the server is in control), and an idle event on any window will begin the graceful timer and automated logout process(and keep them in sync).

If by chance the session expires in an ungraceful manner(the sessions get dumped on memcached), the next request that impacts the server will notify the user and move them back to square one(rarely happens, but can).


问:
Does a data-driven application need a database?
This may be a terribly stupid question, but I can't find anything even related on Google (maybe I am not searching properly). I've been a developer for around a year now. I do desktop and web apps using Visual Studio at my day job and use a WAMP setup for freelancing. For storing data I have either used a database or not. What I mean is that if the program stores data for longer than the app runs then I use a database; that's all I know. Here's the thing, I have always worked with existing databases for desktop apps. I have never made a desktop app from scratch (the programming part yes, but the database has just always been there and on a local server somewhere for the app to pull from).

I want to develop a desktop application that would need a database. My question is how does that process work? In providing the application do I supply the database, say SQLserver, or is there another way in which that works?

To be clear: The application would need to store your typical customer information, files, possibly images, payment information - which I know a database would provide, but I do not know how that works once you sell and install the application. I know other applications do these sorts of things - quickbooks, email clients, etc. How do they do it with just an install?

答:
There are lots of ways to persist data in a desktop application.

A database is one choice.  You would probably have to provide an installer unless you're using a file based database such as SQLite.

You might also just write to a file - either a text file, an XML file, serializing objects, etc.

On a side note, while it is possible to store images in a database, it's been my experience that it's more trouble than it's worth.  I tend to write them as files to a folder then track them some other way (database, etc).


问:
Optimal movie schedule
Let's say Mr. A goes to cinema and he gets a movie schedule. There are N movies on the program today (1 < N < 50) and for every movie the time of the start and the time of the end are given in minutes. Mr. A wants to see as much minutes of movies as possible. But, there is one rule in the cinema: If a movie starts, you can't watch it. In other word if Mr. A watches Movie 1 and in meantime Movie 2 starts, Mr. A can't watch it. Find the maximum number of minutes that Mr. A can spend watching movies.

At first I sorted the movies according to their starting time. Then I made a NxN matrix and fill it with false values. Now if Movie X and Movie Y intersect, i.e play in the same time even just for a minute, then Matrix[X][Y] and Matrix [Y][X] get true value. Then I check the case when every movie is in the optimal solution. I put them into vector. Now using recursion I check every possible combination. If Movie X doens't have an intersection with every movie of the vector, I put into the vector, since there will be no intersection and then I move on to the next movie. And so on.

This algorithm works, but I think that it's too much time-consuming and as I want to say it's "modified brute-force". Is there any better way to reach the optimal solution.

NOTE: We are interested only about the maximum numbers of minutes, not in the maximum number of movies. At the end the program should print the maximum number of minutes, not a list of the movies Mr. A should watch.

答:
Sounds like a decision tree to me.

Make a graph.

Start with a root node, then for its children list all the movies that A could watch first.

For each child, store the length of the movie and add nodes for each movie that A could watch after that child's movie ends.  (i.e., you step out of theater 7 at 10:02 am and check the other 49 theaters to see which ones are not currently playing a movie.  Add them as child nodes).

Continue until you read end of day / your graph is fully populated.

Now search your graph for the path with the highest collective minutes (i.e., the sum of minutes for each movie in the path).  There are several well known algorithms for doing this.  DFS comes to mind for me, but I think there are better ones.

---------edit----------

Excellent comment from AMADANON Inc:

You might improve this alogrithm - do breadth first search, and at any time when two or more branches are NOT watching a movie at the same time, all except the one with the most minutes watched so far can be eliminated (in the case of a tie in the number of minutes, all but an arbitrarily chosen one in the tie can be eliminated). This will save lots of processing during the short film festival.

(Comments are sometimes lost, so I'm putting it here)

Title: Optimal movie schedule


答:
My advice is to get people skills up to date.  I would push back against the assignment and say that adopting old work habits and patterns that don't match newer technology and processes is a bad decision for the future of the company and also for the future skills of the employees.

Technology is a constantly and continually evolving and changing.  When new tools and practices become available, a large challenge is to get people to use the new tools in new ways.  This can mean changing long-held beliefs and practices which is hard.

That also makes the challenge of hacing folks change a little easier.  Explain that git, as a DVCS is a new way of working that is quickly supplanting older technology VCSs.  Doing things the 'git' way is likely what they will be doing in a lot of their future jobs.  If they 'do git the svn way' they are likely going to find their next job hard to do.

The move from svn to git is a particularly difficult one.  It's difficult for many reasons including the fact that the same word means quite different (or even opposite) things.

Good git gui tools such as gitx(osx) or gitg(linux) can also help a lot.

You may also find this Q&A on workflow useful:

https://stackoverflow.com/questions/3329943/git-branch-fork-fetch-merge-rebase-and-clone-what-are-the-differences/9204499#9204499

Title: Adding svn support to our git repo

Body:
We have been using SVN for several years.

Recently, we switched over to git, since some members of the organization pointed out that if our SVN server dies our team is toast.

So far, we've got something worked out with the git workflow, however some team members really do not like this git process. They want to simply right-click on a file and then hit SVN Commit (we're using tortoiseSVN) without having to worry about all this pushing and pulling.

I've been asked to provide SVN support for our repository while keeping the git repo (hosted on github) updated. The workflow I'm imagining is that we'll all just do the normal SVN things as before, and then once in awhile I'll just do a push to github to backup our files.

What are some options for using git purely for backup purposes (one person would manage the git repo), while everyone uses the SVN repo?

I've read about git-svn, but it seems like a completely different tool. Perhaps someone can clarify this? If I checked out a svn repo using git-svn, would I be able to operate on it using tortoiseSVN? Or can everyone else use a regular SVN checkout, while I maintain a git-svn checkout?


问:
Can you use Pi as a crude random number generator?
I recently saw this question over at math.SE. It got me thinking. Could Pi be used as a crude random number generator? I mean the results are well known(how long has pi been computed to now?) but, Pi does seem to be quite random when taken 1 digit at a time. </p>

<p>Does this make any sense at all? </p>

答:
The randomness of digits of pi (or for that matter any other sequence) can be arguably tested by so-called 'battery tests'. One popular battery test is George Marsaglia's Diehard Battery Test. There is also NIST Special publication 800-22 that describes a number of such tests and the results of applying these tests to a number of physical constants, including - lo and behold - pi for over a million bits. The result of pi is given in Appendix B of the report and looks like this: </p>

```<code>Statistical Test                            P-value
Frequency                                   0.578211
Block Frequency (m = 128)                   0.380615
Cusum-Forward                               0.628308
Cusum-Reverse                               0.663369
Runs                                        0.419268
Long Runs of Ones                           0.024390
Rank                                        0.083553
Spectral DFT                                0.010186
Non-overlapping Templates (m = 9, B = 000000001)          0.165757
Overlapping Templates (m = 9)               0.296897
Universal                                   0.669012
Approximate Entropy (m = 10)                0.361595
Random Excursions (x = +1)                  0.844143
Random Excursions Variant (x = -1)          0.760966
Linear Complexity (M = 500)                 0.255475
Serial (m = 16, 2m∇Ψ )                      0.143005
</code>```

<p>Is pi a good random sequence generator? Look at the above results (or search the meanings of the left column variable, if you have no idea what they mean), and check if it satisfies your need. </p>

Body:
The randomness of digits of pi (or for that matter any other sequence) can be arguably tested by so-called 'battery tests'. One popular battery test is George Marsaglia's Diehard Battery Test. There is also NIST Special publication 800-22 that describes a number of such tests and the results of applying these tests to a number of physical constants, including - lo and behold - pi for over a million bits. The result of pi is given in Appendix B of the report and looks like this:

Statistical Test                            P-value
Frequency                                   0.578211
Block Frequency (m = 128)                   0.380615
Cusum-Forward                               0.628308
Cusum-Reverse                               0.663369
Runs                                        0.419268
Long Runs of Ones                           0.024390
Rank                                        0.083553
Spectral DFT                                0.010186
Non-overlapping Templates (m = 9, B = 000000001)          0.165757
Overlapping Templates (m = 9)               0.296897
Universal                                   0.669012
Approximate Entropy (m = 10)                0.361595
Random Excursions (x = +1)                  0.844143
Random Excursions Variant (x = -1)          0.760966
Linear Complexity (M = 500)                 0.255475
Serial (m = 16, 2m∇Ψ )                      0.143005

Is pi a good random sequence generator? Look at the above results (or search the meanings of the left column variable, if you have no idea what they mean), and check if it satisfies your need.


问:
Can I use GPLd code I wrote on the job as code samples without permission?
I'm currently employed by a business to do website development in Wordpress. I've written a number of custom plugins specifically for a number of clients over the time of my employment.

Today, I asked my boss what I would be allowed to use as code samples because I'm quitting. My boss has forbidden me from taking any of the custom plugins I coded (which is all of the programming work I've done). However, all of those custom plugins I coded are currently licensed under the the GPL (though they were never released or shared).

If I was to take this custom code that I wrote under the GPL (but never released) and provide it as code samples anyway, would my current employer be able to take any kind of legal action against me?

答:
Insert normal lawyeresqe disclaimer here.

With that out of the way, your current employer would have a case against you. The GPL, or any copyright license for that matter, comes into play only when the work is redistributed. As your plugins have not yet been distributed, they are not really subject to the GPL, or any other license for that matter.

Until your employer authorizes the work to be released under the terms of the GPL, it's not written "under" anything, and so you do not yet have permission to release it.

Even if your plugins were utilizing GPL software, and being a derivative work, had to be released under the GPL if they were to be released at all, it is still up to the copyright owner of the derivative work whether or not to redistribute.

There is no requirement in the GPL that derivate works utilizing GPL software have to be redistributed, it only dictates terms that must be adhered to in the event that it is.


问:
Programmers forgetting syntax
Do good programmers need to have syntax at the tip of their tongue when writing code? What do you make of them if they google for simple stuff online?  Are they good or bad(maybe they know where to look for)? Should programmers have a good memory? Is this a trait for a good programmer?</p>

答:
My philosophy on programming is that it's a "state of mind" and the rest is "just syntax."  (i.e. not (as) important)

That said, one shouldn't have to look-up the simple stuff.  At least, not for the language(s) you work with regularly.  There's nothing wrong with needing refreshers and knowing how to find information is certainly a good skill to have.  However, the core syntax should definitely be well known.  Otherwise, you spend too much time searching and too little time programming.

Title: Programmers forgetting syntax


问:
What is the difference between collation and character set?
I have a general question about databases. We usually use the term collation with databases. I would like to know how its different from character set. I guess collation is a subset of character set. If its true, what is the purpose multiple collation under a character set.</p>

答:
As the previous answer, character set is a set of characters (letters, numbers, ideograms etc.) assigned to a number; to be able to see them, you must have the font (the small "pictures" we read). They were important using LatinX, because for each X, the same number (byte) could refer to a different character.

Nowadays it's more important to select the encoding: the standard is UTF-8, the most successful representation of Unicode (compatible with ASCII but so flexible to include all language, even Chinese and Japanese) and W3C standard. In other words, it includes all character sets.

Collation: this is an old-fashion word, derived from Latin. It means: compare a copy (manuscript) with the original to find differences (errors or changes). It was very useful in the past, but now it's almost an archaicism because our documents and books are written using computers and the copy is always identical to the original. Example: in Italian (derived from latin) there is the verb "collazionare", but it's in the dictionaries and nobody uses it.

So, the collation defines the behaviour of comparison operators: =, >, <, <=, >= ...

Of course those operators are used to decide if two strings are the same, or if a word is "greater" than another one, very important if we want to sort.
The letters are not in the same order for every language, so a word can be greater than another one using a collation, but not using another one. See [1] for a practical example.

the "bin" collations are the most strict: SELECT "b" = "B" => FALSE

the "ci" collations are not case sensitive: SELECT "b" = "B" => TRUE

the "general" tend to ignore some differences: SELECT "a" = "à" => TRUE

other are specific for one or more languages. Example "swedish" (I don't know why swedish is often a default)

I am still searching for a website where the behaviour of every collation is described in detail... those examples are due to my experience.

[1] http://www.olcot.co.uk/sql-blogs/revised-difference-between-collation-sql_latin1_general_cp1_ci_as-and-latin1_general_ci_as


问:
Why aren't databases integrated as a language feature?
Are there any programming languages that have a built-in database as a first-class language feature rather than connecting to an external SQL (or other) database? What would be the drawbacks and benefits to such a feature? What would such a feature look like and how would it change the way we program?</p>

答:
There are 3 legacy systems that are close to your requirements:

Pick,

MUMPS,

Microsoft Access

Pick and MUMPS were developed years before the first academic paper on relational databases (which was about a decade before the first commercial SQL based database system made it to the market - from a company we now call Oracle; IBM's first attempt at a product fizzled and a successful SQL based system was later). You might find them still in use (our local public transport system used Pick until recently for the trip planning system). You want nothing to do with either Pick or MUMPS, and the best advice I can give is "step away from the keyboard with your hands in the air!" If you do have anything to do with them, the phrase "you'll be sorry" should be ringing in your ears.

Microsoft Access gets severely mocked and criticized in IT circles as it is quite easy for a non-developer to make a critical business app out of Access and have it mutate into something that the company quite literally cannot live without. It is also quite likely that quite a few developers got their start in developing via MS Access and as things kept getting bogged down they learned how to fix them (the first step is traditionally learning visual basic and rewriting the Access app first in VB, then in something "better"). It is possible to make a well behaved Access app that runs distributed with a huge amount of data - I've seen it done - but there are easier ways to do things, and it takes far less skill to make (and maintain) a well behaved app out of VB and SQL Server.

Since SQL Server 2005, Microsoft has introduced the capability to put CLR into stored procedures and functions. And if you want to be tricky about it, you could make datatypes that you could then use as columns in the database. I think Oracle has had something similar with Java.

That being said, I don't think there is anything stopping you from creating one, or hypothesizing about them. Pick and MUMPS are older than most coders here and reflect a very COBOLy way of looking at the world.

My personal advice is to keep things separate. Use a language that is good at manipulating the data your project needs (with the caveat that sometimes the "best" language is one that you can easily find programmers who can read/write the code). Use a database system that is good at keeping the data your project needs.


问:
Can one determine the creation date of an email account?
Is it possible to determine the creation date of the mail account for the address supplied within the authentication process flow; Or at least determine that the mail account was/was not created the same day as signup (or specifically after confirmation)?

A use case is to flag such accounts for closer scrutiny as part of a risk management system.

What general considerations do you think come into play in approaching this problem?

I imagine that solutions might be specific to different email providers but if I could determine this information for the major ones it's a good place to be.

Would love specific answers in any language or pseudocode assuming this is solvable within ethical principles.

Disclaimer: I have asked this question on Stack Overflow. Some nice person said that email providers would not allow it for privacy reasons. Completely acceptable, but IMHO I think that the age of an email account has little to do with personal privacy. Also there are too many smart people using the stack* forums for me to just lie down and die.

答:
In general, no. SMTP is a protocol with a fixed set of information that can be exchanged, and "How long has this address been active?" is not among that information. (In fact, due to the continuing battle between mail infrastructure providers and spammers, it is getting progressively harder to get reliable answers to the much simpler question "Is this address deliverable?", even though this one is supposed to be answerable.)

That doesn't mean you couldn't find the answer in many cases depending on the details of the entity who is actually providing the ail service. Obviously, if you have control over it yourself, you can query the creation date easily. For public providers, there may be traces of the time when the domain an email uses was registered; many common internet stacks incidentally disclose more information than they are supposed to, and it may be possible to deduce something from that. What probably doesn't exist is a general way that works for all email addresses.


问:
Should I use HTTP search
I am working on a web api and I am curios about the HTTP SEARCH verb and how you should use it.

My first approach was, well you could use it surely for a search. But asp.net WebApi doesn't support the SEARCH verb.

My question is basically, should I use SEARCH or is it not important?

PS: I found the SEARCH verb in fiddler2 from telerik.

答: AFAIK the SEARCH method is only a proposal and should not be used. Use GET instead.

Title: Should I use HTTP search


答:
It depends on what you mean, but the short answer is yes.

Are programmers going to forget a semi-colon or a brace here and there? Sure. Are they going to look up the syntax of a switch statement because they probably rarely use it? Well, I do. Will I be working with ActionScript but write it like Java instead? Definitely. It can take some time getting used to typing in a new language, especially if you've worked with a different one for years.

The real concern should be if a programmer cannot make heads or tails of the syntax even with an IDE helping them out. If the person doesn't know what a semi-colon is for, or what those fancy curly braces are, then they have more studying to do.

Title: Programmers forgetting syntax

Body: Do good programmers need to have syntax at the tip of their tongue when writing code? What do you make of them if they google for simple stuff online?  Are they good or bad(maybe they know where to look for)? Should programmers have a good memory? Is this a trait for a good programmer?</p>


问:
What is the best way to work with large databases in Java depending on context?
We are trying to figure out the best practice for working with very large DBs in Java.

What we do is a kind of BI (business Intelligence), i.e analyzing very large DBs, and using them to create intermediate DBs that represent intelligent knowledge of the DBs.

We are currently using JDBC, and just preforming queries using a ResultSet.

As more and more data is being created, we are wondering whether more appropriate ways exist for parsing and manipulating these large DBs:

We need to support 'chunk' manipulation and not an entire DB at once(e.g. limit in JDBC, very poor performance)

We do not need to be constantly connected since we are just pulling results and creating new tables of our own.

We want to understand JDBC alternatives, with respect to advantages and disadvantages.

Whether you think JDBC is the way to go or not, what are the best practices to go by depending on context (e.g. for large DBs queried in chunks)?

答:
Yes if your datebase is large ,You can use partitioning for storing this data.And as above said do not fire single query for fetching data for small comparison or analysis operations.

Divide your logic such way that easy filtering criteria handled by stored procedures and query itself and only complex algorithm which may be not supported by sql query or supported procedure should be done with java after record fetching.


问:
How do searches fit into a RESTful interface?
When designing a RESTful interface, the semantics of the request types are deemed vital to the design.

GET - List collection or retrieve element

PUT - Replace collection or element

POST - Create collection or element

DELETE - Well, erm, delete collection or element

However, this doesn't seem to cover the concept of "search".

E.g. in designing a suite of web services that support a Job Search site you might have the following requirements:

Get individual Job Advert

GET to domain/Job/{id}/

Create Job Advert

POST to domain/Job/

Update Job Advert

PUT to domain/Job/

Delete Job Advert

DELETE to domain/Job/

"Get All Jobs" is also simple:

GET to domain/Jobs/

However, how does the job "search" fall into this structure?

You could claim it's a variation of "list collection" and implement as:

GET to domain/Jobs/

However, searches can be complex and it's entirely possible to produce a search that generates a long GET string.  That is, referencing a SO question here, there are issues using GET strings longer than about 2000 characters.

An example might be in a faceted search - continuing the "job" example.

I may allow for searching on facets - "Technology", "Job Title", "Discipline" as well as free-text keywords, age of job, location and salary.

With a fluid user interface and a large number of technologies and job titles, it is feasible that a search could encompass a large number of facet choices.

Tweak this example to CVs, rather than jobs, bring in even more facets, and you can very easily imagine a search with a hundred facets selected, or even just 40 facets each of which are 50 characters long (e.g. Job Titles, University Names, Employer Names).

In that situation it might be desirable to move a PUT or POST in order to ensure that the search data will get correctly sent.  E.g.:

POST to domain/Jobs/

But semantically that's an instruction to create a collection.

You could also say you'll express this as the creation of a search:

POST to domain/Jobs/Search/

or (as suggested by burninggramma below)

POST to domain/JobSearch/

Semantically it may seem to make sense, but you're not actually creating anything, you're making a request for data.

So, semantically it's a GET, but GET isn't guaranteed to support what you need.

So, the question is - Trying to keep as true to RESTful design as possible, whilst ensuring that I'm keeping within the limitations of HTTP, what is the most appropriate design for a search?

答:
I generally use OData queries, they operate as a GET call but allow you to restrict the properties which are returned and filter them.

You use tokens such as $select= and $filter= so you will end up with a URI which looks something like this:

```<code>/users?$select=Id,Name$filter=endswith(Name, 'Smith')
</code>```

You can also do paging using $skip and $top and ordering.

For more information, check out OData.org. You haven't specified which language you are using, but if it's ASP.NET, the WebApi platform supports OData queries - for others (PHP etc) there are probably libraries you can use to translate them into database queries.

Body:
I generally use OData queries, they operate as a GET call but allow you to restrict the properties which are returned and filter them.

You use tokens such as $select= and $filter= so you will end up with a URI which looks something like this:

/users?$select=Id,Name$filter=endswith(Name, 'Smith')

You can also do paging using $skip and $top and ordering.

For more information, check out OData.org. You haven't specified which language you are using, but if it's ASP.NET, the WebApi platform supports OData queries - for others (PHP etc) there are probably libraries you can use to translate them into database queries.


问:
Next steps for developing new product
I was hired about a year ago as the lead (well, really the only) developer on a new project/product we will call product "B". Product B was designed to pursue a new market for the company.

This company has had great success with a similar product for a different market. We will call this other product "A".

“A” is almost 5 years old now and is reliable.

The two markets don’t necessarily overlap, but a lot of the core functionality in A could be re-purposed to work for B.

My deadline to pursue this new market for product B was pretty aggressive. We had to demonstrate certain capabilities to potential clients quickly and show them that we were a serious competitor in the new market. To expedite the development, we took the shortest route to create a new product. We started with a deep copy (a branch) of the companies' product A and re-purposed it as B.

This approach made a lot of sense given the time constraints as we inherited a lot of overlapping core functionality and infrastructure for free. We removed a bunch of features and options that didn't apply, left some things that carried over, and added a bunch of new features that were needed to secure these customers. It wasn't a perfect transition, but it was good enough.

Product B has been around for about a year now, and things are looking good as we have secured two customers with several more potential customers on the horizon.
What are the next steps?

From a “best practices” perspective, it doesn't seem like a good strategy to continue developing product B as a copy of product A. It’s not a solid foundation to build a new product.

We accomplished our immediate goal by creating a “product” and demonstrating it to potential clients. Now, shouldn't we take a step back, find out what the users really want and refine our design?

We really don’t have a “new product”. We created some “vaporware” for a couple of demo installs.

Unfortunately, I get the impression from management that they think we have a new product to develop and sell and there is no time to step back and refactor and refine. Why would we spend time and money redesigning when we already have something we can use and sell?

Here are my issues:

Since it was created from a copy of A, the product B code base is littered with artifacts and “technical debt” from product A. Some of this code is no longer reachable. Some of this code is reachable, but maybe the business logic does not make sense for product B. For example, there may be lookups against empty tables in the database or checks against things that don’t exist. This type of logic not only hurts performance, but it also a maintenance nightmare.

I’m going to estimate that we’re actually using 35% of product A’s code base, and the rest is baggage.

Management thinks it was smart to create B from a copy of A: “It will save money since code can be reused between the products.” If a bug is fixed in A, why can’t it be merged into B? Or if I develop a new feature in B, why can’t it be merged to A? This argument is flawed. Although B was created from A, it was done so over a year ago, and A has a dedicated team with 4 developers. I am alone on product B. The code branch for A continues to diverge from B. Now, it’s very difficult to merge anything.

Finally, I feel as if we've put unnecessary constraints on ourselves by starting with a product that's already 5 years old. Some aspects were designed very poorly and will no doubt create the same problems with a new user base. Let’s take our lessons learned and use this opportunity to improve the design instead of copying crap. Also, let’s utilize new technologies where it makes sense - a lot of things have changed in 5 years!

How can I convince management that we need to refine our product – most likely from the ground up? My boss thinks in terms of time and dollars, and I feel that I am going to lose this debate if I’m not careful. Can this type of effort be quantified and put into management terms?

I've been reading up on “emergent design” and I’m trying to approach my argument from the angle that we don’t have to deliver everything all at once. Let’s focus on small pieces of working code with the most business value.

答:
The best architects I know have the same reaction periodically - that the fix for all the problems in the project is 'to start from scratch'...

As code ages, it gets messed up, acquires technical debt, missed the boat on a lot of exciting new technologies, which would have made modules in the current system simpler, or even redundant. Also, the architect looking at the system has also aged, and (hopefully) wizened, so he now sees decisions he's made about the product in the past, and knows that now he would have made different (better?) decisions.

There are times when this is also the best approach, but on other times, it might not be, especially since any new code you write as susceptible to the same aging the current code suffered.

What management is looking for, and so should you, is value in writing from scratch. Look forward into the future, and identify the concrete points where the product will hit a brick wall if it continues to depend on the parent project.

Focus on the differences between the markets to show that the products, although on a business perspective might look similar, are actually profoundly and architecturally different.

Also, I suggest that you search for a way where you can gradually divert from the current code-base (by re-writing a module at a time), while always adding value to the system, so that you will not end up suggesting a long period of non-functional deliveries, which might be very problematic in a fast-paced new market, where the competition is just waiting for that edge over you.

If you can't find enough deal-breakers in the current code-base, or can't think of a way to make the change without losing ground on the business aspects, maybe you should consider the possibility that, as much as it offends us technical people, management might be right to keep the current code-base as long as possible...

Title: Next steps for developing new product


问:
suggest structure for classes that maps to json with dynamic data without using dynamic or object reference
this is a kind of data i have to de-serialize

```<code>{
    "id": "M:11427",
    "title": "DAX30",
    "nextStartId": "S:727831",
    "sections": [
        {
            "type": "HIGHLIGHTS",
            "baseResults": [ values of type highlights ],
            "hasMore": true
        },
        {
            "type": "CHART",
            "hasMore": false,
            "chartTypes": [ string values ]
        },
        {
            "type": "TWEETS",
            "baseResults": [ values of type tweets ],
            "hasMore": true
        }]
}
</code>```

I have to serialize & deserialize them all. I want to create something that can hold the values corresponding to baseResults.

there is a main class that represent the whole json

```<code>class Data
{
...
ObservableCollection<Section> sections{get;set;}
...
}
</code>```

then there is a class that represents the data in sections array of main json

```<code>class Section
{
string type{get;set;}// thi elements decides what kind of data would be in baseResults
dynamic baseResults{get;set;} //it should hold ObservableCollection of either Highlights or Tweets etc.
}
</code>```

base class for type of data coming in baseResults array is an abstract class class CategoryData
and its children are class Highlights & class Tweets

I am using dynamic since I can not assign an ObservableCollection<CategoryData> with ObservableCollection<Highlights>. But I don't want to use this dynamic or object type instead I want something relevant. please suggest me what could be a better approach for this problem.

答:
How about using generics:</p>

```<code>class Section<TCategoryData> where TCategoryData : CategoryData
{
    string type{get;set;}
    ObservableCollection<TCategoryData> baseResults{get;set;}
}

class HighlightSection : Section<Highlights> {}

class TweetSection : Section<Tweets> {}
</code>```

Body:
How about using generics:

class Section<TCategoryData> where TCategoryData : CategoryData
{
    string type{get;set;}
    ObservableCollection<TCategoryData> baseResults{get;set;}
}

class HighlightSection : Section<Highlights> {}

class TweetSection : Section<Tweets> {}


答:
You should not forget that GET requests have some superior advantages over other solutions:

1) GET requests can be copied from the URL bar, they are digested by search engines, they are "friendly". Where "friendly" means that normally a GET request should not modify anything inside your application (idempotent). This is the standard case for a search.

2) All of these concepts are very important not just from user and search engine, but from an architectural, API design standpoint.

3) If you create a workaround with POST/PUT you will have problems which you are not thinking of right now. For example in case of a browser the navigate back button / refresh page / history. These can be solved of course, but that's going to be another workaround, then another and another ...

Considering all this my advice would be:

a) You should be able to fit inside your GET with using clever parameter structure. In extreme case you can even go for tactics like this google search where I set a lot of parameters still its a super short url.

b) Create another entity in your application like JobSearch. Assuming you got so much options, its probable that you will need to store these searches as well and manage them, so its just clearing up your application. You can work with the JobSearch objects as a whole entity, meaning you can test it / use it easier.

Personally I would try to fight with all my claws to get it done with a) and when all hope  is lost, I would crawl back with tears in my eyes to option b).

Title: How do searches fit into a RESTful interface?

Body:
When designing a RESTful interface, the semantics of the request types are deemed vital to the design.

GET - List collection or retrieve element

PUT - Replace collection or element

POST - Create collection or element

DELETE - Well, erm, delete collection or element

However, this doesn't seem to cover the concept of "search".

E.g. in designing a suite of web services that support a Job Search site you might have the following requirements:

Get individual Job Advert

GET to domain/Job/{id}/

Create Job Advert

POST to domain/Job/

Update Job Advert

PUT to domain/Job/

Delete Job Advert

DELETE to domain/Job/

"Get All Jobs" is also simple:

GET to domain/Jobs/

However, how does the job "search" fall into this structure?

You could claim it's a variation of "list collection" and implement as:

GET to domain/Jobs/

However, searches can be complex and it's entirely possible to produce a search that generates a long GET string.  That is, referencing a SO question here, there are issues using GET strings longer than about 2000 characters.

An example might be in a faceted search - continuing the "job" example.

I may allow for searching on facets - "Technology", "Job Title", "Discipline" as well as free-text keywords, age of job, location and salary.

With a fluid user interface and a large number of technologies and job titles, it is feasible that a search could encompass a large number of facet choices.

Tweak this example to CVs, rather than jobs, bring in even more facets, and you can very easily imagine a search with a hundred facets selected, or even just 40 facets each of which are 50 characters long (e.g. Job Titles, University Names, Employer Names).

In that situation it might be desirable to move a PUT or POST in order to ensure that the search data will get correctly sent.  E.g.:

POST to domain/Jobs/

But semantically that's an instruction to create a collection.

You could also say you'll express this as the creation of a search:

POST to domain/Jobs/Search/

or (as suggested by burninggramma below)

POST to domain/JobSearch/

Semantically it may seem to make sense, but you're not actually creating anything, you're making a request for data.

So, semantically it's a GET, but GET isn't guaranteed to support what you need.

So, the question is - Trying to keep as true to RESTful design as possible, whilst ensuring that I'm keeping within the limitations of HTTP, what is the most appropriate design for a search?


答:
If I'm understanding you correctly, you're trying to find a statically-typed way to say "a value of type Section can be either a value of type Highlights, Chart, or Tweets". There are many terms for this, including tagged union, discriminated union, variant, or sum type but they all refer to the same concept. Sum types are a standard feature in statically-typed functional programming languages, but with a bit of ingenuity you can roll your own in C#. Using that answer as a template, and adding sealed to make sure no one adds any extra subclasses, your Section type would look something like this:

```<code>public abstract class Section
{
    // Prevent subclassing outside of this scope
    private Section() {}

    // Subclass implementation calls the appropriate function.
    public abstract R Match<R>(Func<H, R> IfHighlight, Func<C, R> IfChart, Func<T, R> IfTweet);

    // Convenience wrapper for when the caller doesn't want to return a value
    // from the match expression.
    public sealed void Match(Action<H> IfHighlight, Action<C> IfChart, Action<T> IfTweet)
    {
        this.Match<int>(
            IfHighlight: Section => { IfHighlight(Section); return 0; },
            IfChart: Section => { IfChart(Section); return 0; },
            IfTweet: Section => { IfTweet(Section); return 0; }
        );
    }

    // From here on down, you define your specific types as usual, and override Match to call
    // the correct function

    public sealed class Highlight : Section
    {
        // Implementation goes here

        public override R Match<R>(Func<H, R> IfHighlight, Func<C, R> IfChart, Func<T, R> IfTweet)
        {
            return IfHighlight(this);
        }
    }

    public class Chart : Section
    {
        // Implementation goes here

        public override R Match<R>(Func<H, R> IfHighlight, Func<C, R> IfChart, Func<T, R> IfTweet)
        {
            return IfChart(this);
        }
    }

    public class Tweet : Section
    {
        // Implementation goes here

        public override R Match<R>(Func<H, R> IfHighlight, Func<C, R> IfChart, Func<T, R> IfTweet)
        {
            return IfTweet(this);
        }
    }
}
</code>```

With that in place, you can declare variables of type Section, and act on them by passing 3 functions to the Match methods:

```<code>Section section = deserializeJson()
section.Match(
    IfHighlight: highlight => /* code to use if you get a Highlight */
    IfChart: chart => /* ... */
    IfTweet: tweet => /* ... */
);
</code>```

You could just as easily have a collection of Sections and operate on them that way when you iterate over it.

Title: suggest structure for classes that maps to json with dynamic data without using dynamic or object reference

Body:
this is a kind of data i have to de-serialize

```<code>{
    "id": "M:11427",
    "title": "DAX30",
    "nextStartId": "S:727831",
    "sections": [
        {
            "type": "HIGHLIGHTS",
            "baseResults": [ values of type highlights ],
            "hasMore": true
        },
        {
            "type": "CHART",
            "hasMore": false,
            "chartTypes": [ string values ]
        },
        {
            "type": "TWEETS",
            "baseResults": [ values of type tweets ],
            "hasMore": true
        }]
}
</code>```

I have to serialize & deserialize them all. I want to create something that can hold the values corresponding to baseResults.

there is a main class that represent the whole json

```<code>class Data
{
...
ObservableCollection<Section> sections{get;set;}
...
}
</code>```

then there is a class that represents the data in sections array of main json

```<code>class Section
{
string type{get;set;}// thi elements decides what kind of data would be in baseResults
dynamic baseResults{get;set;} //it should hold ObservableCollection of either Highlights or Tweets etc.
}
</code>```

base class for type of data coming in baseResults array is an abstract class class CategoryData
and its children are class Highlights & class Tweets

I am using dynamic since I can not assign an ObservableCollection<CategoryData> with ObservableCollection<Highlights>. But I don't want to use this dynamic or object type instead I want something relevant. please suggest me what could be a better approach for this problem.

Body:
If I'm understanding you correctly, you're trying to find a statically-typed way to say "a value of type Section can be either a value of type Highlights, Chart, or Tweets". There are many terms for this, including tagged union, discriminated union, variant, or sum type but they all refer to the same concept. Sum types are a standard feature in statically-typed functional programming languages, but with a bit of ingenuity you can roll your own in C#. Using that answer as a template, and adding sealed to make sure no one adds any extra subclasses, your Section type would look something like this:

public abstract class Section
{
    // Prevent subclassing outside of this scope
    private Section() {}

    // Subclass implementation calls the appropriate function.
    public abstract R Match<R>(Func<H, R> IfHighlight, Func<C, R> IfChart, Func<T, R> IfTweet);

    // Convenience wrapper for when the caller doesn't want to return a value
    // from the match expression.
    public sealed void Match(Action<H> IfHighlight, Action<C> IfChart, Action<T> IfTweet)
    {
        this.Match<int>(
            IfHighlight: Section => { IfHighlight(Section); return 0; },
            IfChart: Section => { IfChart(Section); return 0; },
            IfTweet: Section => { IfTweet(Section); return 0; }
        );
    }

    // From here on down, you define your specific types as usual, and override Match to call
    // the correct function

    public sealed class Highlight : Section
    {
        // Implementation goes here

        public override R Match<R>(Func<H, R> IfHighlight, Func<C, R> IfChart, Func<T, R> IfTweet)
        {
            return IfHighlight(this);
        }
    }

    public class Chart : Section
    {
        // Implementation goes here

        public override R Match<R>(Func<H, R> IfHighlight, Func<C, R> IfChart, Func<T, R> IfTweet)
        {
            return IfChart(this);
        }
    }

    public class Tweet : Section
    {
        // Implementation goes here

        public override R Match<R>(Func<H, R> IfHighlight, Func<C, R> IfChart, Func<T, R> IfTweet)
        {
            return IfTweet(this);
        }
    }
}

With that in place, you can declare variables of type Section, and act on them by passing 3 functions to the Match methods:

Section section = deserializeJson()
section.Match(
    IfHighlight: highlight => /* code to use if you get a Highlight */
    IfChart: chart => /* ... */
    IfTweet: tweet => /* ... */
);

You could just as easily have a collection of Sections and operate on them that way when you iterate over it.


答:
You are supposed to choose concrete subtype of Section BEFORE you create the instance. The type property should not even be in a Section and should be tied to what subclass the instance is.

But how to do this depends on how you are doing the serialization and deserialization.


问:
Which extreme-programming techniques are appropriate to use in a research environment?
Which (if any) extreme-programming techniques would be appropriate to use in a research environment - where the goal is to produce prototypes, patentable, and/or publishable work?</p>

答:
You have to be Agile to do research
programming.

You have to be willing to throw away
a lot of prototypes.

You have to be willing to think
outside the box, so software patterns
are not going to help you that much.

I think you have to be willing to
learn new languages, and even create
some new ones.

Other than that, research programming is basically the same as any other. :)  You still have to write unit tests.  You still have to write documentation.  And you still have a boss.

Your deadlines may be a bit more fluid.