问:
What is the best pattern for adding an existing item to a collection in REST API?
I'm designing a pragmatic REST API and I'm a little stuck on how best to add existing entities to a collection. My domain model includes a Project that has a collection of Sites. This is a strict many-to-many relationship and I have no need to create an entity that explicitly models the relationship (i.e. ProjectSite).

My API will allow consumers to add an existing Site to a Project. Where I'm getting hung up is that the only data I really need are ProjectId and SiteId. My initial idea was:

```<code>1. POST myapi/projects/{projectId}/sites/{siteId}
</code>```

But I also thought about

```<code>2. POST myapi/projects/{projectId}/sites
</code>```

with a Site entity sent as JSON content.

Option 1 is simple and works but doesn't feel quite right, and I have other relationships that cannot follow this pattern so it adds inconsistency to my API.

Option 2 feels better but leads to two concerns:

Should I create a Site or throw an exception if a new Site is posted (SiteId = 0)?

Because I only need ProjectId and SiteId to create the relationship, the Site could be posted with wrong or missing data for other properties.

A 3rd option is to provide a simple endpoint solely for creating and deleting the relationship. This endpoint would expect a JSON payload containing just ProjectId and SiteId.

What do you think?

答:
We use the Patch method for stuff like this. What you want to do is modify an existing Project to add a Site to it.

So something like this would work

```<code>PATCH myapi/projects/{id}
</code>```

with the Site(s) entity as JSON/JSONArray in the request body.

That way you can use the same URL to modify different parts of the Project if you needed to -- your code in the implementation must be intelligent enough to handle this partial modification of the resource.

Body:
We use the Patch method for stuff like this. What you want to do is modify an existing Project to add a Site to it.

So something like this would work

PATCH myapi/projects/{id}

with the Site(s) entity as JSON/JSONArray in the request body.

That way you can use the same URL to modify different parts of the Project if you needed to -- your code in the implementation must be intelligent enough to handle this partial modification of the resource.


问:
Use of Unmodified AGPLv3 lib - am I AGPL too?
So, I've been reading the AGPL and here is my understanding (not being a lawyer and I'm not trying to look at it through the lens of "Since I WANT it to be ''free'', it therefore is.".  In my case, I am considering the use of itext, an AGPL library, to crack open PDF files and extract the text - that's it. There will be an internal desktop app and I've proposed using my extraction code (which uses the itext dll) on the website to speed up the process for those folks upstairs who've been doing it manually for years.

Under definitions:

"the program" means the itext lib, being the copyrightable work.

"modify" or "based on" means, a version of the program which differs
from the original. Not applicable here since I am not modifying the code.

"covered work" means the original or modified versions of the
original work. In my case, it would be the original work.

"propagate" and "convey" mean to copy or distribute the program (the
itext lib, in my case, compiled as a dll), in which case, as I
understand it, the source to the covered work must be made available.
This doesn't apply to use within companies (since the company can
require employees to not make copies and distribute software).  Use
on public facing networks though, might be a consideration per sec13,
though the web users won't be interacting with the program itself or
with the output of the program.

"interactive user interface"... so far, haven't seen one in the lib
but this is probably the least clear of the definitions since it
mentions the "work" and libs (the work, in this case) generally don't
interact with users. If I need to, I can include a mention somewhere,
no biggie.

So, by my interpretation of the definitions, the covered work is the itext code I am using.  The code I write separately, is not based on or modified from the itext code and thus, can be licenced any way I choose, incl locking it down tightly or posting openly on my fav forum.  So long as I do not modify or incorporate copyrighted AGPL code directly into my code, there is nothing I can see in this licence that prevents me from linking to the original version I downloaded.  Most I might have to do is provide the source to the version of the covered work.

So, emotions aside and focusing solely on legality, what say you?  I think it's clear from the FSF FAQ, that internal corporate use means I can do pretty much anything I like and  no source needs to be distributed outside the organization.  My only real concern is making a web app which in turn, makes calls to the itext lib. What am I required to do in this case? I believe I only need to provide a link or location to download the itext code.  Another option, what if I made a small, separate, standalone program, and had the website call it via a standard "run" mechanism? The rest of the existing website should not have to suddenly fall under the AGPL even if my text extractor portion does, correct?

答:
The only material difference between the GPL and the AGPL is that the AGPL extends the concept of distribution to include "providing the web interface of a program to an internet-facing customer."

If you really want a workaround, the way you do it is by wrapping the AGPL library in an executable, and calling it from the command line.  The FSF calls this "arms-length communication;" it means that your AGPL library is not "linked" with your executable via early binding or late binding programming language mechanisms.

See here, where it says:

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

The difference between this and “incorporating” the GPL-covered
  software is partly a matter of substance and partly form. The
  substantive part is this: if the two programs are combined so that
  they become effectively two parts of one program, then you can't treat
  them as two separate programs. So the GPL has to cover the whole
  thing.

If the two programs remain well separated, like the compiler and the
  kernel, or like an editor and a shell, then you can treat them as two
  separate programs—but you have to do it properly. The issue is simply
  one of form: how you describe what you are doing.

In short, the AGPL library has to be a standalone program, and your application has to be able to function without it.

As always, if you have real legal concerns, you should consult a real lawyer who specializes in this sort of thing.

ContentLicense: CC BY-SA 3.0


问:
How do I stop designing and start architecting this project as suggested by my lead?
I'm a junior developer (~3 years' exp.) and at my job we're in the process of architecting a new system. My lead developer will be the principal architect, however he's challenged me to try architecting the system myself (in parallel).

Over the course of a few iterations of brainstorming ideas and proposing what I saw as architecture suggestions, my lead has given me the feedback that most of what I've been doing was "designing" and not "architecting".

He described the difference as architecture being implementation-agnostic whereas a design is the description of an implementation. He said I need to take off my designer hat and put on my architect hat. He gave me a little bit of advice on how to do so, but I would like to ask you as well:

How do I get out of software designer mode and start thinking more like an architect?

Here are some examples of "designs" I came up with that weren't seen as relevant to the architecture by my lead:

I came up with an algorithm for loading and unloading resources from our system and my lead said that algorithms are categorically not architecture.

I came up with a set of events the system should be raising and in what order it should raise them, but this too didn't seem to cut it as architecture.

I seem to be getting caught up in the details and not stepping back far enough. I find that even when I come up with something that is at an architecture level, I often got there by trying out various implementations and mucking around in the details then generalizing and abstracting. When I described this to my lead, he said that I was taking the wrong approach: I needed to be thinking "top down" and not "bottom up".

Here are some more specific details about the project:

The project we're architecting is a web application.

I'm estimating around 10-100 thousand lines of code.

We're a start up. Our engineering team is about 3-5 people.

The closest thing I could compare our application to is a lightweight CMS. It has similar complexity and deals largely with component loading and unloading, layout management, and plug-in style modules.

The application is ajax-y. The user downloads the client once then requests data as it needs it from the server.

We will be using the MVC pattern.

The application will have authentication.

We aren't very concerned about old browser support (whew!), so we're looking to leverage the latest and greatest that is out there and will be coming out. (HTML5, CSS3, WebGL?, Media Source Extensions, and more!)

Here are some goals of the project:

The application needs to scale. In the near term our users will be on the order of hundreds to thousands, but we're planning for tens of thousands to millions and beyond.

We hope the application will be around forever. This isn't a temporary solution. (Actually we already have a temporary solution, and what we're architecting is the long-term replacement for what we have).

The application should be secure as it may have contact with sensitive personal information.

The application needs to be stable. (Ideally, it'd be stable around the level of gmail but it doesn't need to be at the extreme of a Mars rover.)

答:
Think of all the operations (ie. use-cases) your system can perform. For each operation, document what happens in terms of your business domain for each operation. You should only talk in terms of your problem domain and not describe any implementation details. Draw a big block and call it System. The combination of this "big block" and the operation descriptions is the highest level system architecture.

While this high level architecture does provide a decent starting point, it really isn't of much value when building an actual system. You must take it down one level of detail to turn this into a useful architecture.

So you follow the same general idea as the "big block" approach only you begin adding "sub-blocks" that are necessary to accomplish each operation. These "sub-blocks" are frequently called domain classes or modules. These are easily identified by using your operation descriptions (from the big block approach) and drawing sequence diagrams. They are called domain classes because they aren't intended to be "real" classes, but they are intended to describe your system in terms of the problem domain of your system.

The end result of creating all the sequence diagram and identifying all the "sub-blocks" is that you now have a list of domain classes and their lists of operations. This usually ends up resulting in a fairly usable software architecture, where each of the "sub-blocks"/modules could be parceled out to different developers to design and implement.

Of course, if you leave it as is, then your designers will have a lot of interaction with each other in defining the interfaces between the modules. Thus, the architect may also decide on the specific interface mechanisms and data types to be used between modules.

Also, some "sub-blocks" will still be very complicated under-the-hood. So another iteration of the "sub-block" approach may be necessary but only this time on one of the newly identified modules.

Finally, there may be some specific patterns/limitations between interfaces that the architect wants the system to adhere to (e.g. event callbacks versus direct method calls), so those decisions would need to be talked about in the architectural design. Plus there may be "common" modules that the architect wants everyone to use.


问:
Lots of classes with only one single static method with same name as class - Code smell?
I'm trying to follow the single responsibility principle (SRP) in my applications. I have lots of CRUD classes I just name xxxxxManager.

Following the SRP, I made 4 classes for each one :

xxxxxCreator, xxxxxGetter, xxxxxDeleter, xxxxxUpdater

They end up having only one static method : xxxxxCreator::create(Model $model), xxxxUpdater::update(Model $model), etc.

This is a code smell for me. Am I pushing the SRP too far ?

答:
The single responsibility is data access, not creating, reading, updating and deleting.  Your granularity is too small at that level.

SRP doesn't mean that the class should only do one thing; it means that the class should have only one reason to change.  The Wikipedia article describes it as

Every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility.


答:
I don't believe anywhere in SRP does it say that each class should have a single method... Also, you created 4 classes which have a lot of dependencies - changes in xxxxCreator will almost certainly come together with xxxxUpdater.

I would say that CRUD definitely falls within the realm of single dependency.

Title: Lots of classes with only one single static method with same name as class - Code smell?

Body:
I'm trying to follow the single responsibility principle (SRP) in my applications. I have lots of CRUD classes I just name xxxxxManager.

Following the SRP, I made 4 classes for each one :

xxxxxCreator, xxxxxGetter, xxxxxDeleter, xxxxxUpdater

They end up having only one static method : xxxxxCreator::create(Model $model), xxxxUpdater::update(Model $model), etc.

This is a code smell for me. Am I pushing the SRP too far ?


问:
How to you achieve flow in web programming?
I really like programming simple things, like solutions for Project Euler, where you can concentrate, write an algorithm, instantly execute, test, verify and change the program until it works. Even for bigger projects I feel I can maintain flow and be very productive as long as I can stay in one IDE (e.g. Eclipse) and everything compiles and starts fast, for example, if it is a Swing GUI.

With the growing focus on web applications and smart phones however, I am forced to set up a web server, juggle a big amount of programming and markup languages (e.g. Javascript, Java, HTML, CSS), different kinds of editors and wait while something is deployed (web server), compiled (GWT, Vaadin) or virtualized (Android). Are there solutions that allow to circumvent those problems?

I know this questions may sound subjective but it is an important issue for me and I think it can benefit many others as well.

P.S.: What I am looking for is a solution to web development which allows staying in one IDE and which allows testing and executing without long waiting for long compiles, deploys, ect.

答:
As a matter of principal, as the problem gets tougher, the solution gets more complicated - Project Euler is a very safe environment, which poses problems intended specifically to teach you how to solve an issue.

Real-life projects tend to be made up of a lot of issues in the form of features, media, scale, connectivity, front-end, etc.

I don't think you should strive to make solving a real-life problem look like solving an exercise. The best approach, in my opinion, is to solve it one problem at a time.

You can start by breaking your problem to features, starting with a simple one, implementing it, and continuing to the next (BDD style).

This way, with each feature, you can solve the problem in the most simple way you can (continually refactoring it to be DRY and well designed), keeping with small iterations, and manageable "sprints", where you can control which technology you are focusing on at each tier.

This way (and with a little patience), you can solve bigger and bigger problems, learning a lot of technologies along the way, being less concerned about juggling and switching between technologies, IDEs and design problems, and more focused on the problem at hand.


答:
I'd say so.  I think there was a little bit of talk back in the day about redesigning Java so that every class only had one method: run().  This is effectively what you're talking about.  This didn't really get anywhere or pick up any traction anywhere else, because you couldn't really do much with it.

What you start running into at this point is a very hard time implmementing very basic control structures.  Because if you think about what an if statement looks like:

```<code>if (condition)
{
    // do this
}
else
{
    // do that
}
</code>```

is that just doing one thing?  Is it just running()?  No, it's doing two things, and it's not even the same one or two each time.  Sometimes it doesThis(), and sometimes it doesThat().  So what you have there, with virtually any if statement with an else clause, is a choice:

Use multiple functions within the class or module or whatever.

Use only one function, but with distinctly different behavior in different spots that could each be easily converted into a separate function.

Is 1 cleaner than 2, or is 2 cleaner than 1?  ...Yes.  It really depends on the situation, with regards to which one you want to go with.  What you do not want to do is rid yourself of if statements.  And every non-infinite loop that's not automatically broken out of pretty much implies an if statement.

Why make a separate class for each updating, deleting, creating, and getting?  Somewhere along the road, you'll still end up having to do this:

```<code>if (condition1)
{
    xxxxxCreator.Create();
}
else if (condition2)
{
    xxxxxGetter.Get();
}
else if (condition3)
{
    xxxxxUpdater.Update();
}
else
{
    xxxxxDeleter.Delete();
}
</code>```

I count one, two, three, four different things that are being done all in the same class.  Even if you break this up into smaller if statements, there will still be a conditional somewhere, even if it's in the machine code.  ...And that violates such a strict interpretation of the necessity of a function/class needing to do one and only one thing.

Since you cannot forgo conditionals in programming, you should not try to adhere to such a strict interpretation.  Go ahead and create an xxxxxManager class with methods Get(), Update(), Create(), and Delete().

Body:
I'd say so.  I think there was a little bit of talk back in the day about redesigning Java so that every class only had one method: run().  This is effectively what you're talking about.  This didn't really get anywhere or pick up any traction anywhere else, because you couldn't really do much with it.

What you start running into at this point is a very hard time implmementing very basic control structures.  Because if you think about what an if statement looks like:

if (condition)
{
    // do this
}
else
{
    // do that
}

is that just doing one thing?  Is it just running()?  No, it's doing two things, and it's not even the same one or two each time.  Sometimes it doesThis(), and sometimes it doesThat().  So what you have there, with virtually any if statement with an else clause, is a choice:

Use multiple functions within the class or module or whatever.

Use only one function, but with distinctly different behavior in different spots that could each be easily converted into a separate function.

Is 1 cleaner than 2, or is 2 cleaner than 1?  ...Yes.  It really depends on the situation, with regards to which one you want to go with.  What you do not want to do is rid yourself of if statements.  And every non-infinite loop that's not automatically broken out of pretty much implies an if statement.

Why make a separate class for each updating, deleting, creating, and getting?  Somewhere along the road, you'll still end up having to do this:

if (condition1)
{
    xxxxxCreator.Create();
}
else if (condition2)
{
    xxxxxGetter.Get();
}
else if (condition3)
{
    xxxxxUpdater.Update();
}
else
{
    xxxxxDeleter.Delete();
}

I count one, two, three, four different things that are being done all in the same class.  Even if you break this up into smaller if statements, there will still be a conditional somewhere, even if it's in the machine code.  ...And that violates such a strict interpretation of the necessity of a function/class needing to do one and only one thing.

Since you cannot forgo conditionals in programming, you should not try to adhere to such a strict interpretation.  Go ahead and create an xxxxxManager class with methods Get(), Update(), Create(), and Delete().


答:
The single responsability principle main reasosn of existence are :

To prevent you to make classes who do everything in a total mess and

Force you to segregate your code in well separate concerns.

So, basically, if you make a class who handle the 4 CRUD actions on an entity, for me, it's fine.
Moreover, I would add that your methods should respect the SRP principle too.
For example, the update action should NOT return an entity, it's the role of the read action, not the update !


答:
You adress three different topics:

switching between different editors

switching between different languages

build duration

Concerning the editors, the is no reason to use more than one. If you have an IDE, it certainly has html/css/javascript modes. Same thing if you use something like vim/emacs/sublime text/notepad++. I don't see why you should change your editor.

Build duration is a problem in all kind of application. The solution is to use an interpreted language, or to work on individual modules and use TDD. This also allows you to bypass the launch & manual test phase. This requires a bit of initial design to break down & formalize features needed but it is usually pays to do so anyway.

HTML does not really needs to be unit tested. I find it useful to test css adjustment using the browser debug mode. That way you get a quick edit-feedback loop.

Switching between different languages is a problem. You should organize yourself to minimize such switches by focusing on one part at a time. However, with time it will be less and less problematic.

Title: How to you achieve flow in web programming?

Body:
I really like programming simple things, like solutions for Project Euler, where you can concentrate, write an algorithm, instantly execute, test, verify and change the program until it works. Even for bigger projects I feel I can maintain flow and be very productive as long as I can stay in one IDE (e.g. Eclipse) and everything compiles and starts fast, for example, if it is a Swing GUI.

With the growing focus on web applications and smart phones however, I am forced to set up a web server, juggle a big amount of programming and markup languages (e.g. Javascript, Java, HTML, CSS), different kinds of editors and wait while something is deployed (web server), compiled (GWT, Vaadin) or virtualized (Android). Are there solutions that allow to circumvent those problems?

I know this questions may sound subjective but it is an important issue for me and I think it can benefit many others as well.

P.S.: What I am looking for is a solution to web development which allows staying in one IDE and which allows testing and executing without long waiting for long compiles, deploys, ect.


答:
What you're doing is writing functions, not classes.  Not all languages allow stand-alone functions, but if the language allows you, it would make more sense to write them as functions.

This is not necessarily a bad thing.  A lot of people like to dogmatically say "everything is an object", but they're wrong -- these things you're writing aren't objects, they're functions, even though they're wearing object clothing.  There's nothing wrong with functions.

The SRP is OOP specific terminology, but the idea also works for procedural or functional programming; instead of an object or class having a single responsibility, a function does a single thing.  These functions do a single thing.

However, if Model is an OO class or object (not just a data structure that happens to be an 'object' or 'class' in the type system of the language you're using), it might not mesh well with the style of the rest of the code.

If you want to do things in a more OO way, I would guess that you could put these in the Model class, since the two examples you give both take a Model as their only argument.  Then, assuming that Model is not already huge, bloated, or unwieldy, it would likely be in line with the SRP.


问:
Strategy to store/average logs of pings
I'm developing a site to monitor web services. The most basic type of check is sending a ping, storing the response time in a CheckLog object. By default, PingCheck objects are triggered every minute, so in one hour you get 60 CheckLogs and in one day you get 1440 CheckLogs.

That's a lot of them, I don't need to store such level of detail, so I've set a up collapsing mechanism that periodically takes the uncollapsed CheckLogs older than 24h and collapses (averages) them in intervals of 30 minutes. So, if you have 360 CheckLogs that have been saved from 0:00 to 6:00, after collapsing you retain just 12 of them. The problem.. well, is this:

After averaging the response times, the graph changes drastically. What can I do to improve this? Guess one option could be narrowing the interval duration to 15 min.

I've seen the graphs at the GitHub status page and they do not seem to suffer from this problem.

I'd appreciate any kind of information you could give me about this area.

答:
Your graph before averaging shows that you have a lot of variance. This means that the graph before averaging may actually show you less information - mostly noise. To get valuable information about problems you may have (like latency), you might want to keep a running window average, and watch for trends in your data, which might point to problems.

Of course, keeping score of your minimum, maximum and standard deviation will also give valuable information.

You can use third party services (like NewRelic for example), which can receive your reports, and give you all this information, as well as alarms to notify you about suspicious changes.

Title: Strategy to store/average logs of pings


问:
What's a "Professional Fit" interview?
So I went through an initial interview on school campus, and an on-site interview(one day, mostly technical interviews) with this company, and then a week later, I am told that there will be an additional phone interview with one of their hiring managers, called "Professional Fit Interview", which I have no idea what it is. Before I thought the on-site interview was gonna be the last round, at least that's the impression I got from them.

So what this "professional fit interview" might be? How should I prepare for it?

Thanks a lot!

A follow-up: Thank everyone for the replies. As everybody has mentioned, it's a HR type interview. The interviewer did some introduction of the team, then asked if I have some questions, and asked me a couple of questions like "where do you see yourself in 2 years". Anyway, a rejection email came about one week later.

答:
Typically, a cultural fit assessment is something to gauge your personality (and how it'll mesh with the existing employees there). Given that your day of interviews was mostly technical, it's possible that this is what they were referring to.

Just try not to be too much of a richard and you'll be fine. It's typically HR equine-feces and tea-leaves; you really can't study for it short of reading up on Myer-Briggs and playing the meta-answer game.

ContentLicense: CC BY-SA 2.5

Title: What's a "Professional Fit" interview?


问:
About protection for important actions on the server
We developing a web service. And need our important actions (i.e. money transfer) to be protected from accidental calling. In frontend we asking user to confirm such actions. Ok.

But how to prevent accidental calling in case of developer mistake?

Is it good idea, that action require some confirmation token from developer to proceed?

答:
If you are exposing your web-service to 3rd party application developers, I can think of two scenarios where a critical API may be called without user consent (given your UI guidelines):

A bug in the code

Malicious 3rd party developer, misusing the API

Against non-sindicated usage, what I can suggest is providing your 3rd party developers with API keys, which will be needed to issue the critical API call.

This way, you can shield your application from malicious use of the API, as well as track which 3rd party made which call, to be able to track down suspicious behavior.

As for bugs in the code, they are trickier, since there is no programatic way to prevent them. A possible solution might be to have a two-phase confirmation (i.e. sending a mail to the user, with a confirmation link, which he must click for the transaction to complete), or (maybe more user-friendly, but might not be possible, depending on the service) a mail with an undo transaction link, to prevent accidental transactions after the fact.


问:
How to design to allow for future logic revision?
The typical programming designing method that I've come to use goes like this:

```<code>1. ID the problem and what's required
2. Make your program do something simple
3. Test it
4. Make your program do a little bit more
5. Repeat 2 until all the micro problems are solved by the program as a whole
</code>```

Basically, incremental design.  So, all the pieces can be split apart and each micro problem is solved by a micro problem function; does a great job with cohesion and reduces coupling.

Then, sometime in the future, the program comes across a problem that is just like the problem it is built on, but requires a little extra.  So, I'd say add the functionality to the program, to make up for it.  If, when you're adding that functionality, the already established working logic has to be edited to make the new functionality work, it suddenly seems like you're messing with something you shouldn't.

So, is there a designing method where every program developed with it can be added onto without compromising working logic?

Example:

```<code>word = yes,no,"maybe,so"

oldCSVSplit(word, ",") -> {"yes", "no", "\"maybe", "so\""}
newCSVSplit(word, ",") -> {"yes", "no", "maybe,so"};
</code>```

The oldCSVSplit function does what it should, split on ",".  Then, sometime in the future, commas inside quotes must be ignored to properly get entries.  Adding the functionality to ignore single/double quotes would severely alter the logic, with more ifs and checks and even a stack for keeping track of starting quotes.  Is such a scenario avoidable?  What method can make such additions painless and less compromising to working logic?

答:
So, is there a designing method where every program developed with it can be added onto without compromising working logic?

No. As you refine, you necessarily change existing logic. You hide it, obscure it or re-write it.


答: Have you considered asking them what it is? I have not heard of it. Although, it sounds a little like something we used to do in my company. What we did was have two managers interview a candidate and a developer. The developer afterward would be asked how they felt the candidate would fit in at the company.</p>

Title: What's a "Professional Fit" interview?

Body:
So I went through an initial interview on school campus, and an on-site interview(one day, mostly technical interviews) with this company, and then a week later, I am told that there will be an additional phone interview with one of their hiring managers, called "Professional Fit Interview", which I have no idea what it is. Before I thought the on-site interview was gonna be the last round, at least that's the impression I got from them.

So what this "professional fit interview" might be? How should I prepare for it?

Thanks a lot!

A follow-up: Thank everyone for the replies. As everybody has mentioned, it's a HR type interview. The interviewer did some introduction of the team, then asked if I have some questions, and asked me a couple of questions like "where do you see yourself in 2 years". Anyway, a rejection email came about one week later.


问:
messaging class and global state
This is a front end project that is using socket.io for all communication with the server. This allows for push which is good, but recently we have been asked to provide a pause button. The pause button is intended on stopping the data from changing out on the ui if the user does not wish it to do so automatically.

We currently have a class that wraps the web-socket and provides very minimal wrapping of socket.io.

The problem is, we can't just turn off the socket. User interactions need to continue to work, and different views have different specs as to what messages need to be ignored.

Ultimately its a big global boolean no matter how you slice it, and that sucks. I would rather not have it truly be a global variable, so here are the idea's I've had so far:

Narsty Global

```<code>  // A non pausable listener
  socket.on('myEvent', function(data){
      // do thing
  });

  // A pausable listener
  socket.on('myPausable', function(data){
      if(window.isPaused){ return false; }
      // do thing
  });
</code>```

Passed Value

```<code>  // A non pausable listener
  socket.on('myEvent', function(data){
      // do thing
  });

  // A pausable listener
  socket.on('myPausable', function(data, isPaused){
      if(isPaused){ return false; }
      // do thing
  });
</code>```

Wrapped Method

```<code>  // A non pausable listener
  socket.on('myEvent', function(data){
      // do thing
  });

  // A pausable listener
  socket.onLive('myPausable', function(data){
      // do thing
  });
</code>```

Separate Class

```<code>  // A non pausable listener
  socket.on('myEvent', function(data){
      // do thing
  });

  // A pausable listener
  liveData.on('myPausable', function(data){
      // do thing
  });
</code>```

Currently there is ALOT of messaging taking place over the socket, and there is only going to be one 'PAUSE' toggle on the UI, so this needs to be done carefully. Advice and best practices are appreciated. Thanks folks.

答:
I presume that you need to update the UI with the most recent information when you un-pause the update.

This means that you want pausing to occur on the UI and not on the socket. Let the socket run freely, updating local state. For your UI, you use a copy of the local state for display and don't refresh the copy until you unpause everything.

Title: messaging class and global state


答:
I have some cognitive dissonance regarding the pause button - as a user, I consider 'Pause' to mean - halt what the server is doing. From your requirement, though, it seems that the server is not affected by the button at all, which might be confusing, and even misleading, as the feedback to the user really stops. I believe that in most cases, a button called 'Stop animation' or a toggle called 'Auto-refresh' might convey the idea to the user better.

To the matter at hand, I could suggest one more idea, which is having a flag on the server, which will prevent relevant messages from reaching the client altogether when paused. This way, the only change in the client is adding the server message to pause or un-pause, and the rest stays the same.

If that does not make sense in your case, I believe that the simplest solution (although deemed ugly) will be the best, since it has the least number of moving parts. Use a global state variable (under a suitable namespace of course - window.MyAmazingApp.isPaused), and use it as necessary, leaving other code untouched.

Title: messaging class and global state

Body:
This is a front end project that is using socket.io for all communication with the server. This allows for push which is good, but recently we have been asked to provide a pause button. The pause button is intended on stopping the data from changing out on the ui if the user does not wish it to do so automatically.

We currently have a class that wraps the web-socket and provides very minimal wrapping of socket.io.

The problem is, we can't just turn off the socket. User interactions need to continue to work, and different views have different specs as to what messages need to be ignored.

Ultimately its a big global boolean no matter how you slice it, and that sucks. I would rather not have it truly be a global variable, so here are the idea's I've had so far:

Narsty Global

```<code>  // A non pausable listener
  socket.on('myEvent', function(data){
      // do thing
  });

  // A pausable listener
  socket.on('myPausable', function(data){
      if(window.isPaused){ return false; }
      // do thing
  });
</code>```

Passed Value

```<code>  // A non pausable listener
  socket.on('myEvent', function(data){
      // do thing
  });

  // A pausable listener
  socket.on('myPausable', function(data, isPaused){
      if(isPaused){ return false; }
      // do thing
  });
</code>```

Wrapped Method

```<code>  // A non pausable listener
  socket.on('myEvent', function(data){
      // do thing
  });

  // A pausable listener
  socket.onLive('myPausable', function(data){
      // do thing
  });
</code>```

Separate Class

```<code>  // A non pausable listener
  socket.on('myEvent', function(data){
      // do thing
  });

  // A pausable listener
  liveData.on('myPausable', function(data){
      // do thing
  });
</code>```

Currently there is ALOT of messaging taking place over the socket, and there is only going to be one 'PAUSE' toggle on the UI, so this needs to be done carefully. Advice and best practices are appreciated. Thanks folks.


答:
Well, I would say that changing software that was written before is a fairly big part of what programming is all about.

I'd wager that most developers are paid to maintain, extend and fix brownfield projects rather than greenfield ones.

If you need to get a program to handle a scenario that it wasn't designed to handle, you have to change something and shouldn't feel bad about it.

I might have misunderstood your post but, to me, it sounds like either you don't practice TDD or, if you do, you got it kind of backwards.

If the first is true, you should by all means look into it. If the second is true, you might want to read about it again.

In case you don't know what I'm talking about, TDD in a nutshell is:

You write a test that confirms the software can't already do what you want it to do

You execute the test, and it should fail

Only then do you write some code, as little as possible, to make the test pass

If the test passes, bam, you're golden and can refactor the code to make it more understandable/efficient/beautiful. A further run of the test will confirm you didn't break anything while refactoring

If the test doesn't pass, well, tough luck, you'll have to figure out why. The good news is that, if you do unit testing right, your test will be small and focused enough to make finding the bug a breeze in most cases, without even resorting to the debugger

If you developed your program with this approach, testing that it still splits on commas but not if a comma is between two double quotes is trivial.
You will have old tests that tell you the program behaves as originally intended, plus new tests that tell you that it can handle commas inside double quotes.

Learning more about TDD is left as an exercise for the reader.

Title: How to design to allow for future logic revision?

Body:
The typical programming designing method that I've come to use goes like this:

```<code>1. ID the problem and what's required
2. Make your program do something simple
3. Test it
4. Make your program do a little bit more
5. Repeat 2 until all the micro problems are solved by the program as a whole
</code>```

Basically, incremental design.  So, all the pieces can be split apart and each micro problem is solved by a micro problem function; does a great job with cohesion and reduces coupling.

Then, sometime in the future, the program comes across a problem that is just like the problem it is built on, but requires a little extra.  So, I'd say add the functionality to the program, to make up for it.  If, when you're adding that functionality, the already established working logic has to be edited to make the new functionality work, it suddenly seems like you're messing with something you shouldn't.

So, is there a designing method where every program developed with it can be added onto without compromising working logic?

Example:

```<code>word = yes,no,"maybe,so"

oldCSVSplit(word, ",") -> {"yes", "no", "\"maybe", "so\""}
newCSVSplit(word, ",") -> {"yes", "no", "maybe,so"};
</code>```

The oldCSVSplit function does what it should, split on ",".  Then, sometime in the future, commas inside quotes must be ignored to properly get entries.  Adding the functionality to ignore single/double quotes would severely alter the logic, with more ifs and checks and even a stack for keeping track of starting quotes.  Is such a scenario avoidable?  What method can make such additions painless and less compromising to working logic?


答:
There's no way to guard against all changes in requirements. No matter how you design your code, there always exists a requirement that'll force you to alter the functionality. Attempting to foresee all the possible changes is futile and ill-adviced - you'll end up with over-generalized and over-abstracted code, paying an up-front cost of increased complexity without knowing for sure it's going to pay off later. Worse, since there's always a change your code isn't protected against, there's no limit to how far you can overengineer your code.

The best you can do is code for the current set of requirements and adapt to change. If you keep your design modular, even if new additions require significant amounts of rework, you'll at least be fairly confident you're not inadvertently breaking completely unrelated functionality. Once you get burned by a particular kind of change, then you can make your code resistant to other changes of that same type. (If it happened once, there's a good chance it'll happen again.)


问:
Are patches a bad sign for the customer?
At the office we just got out of a long period where we released patches on a too-frequent basis. Near the end of that period we were doing almost three patches per week on average.

Beside that this was very demotivating for the developers, I was wondering what the customer would think about this. I asked the question myself and concluded that I never knew software that was updated that frequently. However, for the case that comes the closest I do not care really since the patches are pretty quickly applied.

The customers which received these patches differ a lot from each other. Some were really waiting for the patch where others did not really cared, yet they all got the same patches.
The time to update the customers software is less than 30 seconds, so I do not expect any problems concerning time. They do need to be logged out though.

So my question in more detail: Is getting updates frequently giving a 'negative' message to the receiver?

Of course, I could ask the customers, but I'm not in that position nor do I want to 'Awaken the sleeping dogs'.

PS: If there is anything I could do to improve my question, please leave a comment.

答:
I feel like releasing several patches in close proximity reflects poorly on the company.  It always makes me feel like they didn't test throughly enough up front, that the developers are incompetent, or the management has no idea what they are doing.

That being said, the other side of the token is that releasing several patches close to one another shows that the company is taking a proactive approach to their product and is continuing to improve their product for the consumer.

I'm more inclined to feel that the former is the way most will look at it from a consumer's standpoint, but speaking directly with them will (obviously) be the best choice, but will also raise the issue within the customer base that they may not have been aware of initially.


答:
As with many things in computing, it depends.  If the patches are a response to customer  requests for new features or improvements, then your company will be viewed as responsive.  If, on the other hand, your patches are a response to bug reports, then your company will be viewed as incompetent.

Testing software on your customers is by far the most expensive possible way to detect bugs, no matter what anyone says.  It's a false economy; the free labor that you think you're getting is more than offset by customer service effort, breaking the software development life-cycle, and losing customer confidence.

Title: Are patches a bad sign for the customer?

Body:
At the office we just got out of a long period where we released patches on a too-frequent basis. Near the end of that period we were doing almost three patches per week on average.

Beside that this was very demotivating for the developers, I was wondering what the customer would think about this. I asked the question myself and concluded that I never knew software that was updated that frequently. However, for the case that comes the closest I do not care really since the patches are pretty quickly applied.

The customers which received these patches differ a lot from each other. Some were really waiting for the patch where others did not really cared, yet they all got the same patches.
The time to update the customers software is less than 30 seconds, so I do not expect any problems concerning time. They do need to be logged out though.

So my question in more detail: Is getting updates frequently giving a 'negative' message to the receiver?

Of course, I could ask the customers, but I'm not in that position nor do I want to 'Awaken the sleeping dogs'.

PS: If there is anything I could do to improve my question, please leave a comment.


答:
Patches specifically for customers that have detected a problem are obviously going to need to go out as soon as possible.

I have seen software at large companies then take the approach that other customers will get those patches as a service pack at regular scheduled intervals. Normally because the patches take some effort to install and test in the customer environment but in your case it could just be used to lessen the possible impact of the effect you are concerned about.

I have also seen people advocate putting patches up in repositories or on websites where customers can download and install the ones they want to. This can create problems with knowing what patches which customers have, so when they call in with a problem you have to determine exactly what code they are running, but with care that can be tracked. You can then force people to upgrade to one of the larger 'packs' when one is released that bundles up lots of patches.

The exception are security patches. A large Washington based software company has been known to get into hot water by waiting for the third Thursday of the month before releasing critical security patches and information about the hack has leaked out and forced their hand early to even greater embarrassment.

Google chrome gets around the issue by auto updating very frequently, they too require you to cycle the program (restart chrome, or in your case log out). They have now made that normal practice for browsers and people don't even think about it any more. But not everyone can be Google.

SaaS applications get around the whole issue by doing the updates in the background.

However, above all, unless you are doing continuous integration or updating with new user requested features very frequently, then I think we are still in a time when people expect you to have done a decent amount of testing before release. If you would be embarrassed to meet your customers and talk about the frequency of bug fixes, you are probably not doing enough testing. Did you release how much of a risk you were taking before you released the code. There is an argument for releasing very early buggy code as long as you know that is what it is, but I think you need to have a good understanding of your known quality, which means understanding and keeping under control your time to know quality.


问:
Best practice for security checks, in surface or deep layer?
Let's take a server-side WebServices app, we need to make sure that all function applies every security rules, and keep the code clean.

In such a case, I usually prefer to place my security checks on the upper layers. As soon as the user call a function, I check if he has the rights to access it or not. But this strategy doesn't always works, if we need to retrieve infos from the database before performing all the checks, for instance.

Is this a bad idea? Should it be better to place security checks in deep layers, just before/after accessing database? I'm trying to figure out the best approach for a system that have a lot of security checks, and avoiding creating a big spaguetti.

The question could be like "What are the best practice to make sure an app is secure and the code is easy to maintain?".

答:
There are two facets to this problem and both should be satisfied for a good application to work:

Fail Fast - having the user fill all the data, press the action button, wait 5 seconds, only to fail since some text at the beginning of the form should be at least 3 characters, or a dash has been forgotten is a very bad experience - do your security and validation checks as close as possible to the beginning of the transaction, and fail it as soon as you discover a problem. This means that UI validations are very important for a smooth experience, and even checks on the server-side before the "heavy lifting" is important.

Trust no one - clients are easily hacked, service APIs are exposed to spoofing, 3rd party implementations may be lacking - don't trust that an earlier validation was made, and make sure as low as possible that your data remains consistent, and that the transaction is authorized. This is why you put constraints on your data tables, and not only count on the business logic to keep your data consistent.

Bottom line - each layer should make its own validations on its input, and on its output, even if that means that some validations are made more than once in a transaction. This might seem like it is 'less easy to maintain' since you may implement a validation more than once, but each validation has its own merit and its own importance - upper layer validation for better user experience, and lower layer validations for security.


答:
Treating security as a separate concern, and handling it in a layer above application logic is a good practice.

One project I was on was a great example. It involved a family of web services. The evolution of our authorization check went like this (it's a bit Java-centric, but hopefully the idea is clear):

First as a shared jar bundled into all the services.

However, as we tweaked the security logic, it forced us to rebuild and redeploy everything. Yuck.

Next a shared jar that implemented a JEE Filter, bundled with all the services.

This was better, but any tweak still required us to rebuild & redeploy everything.

Next as a Tomcat filter that we deployed with Tomcat, outside the .war file

Better still. But our tweaks still required a deployment & reboot of the Tomcat servers.

Finally as a reverse proxy that ran as its own service separate from the other services, which took all requests, and authorized and forwarded valid requests down to the right server, or else returned an "unauthorized" error.

And this worked like a charm, because changing the authorization concerns only required a rebuild and redeploy of one service -- the reverse proxy.

So, see, in that case we ended up abstracting security up and out of the service altogether.

I agree with your feeling that pushing security higher in the call stack as a gate makes the  implementation logic much cleaner and easier to handle. If you combine application logic with security checks, there's the risk of doing extra work before finding out (whoops) they aren't allowed to do step 3. Or worse, it might be a rollback situation where the app actually has to un-do what it did in step 2.

It's valuable to treat your security as a separate layer -- whether that layer is in code, a servlet filter, or an upstream proxy. Even if the security is a shopping list of actions, determine what they want to do up front, and then validate they are authorized to do all that before any actual work begins. That provides a really important separation of concerns.

...

Another practice that I've found that greatly simplifies security concerns is tying security rules to "roles" or "scopes". You cold say, client X wants to do operations X, Y and Z, and that requires scope M and P. A quick lookup (possibly cached) answers quickly whether the operations they want to do are covered by the scopes they have.

How broad or granular the scopes is just a design question, but allows you to be broad or granular as needed.

Title: Best practice for security checks, in surface or deep layer?

Body:
Let's take a server-side WebServices app, we need to make sure that all function applies every security rules, and keep the code clean.

In such a case, I usually prefer to place my security checks on the upper layers. As soon as the user call a function, I check if he has the rights to access it or not. But this strategy doesn't always works, if we need to retrieve infos from the database before performing all the checks, for instance.

Is this a bad idea? Should it be better to place security checks in deep layers, just before/after accessing database? I'm trying to figure out the best approach for a system that have a lot of security checks, and avoiding creating a big spaguetti.

The question could be like "What are the best practice to make sure an app is secure and the code is easy to maintain?".


答:
More and more companies follow in Chrome's footsteps and have more and more frequent customer releases.

The pre-requisite for implementing short release cycles is a painless upgrade - in chrome, for example, the upgrade is done without user intervention at all on application start-up, and if the user keeps his application always on, he receives a minor flag advising him to restart the application at his convenient time, and the application then makes the effort to return him to his previous state after the restart.

This method leaves the customer happy, as he does not need to be aware of every update, and since feature releases come frequently, bug fix releases will be just as welcome.

If, on the other hand, patches come after glaring show-stopper bugs, and they come in clusters, since the earlier ones failed to fix the bug, or created a greater bug - rest assured your customers will smell it. This will definitely reflect poorly on the vendor's professional reputation, and lower the vendor's perceived software standards. Continuous delivery relies heavily on effective unit testing and integration testing to guarantee its success.

On the matter of not talking to your customers to 'let sleeping dogs lie', I believe this is a wrong strategy - customers are not blind, and they are no fools. I believe that good communication with your customers can only reassure them that they are your priority, and that you are receptive to their criticism. If you have delivered bad releases a couple of times, and you do not hear them complain - you should definitely be worried - it is not that they did not notice, more likely they are just to busy finding a replacement for you...


问:
Are null references really a bad thing?
I've heard it said that the inclusion of null references in programming languages is the "billion dollar mistake".  But why?  Sure, they can cause NullReferenceExceptions, but so what?  Any element of the language can be a source of errors if used improperly.

And what's the alternative?  I suppose instead of saying this:

Customer c = Customer.GetByLastName("Goodman"); // returns null if not found
if (c != null)
{
    Console.WriteLine(c.FirstName + " " + c.LastName + " is awesome!");
}
else { Console.WriteLine("There was no customer named Goodman.  How lame!"); }
```

<p>You could say this:</p>

<pre class="lang-cs prettyprint-override"><code>if (Customer.ExistsWithLastName("Goodman"))
{
    Customer c = Customer.GetByLastName("Goodman") // throws error if not found
    Console.WriteLine(c.FirstName + " " + c.LastName + " is awesome!");
}
else { Console.WriteLine("There was no customer named Goodman.  How lame!"); }
</code>```

But how is that better?  Either way, if you forget to check that the customer exists, you get an exception.

I suppose that a CustomerNotFoundException is a bit easier to debug than a NullReferenceException by virtue of being more descriptive.  Is that all there is to it?

答:
(Throwing my hat in the ring for an old question ;) )

The specific problem with null is that it breaks static typing.

If I have a Thing t, then the compiler can guarantee I can call t.doSomething(). Well, UNLESS t is null at runtime. Now all bets are off. The compiler said it was OK, but I find out much later that t does NOT in fact doSomething(). So rather than being able to trust the compiler to catch type errors, I have to wait until runtime to catch them. I might as well just use Python!

So, in a sense, null introduces dynamic typing into a statically typed system, with expected results.

The difference between that an divide by zero or log of negative, etc. is that when i = 0, it's still an int. The compiler can still guarantee its type. The problem is that the logic mis-applies that value in a way that isn't permitted by the logic ... but if the logic does that, that's pretty much the definition of a bug.

(The compiler can catch some of those problems, BTW. Like flagging expressions like i = 1 / 0 at compile time. But you can't really expect the compiler to follow into a function and ensure that the parameters are all consistent with the function's logic)

The practical problem is that you do a lot of extra work, and add null checks to protect yourself at runtime, but what if you forget one? The compiler stops you from assigning:

String s = new Integer(1234);

So why should it allow assignment to a value (null) that will break de-references to s?

By mixing "no value" with "typed" references in your code, you're putting an extra burden on the programmers. And when NullPointerExceptions happen, tracking them down can be even more time consuming. Rather than relying on static typing to say "this is a reference to something expected," you're letting the language say "this may well be a reference to something expected."

Title: Are null references really a bad thing?


问:
Regarding interfaces of classes in OOP
When one says "a class' interface":

Does he/she refer to all of the get and set methods - or do they refer only to the methods' signatures and return types, without the inner implementation of these methods? (Aka, the implementation of a 'get' method isn't considered part of the interface, but rather part of the inner implementation of the class. The interface is the return type for that method and the signature of that method).

答:
If you're doing interfaces properly, the interface consists of the signature of the methods and the model semantics of the methods. That second part is important — you almost certainly wouldn't want a SumTheColumnContents method to actually launch a preemptive thermonuclear strike on the neighbors prized goldfish — yet it's not really all that possible for the compiler to enforce. (Determining when two general pieces of code do the same thing is A Stupendously Hard Problem, as it includes the famous Halting Problem, and indeed most interesting challenges in mathematical proofs, as sub-problems.) So you have to be well-behaved and not go round doing nasty things. Of course, this is just the good old Liskov Substitution Principle with a fully abstract class as the superclass; if the semantics of the subclasses are wildly different, they won't be interchangeable with each other even even if the signature is the same.

This is all independent of how some random programming language describes or implements an interface. It's a much more general concept than that. (Yes, some call them “interfaces”, and others call them “protocols”, and some just call them “abstract superclasses”. The idea is still the same.)

Title: Regarding interfaces of classes in OOP


答:
The interface doesn't include implementation details, by definition.  It's the way you interact with the 'thing', so another 'thing' could be created which does the same thing, even if its innards are completely different.

The problem with get and set methods is that they tell you what they're doing to the innards of the thing.  A method named .getZebra() tells me that there's a variable named zebra in that thing; otherwise it would have been named .zebra(), and you wouldn't know whether it's stored or calculated or what.

If someone wants to come along and reimplement your thing differently (possibly you, later on), and your interface is sprinkled with getters and setters, then there's a choice of a) breaking the interface, b) using the same variables to represent it, constraining the design unnecessarily, or c) simulating the presence of those variables in the new code, complicating the design unnecessarily.   It's possible that you might get lucky and that your interface is nice and you won't need to do those things, but if you use names like getX() and setY(), you're thinking in terms of the variables x and y that you have, not what they represent abstractly.

Setters also force your object to be mutable, and the meaning of what you're trying to do may not require that.

The implementation of getters and setters is not guaranteed by the words 'get' or 'set', so technically you can say that they're part of the class interface and that therefore there's no encapsulation violation, but really there is.  Programmers use words to mean something, and when they put 'get' or 'set' at the beginning of a method name, they're saying "this is implemented as a variable".

The inside and outside of a class (or object) are at different levels of abstraction; the inside is all about how it's done, the outside is all about what can be done.  The naming should reflect the distinction.

If you find yourself writing an object that has lots of getters and setters, and you can't find a reasonable way to rename them, what you have is probably a data structure, not an object.

Title: Regarding interfaces of classes in OOP

Body:
When one says "a class' interface":

Does he/she refer to all of the get and set methods - or do they refer only to the methods' signatures and return types, without the inner implementation of these methods? (Aka, the implementation of a 'get' method isn't considered part of the interface, but rather part of the inner implementation of the class. The interface is the return type for that method and the signature of that method).


答:
I love the buzz words that this site generates. I am tasked frequently with interviewing programmers. It is common to have several levels of interviews:

Education / Employment / Experience

This is where we ask your previous employers if they would hire you again. If the job said "[insert degree here] or related experience", we've phoned your university to verify things, or had someone capable of ingesting 'related experience' report on it. Nothing much to see here.

Additionally, if the job you seek requires additional clearance, we'll investigate the possibility of obtaining that.

Finally, we need to know if you might be a good fit, and move you on to the next step.

Technical interview

You will be interviewed by a peer. You will be asked to solve problems, give insights into emerging things, and then asked to pick out mistakes in presumptions that you interviewer just presumed. We want to not only gauge your experience, we want to see what happens when someone in authority is obviously wrong.

Background

Sometimes, we do have to conduct a background check.

By this time, a fellow hacker has interviewed and endorsed you. If you are unfortunate enough to talk to a company psychologist to determine your 'suitability' beyond that .. run, and run like hell.

Seriously, run. If the hiring manager must defer to a HR bot to determine how you might fit in, you don't want to work there. Run away, fast ... if for no other reason than avoiding needless complexity that will likely introduce needless complexity in whatever they ask you to produce.

Title: What's a "Professional Fit" interview?


答:
There's plenty of excellent answers that cover the unfortunate symptoms of null, so I'd like to present an alternative argument: Null is a flaw in the type system.

The purpose of a type system is to ensure that the different components of a program "fit together" properly; a well-typed program can't "off the rails" into undefined behavior.

Consider a hypothetical dialect of Java, or whatever your preferred statically-typed language is, where you can assign the string "Hello, world!" to any variable of any type:

Foo foo1 = new Foo();  // Legal
Foo foo2 = "Hello, world!"; // Also legal
Foo foo3 = "Bonjour!"; // Not legal - only "Hello, world!" is allowed
```

<p>And you can check variables like so:</p>

<pre class="lang-cs prettyprint-override"><code>if (foo1 != "Hello, world!") {
    bar(foo1);
} else {
    baz();
}
</code>```

There's nothing impossible about this - someone could design such a language if they wanted to. The special value need not be "Hello, world!" - it could've been the number 42, the tuple (1, 4, 9), or, say, null. But why would you do this? A variable of type Foo should only hold Foos - that's the whole point of the type system! null is not a Foo any more than "Hello, world!" is. Worse, null is not a value of any type, and there's nothing you can do with it!

The programmer can never be sure that a variable actually holds a Foo, and neither can the program; in order to avoid undefined behavior, it has to check variables for "Hello, world!" before using them as Foos. Note that doing the string check in the previous snippet doesn't propagate the fact that foo1 is really a Foo - bar will likely have its own check as well, just to be safe.

Compare that to using a Maybe/Option type with pattern matching:

case maybeFoo of
 |  Just foo => bar(foo)
 |  Nothing => baz()
```

Inside the Just foo clause, both you and the program know for sure that our Maybe Foo variable truly does contain a Foo value - that information is propagated down the call chain, and bar doesn't need to do any checks. Because Maybe Foo is a distinct type from Foo, you're forced to handle the possibility that it could contain Nothing, so you can never by blindsided by a NullPointerException. You can reason about your program much more easily and the compiler can omit null checks knowing that all variables of type Foo really do contain Foos. Everyone wins.

Title: Are null references really a bad thing?

Body:
I've heard it said that the inclusion of null references in programming languages is the "billion dollar mistake".  But why?  Sure, they can cause NullReferenceExceptions, but so what?  Any element of the language can be a source of errors if used improperly.

And what's the alternative?  I suppose instead of saying this:

Customer c = Customer.GetByLastName("Goodman"); // returns null if not found
if (c != null)
{
    Console.WriteLine(c.FirstName + " " + c.LastName + " is awesome!");
}
else { Console.WriteLine("There was no customer named Goodman.  How lame!"); }
```

<p>You could say this:</p>

<pre class="lang-cs prettyprint-override"><code>if (Customer.ExistsWithLastName("Goodman"))
{
    Customer c = Customer.GetByLastName("Goodman") // throws error if not found
    Console.WriteLine(c.FirstName + " " + c.LastName + " is awesome!");
}
else { Console.WriteLine("There was no customer named Goodman.  How lame!"); }
</code>```

But how is that better?  Either way, if you forget to check that the customer exists, you get an exception.

I suppose that a CustomerNotFoundException is a bit easier to debug than a NullReferenceException by virtue of being more descriptive.  Is that all there is to it?

Body:
There's plenty of excellent answers that cover the unfortunate symptoms of null, so I'd like to present an alternative argument: Null is a flaw in the type system.

The purpose of a type system is to ensure that the different components of a program "fit together" properly; a well-typed program can't "off the rails" into undefined behavior.

Consider a hypothetical dialect of Java, or whatever your preferred statically-typed language is, where you can assign the string "Hello, world!" to any variable of any type:

Foo foo1 = new Foo();  // Legal
Foo foo2 = "Hello, world!"; // Also legal
Foo foo3 = "Bonjour!"; // Not legal - only "Hello, world!" is allowed

And you can check variables like so:

if (foo1 != "Hello, world!") {
    bar(foo1);
} else {
    baz();
}

There's nothing impossible about this - someone could design such a language if they wanted to. The special value need not be "Hello, world!" - it could've been the number 42, the tuple (1, 4, 9), or, say, null. But why would you do this? A variable of type Foo should only hold Foos - that's the whole point of the type system! null is not a Foo any more than "Hello, world!" is. Worse, null is not a value of any type, and there's nothing you can do with it!

The programmer can never be sure that a variable actually holds a Foo, and neither can the program; in order to avoid undefined behavior, it has to check variables for "Hello, world!" before using them as Foos. Note that doing the string check in the previous snippet doesn't propagate the fact that foo1 is really a Foo - bar will likely have its own check as well, just to be safe.

Compare that to using a Maybe/Option type with pattern matching:

case maybeFoo of
 |  Just foo => bar(foo)
 |  Nothing => baz()

Inside the Just foo clause, both you and the program know for sure that our Maybe Foo variable truly does contain a Foo value - that information is propagated down the call chain, and bar doesn't need to do any checks. Because Maybe Foo is a distinct type from Foo, you're forced to handle the possibility that it could contain Nothing, so you can never by blindsided by a NullPointerException. You can reason about your program much more easily and the compiler can omit null checks knowing that all variables of type Foo really do contain Foos. Everyone wins.


问:
When not to move a "C style" code to "C++ or Object Oriented" code?
Context

I am (part of team A) developing a piece of functionality which depends on new APIs provided by team B. Old APIs (also provided by Team B) are there and this is how they are being used in our code...

```<code>int someFunction() {
 //-- lots of code here
 oldAPI.func1();
 //-- lots of code again
 if (something)
     oldAPI.func2();
 else oldAPI.func3();
 //lots of code
 // ans so on
 }
</code>```

We needed to complete it quickly,So I just modify the existing flow to use newAPI and tested it with some placeholder calls.

Soon after I completed... Team B informed us that they will take more time.

Now I have two options...

Option 1: Wait for Team B to complete; push your code along/after them

Option 2: Make your code support both old and new; based on a configuration.

if we choose option 2; there are two approaches...

Approach 1: Modularize your code; and use polymorphism in your code.

```<code> class API_BASE {virtual funct1(),func2(),func3()};
 class API_OLD : API_BASE {funct1(),func2(),func3()};
 class API_NEW : API_BASE {funct1(),func2(),func3()};
</code>```

Approach 2: use plain conditional logic

```<code>if (newAvailable)
    useNew();
else
    useOld();
</code>```

Questions

If possibilities of supporting multiple flow in future is very less(say 15%); but u need to support them for some time (say few months), would you modify a code written in procedural way to support OOPs? I see benefit of maintainability, readability and easy to extend code. But what is the smart way?

In legacy lode base... what is the ideal time to refactor code? You touch one file once in a year and move to other. Provide I have time... should I refactor an stable/running code, or should I do it when there is a real need to refactoring (how to define that I dont know)

In big software companies... team works in there own boundaries. If team A completes his job, it wants to push to production sooner and announce to world (mgmt, team b) etc that we are done. Until we have everything ready (i.e. A's part and B's Part), for end user (QA/Customer) there is no change is functionality. Is this a good way of thinking? should I concentrate more on my part, and let mgmt worry about bigger picture?

答:
Option 1.

Team B advertised the API and their schedule estimate.  You took them at their word, you designed to their interface design specification.  You're done, you're now available to work other tasks in the backlog.  It isn't your fault that their schedule estimate was not perfect.

Either of the approaches to Option 2 makes your code more verbose and less maintainable.  That's the LAST thing you want to do.

If they pulled their estimate in because of political pressure (it happens, far too often), they need to man up and take their medicine - and so does the clown who applied the pressure.

To answer your questions:

Do it right the first time, and then LEAVE it.  Heinlein put this as "Write, finish what you write, then LEAVE IT ALONE AND SEND IT OUT FOR PUBLICATION."  He was right.

Refactor when you AREN'T in the middle of a push to finish something else, like you are right now, when the entire code base ISN'T in flux, like it is right now.  In other words, NOT NOW.

The focus has to be on completing the parts, and then integrating the parts.  If Part A is done, Team A can be assigned to help Team C on Part C.  Once Part A is finished, Team A should not continue to monkey with it just because Team B is running late.

These are probably not the answers you wanted to hear, but they are the answers that hopefully maximize your odds of actually shipping working product.


答:
POST is the "append" verb, and also the "processing" verb. PUT is the "create/update" verb (for known identifiers), and almost looks like the right choice here, because the full target URI is known. projectId and siteId already exist, so you don't need to "POST to a collection" to produce a new ID.

The problem with PUT is that it requires the body be the representation of the resource you're PUTting. But the intent here is to append to the "project/sites" collection resource, rather than updating the Site resource.

What if someone PUTs a full JSON representation of an existing Site? Should you update the collection and update the object? You could support that, but it sounds like that's not the intent. As you said,

the only data I really need are ProjectId and SiteId

Rather, I'd try POSTing the siteId to the collection, and rely on the "append" and "process" nature of POST:

POST myapi/projects/{projectId}/sites

{'id': '...' }

Since you're modifying the sites collection resource and not the Site resource, that's the URI you want. POST can know to "append/process" and add the element with that id to the project's sites collection.

That still leaves the door open to creating brand new sites for the project by fleshing out the JSON and omitting the id. "No id" == "create from scratch". But if the collection URI gets an id and nothing else, it's pretty clear what needs to happen.

Interesting question. :)

Title: What is the best pattern for adding an existing item to a collection in REST API?

Body:
I'm designing a pragmatic REST API and I'm a little stuck on how best to add existing entities to a collection. My domain model includes a Project that has a collection of Sites. This is a strict many-to-many relationship and I have no need to create an entity that explicitly models the relationship (i.e. ProjectSite).

My API will allow consumers to add an existing Site to a Project. Where I'm getting hung up is that the only data I really need are ProjectId and SiteId. My initial idea was:

```<code>1. POST myapi/projects/{projectId}/sites/{siteId}
</code>```

But I also thought about

```<code>2. POST myapi/projects/{projectId}/sites
</code>```

with a Site entity sent as JSON content.

Option 1 is simple and works but doesn't feel quite right, and I have other relationships that cannot follow this pattern so it adds inconsistency to my API.

Option 2 feels better but leads to two concerns:

Should I create a Site or throw an exception if a new Site is posted (SiteId = 0)?

Because I only need ProjectId and SiteId to create the relationship, the Site could be posted with wrong or missing data for other properties.

A 3rd option is to provide a simple endpoint solely for creating and deleting the relationship. This endpoint would expect a JSON payload containing just ProjectId and SiteId.

What do you think?


问:
Should I always use "is" as prefix for boolean variables?
Should I always use is as prefix for boolean variables? What about booleans that indicate something in past? Should I write isInitialized or wasInitialized? Should I write for properties IsManyMembers or HasManyMembers?

Is there any best practices? Or I should just write in accordance with English rules?

答:
I'd go with English rules.
I tend to think about the next coder that is going to look at your work being an axe wielding maniac that is going to come after me if the code is hard to understand. When I keep this in mind the best option for my health is to keep the code clean and easy to read, which means the best English and domain language possible. </p>

ContentLicense: CC BY-SA 4.0


答:
Not really, as booleans are not always used to indicate that an object "is" something.

"has" is an equally valid prefix "was", "can" are also valid in particular circumstances, also, I have seen the suffix "Able" used.

```<code>So Object herring:-
 isFish = true
 isCat = false
 hasScales = true
 hasFur = false
 canSwim = true
 wasEgg = true
 eatAble = true

Object moggy:-
 isFish = false
 isCat = true
 hasScales = false
 hasFur = true
 canSwim = false
 wasEgg = false
 eatAble = false
</code>```

It all depends on what makes the program readable.

Title: Should I always use "is" as prefix for boolean variables?

Body:
Should I always use is as prefix for boolean variables? What about booleans that indicate something in past? Should I write isInitialized or wasInitialized? Should I write for properties IsManyMembers or HasManyMembers?

Is there any best practices? Or I should just write in accordance with English rules?

Body:
Not really, as booleans are not always used to indicate that an object "is" something.

"has" is an equally valid prefix "was", "can" are also valid in particular circumstances, also, I have seen the suffix "Able" used.

So Object herring:-
 isFish = true
 isCat = false
 hasScales = true
 hasFur = false
 canSwim = true
 wasEgg = true
 eatAble = true

Object moggy:-
 isFish = false
 isCat = true
 hasScales = false
 hasFur = true
 canSwim = false
 wasEgg = false
 eatAble = false

It all depends on what makes the program readable.


问:
Read-only class properties
When is recommended to use read-only properties -- if the language allows me?

Are public read-only properties meant to replace getter methods or at least the Magic Methods like what is available as __get() in PHP for example?

What is the use of a private read-only property?

答:
read-only properties are assigned only once - on the initialization of the instance.

It is different from getters, since getters allow the instance itself to change the value of the property. It is different from constants, since constants are assigned on the class declaration.

One use-case for read-only properties is to define immutable objects, another is in the definition of static read-only for a singleton implementation.

Other use-cases may be in container properties (like lists and dictionaries), in which it is intended that their contents might change, but the collection itself stays with the instance for all its life-cycle. This way you can be sure that they are never nullified.

These are some use-cases of the top of my head, I'm sure that there are more...

Title: Read-only class properties


答:
Exceptions are not eval!

They are there for a reason. If your code is running bad, there is a genius pattern, called exception, and it tells you that some thing is wrong.

By avoiding using null objects you are hiding part of those exceptions. I am not spiking about OP example where he convert null pointer exception to well typed exception, this might actually be good thing as it increase readability. How ever when you take the Option type solution as @Jonas pointed out, you are hiding exceptions.

Than in your production application, instead of exception to be thrown when you are clicking on button to select empty option, nothing just happening. Instead of null pointer exception would be thrown and we would probably get a report of that exception(as in many production applications we have such mechanism), and than we could actually fix it.

Making your code bulletproof by avoiding exception is bad idea, making you code bulletproof by fixing exception, well this the path that I would choose.

Title: Are null references really a bad thing?


问:
Design: Mixed XML / Relational or Pure Relational?
Is it acceptable to model a very complex object graph using XML in the database, but leave the rest of a system in relational tables?

I'd like to gauge opinion on this as I've hit a bit of a conundrum.

Many thanks

--------------------

Background

I'm building a financial application which, although not at all large in terms of data storage ( <= tens of megabytes initially), will have a very complex data model.

Specifically, users will be working within the context of a "Project" entity, which will contain various sub-entities and lists.  The users will be able to add formulae to diverse parts of this object graph and they will be continuously recalculated in realtime.

The complexity comes in two parts:

No matter where in the class hierarchy a formula is located, it will be able to reach any other part of the same parent project entity using a path-like syntax.  This will include the results of other formulae, and I will be implementing all of this with an in-memory dependency tree on a middle tier.

I'd like all the formulae to have the same basic structure, metadata, etc.  To accomplish this, all formulae will be represented by the same class structure in code, regardless of which part of the data graph they are attached to.

I'd much rather have the whole thing in a document - it would mean much less time spent fussing with database design, and I'd be able to have a much richer object model for the same amount of effort.  I'm worried though about relational integrity - I'd still want to store my static data in relational tables.

Technologies

SQL Server 2012.

.Net 4.5 (via C#)

Entity Framework (database first) on the middle tier

Simple auto-generated DTOs over WCF for services

WPF with Prism on the client.

I've not considered NoSQL storage ideas, largely because I don't have enough experience of them for a project with tight timelines.  I've also not considered Entity Framework code-first, for the same reason.

答:
Is it acceptable to model a very complex object graph using XML in the database, but leave the rest of a system in relational tables?

Absolutely, as long as you know what you are doing, and you know what it is good for. For example, modeling your object graph as an XML document won't let you change parts of that XML concurrently by different users. And it will make SQL queries more complex when querying for a property within the XML (note that SQL Server has a lot of direct XML support). On the other hand, you will gain the flexibility you already mentioned in your post. So when the advantages outweigh the disadvantages, there's no reason to stick dogmatically to "only relational" or "only XML".


问:
What is a O(n) algorithm to solve this puzzle?
We are going to hold a meeting where everybody will speak in clockwise direction around a table. There are n people with n spots. Each person has a position preference (e.g. some want to go first, some last, etc). Everyone is seated randomly and cannot move from their position. How shall we compute the best starting position on the table to satisfy the most people?

I have an O(n^2) solution:
See how many people would be satisfied having assumed each of the positions 1..n as start positions; then return the position that gave the maximum value.

答: If each person knows exactly what order he wants to go in and the seating order is constant, then each person knows what starting position he wants the speaking to start at. This way, you can calculate how many people want speaking start at specific points, which is O(n) in complexity if you the preferred position as index into array.</p>


答:
A fairly simple O(n) algorithm exists:

Let pos be an array so that if the person at seat i wants to speak as n-th, we have an entry pos[i] = n. Where the numbering of the seats starts is irrelevant. Both i and n start counting with zero.

The difference i - pos[i] is the seat where the round would have to start for the person at seat i to be satisfied. We count the satisfied persons per start position in a satisfied array. We can then find the maximum of that array, the index of the maximum is the seat where the round should start for maximum satisfaction.

Java example:

int findBestStart(int[] pos) {
    // ask each seat where they'd like to start
    int[] satisfied = new int[pos.length];
    for (int i = 0; i < pos.length; i++) {
        int start = i - pos[i]
        if (start < 0) start += pos.length;
        satisfied[start]++;
    }

    // find where most would like to start
    int bestSeat = -1;
    int bestSatisfied = -1;
    for (int i = 0; i < satisfied.length; i++) {
        if (satisfied[i] > bestSatisfied) {
            bestSeat = i;
            bestSatisfied = satisfied[i];
        }
    }

    return bestSeat;
}
```

Title: What is a O(n) algorithm to solve this puzzle?

Body:
We are going to hold a meeting where everybody will speak in clockwise direction around a table. There are n people with n spots. Each person has a position preference (e.g. some want to go first, some last, etc). Everyone is seated randomly and cannot move from their position. How shall we compute the best starting position on the table to satisfy the most people?

I have an O(n^2) solution:
See how many people would be satisfied having assumed each of the positions 1..n as start positions; then return the position that gave the maximum value.


问:
Understanding dependency injection
I'm reading about dependency injection (DI). To me, it is a very complicated thing to do, as I was reading it was referencing inversion of control (IoC) as well and such I felt I was going to be in for a journey.

This is my understanding: Instead of creating a model in the class which also consumes it, you pass (inject) the model (already filled with interesting properties) to where it is needed (to a new class which could take it as a parameter in the constructor).

To me, this is just passing an argument. I must have miss understood the point? Maybe it becomes more obvious with bigger projects?

My understanding is non-DI (using pseudo code):

```<code>public void Start()
{
    MyClass class = new MyClass();
}

...

public MyClass()
{
    this.MyInterface = new MyInterface();
}
</code>```

And DI would be

```<code>public void Start()
{
    MyInterface myInterface = new MyInterface();
    MyClass class = new MyClass(myInterface);
}

...

public MyClass(MyInterface myInterface)
{
    this.MyInterface = myInterface;
}
</code>```

Could some one shed some light as I'm sure I'm in a muddle here.

答:
Well yes, you inject your dependencies, either through a constructor or through properties.

One of the reasons for this, is not to encumber MyClass with the details of how an instance of MyInterface needs to be constructed. MyInterface could be something that has a whole list of dependencies by itself and the code of MyClass would become ugly very fast if you had instantiate all the MyInterface dependencies inside of MyClass.

Another reason is for testing.

If you have a dependency on a file reader interface and you inject this dependency through a constructor in, say, ConsumerClass, that means that during testing, you can pass an in-memory implementation of the file reader to the ConsumerClass, avoiding the need to do I/O during testing.

Title: Understanding dependency injection


问:
How to introduce testing in the development cycle
In our company, we are only two IT staffs, and I'm the only developper. I'm developping rich intranet applications using plain php and extjs as javascript framework.

Our development cycle is usually very fast, such that often people are using tomorrow what I develop today. This is possible through an automated build script.

Now the problem:

It happens, that despite all the care, things break. And myself or the end users will notice it once the application update is published. Of course a testing framework (or mabe two, one for php and one for js) would be the solution. But this looks to me just as an unsurmountable barrier, because of these points:

I never used a testing framework, and lack necessary knowledge

A testing framework puts constraints on the way code is written (and I cannot judge for now, if my code fits any particular framework). I therefore fear that I had to refactor my code to be able to use a testing framework.

I fear that writing the tests is likely to take more time than to write the code.

Much of the code depends on the data present in different databases. How to make up mock data that can be used for testing.

Can someone give me advice on how to introduce a testing framework in a setting where proficiency and time are scarce ? I know this question is really broad, but I hope I will get nonetheless some precious advices.

Edit:

It took me several months before I dared to dive into Unit testing, and it took me just one hour to get up und testing. It will take me some hours more to include this permanently into the build process.

I really feared too much !!

Unit testing is not more work (or just slightly more) than testing with echo's and var_dump's. The advantage is that it is permanent. Once you change some code, and the test still works your done. There's no need any more to retest manually.

答:
I agree that the question is broad, but I'd consider it borderline answerable. So here's my take.

Doing something for the first time takes longer than doing a well-known thing, but for a professional, time to improve your efficiently in a lasting way is almost always worthwhile. It shouldn't take more than a day to pick up enough of a testing framework to automate some of the things you need, and that will probably pay for itself sooner rather than later.

Testing frameworks can impose restrictions on your code structure, but usually they go out of their way to minimize that. The conditions they do make are usually things that are a good idea for healthy, maintainable code anyway (small functions, single responsibility, orthogonality, etc.)

Spending more time on tests than on production code can happen - in fact, some people claim this is the normal and expected way of programming - but that is not what you should be measuring. The value to optimize is total turnaround time on the requested features at an acceptable quality; the fact that test automation tools have many satisfied, even enthusiastic users is at least mild evidence that this can be pulled off.

This is least easily answerable without context. The general trend of opinion is that anything which interacts with a database isn't a unit test, but an integration test. Testing code that is coupled to databases poses a problem with several kinds of solutions: invent your own primitive mock database; take advantage of mock databases offered by testing frameworks; switch use an in-memory database or just put one on a really fast drive, etc.