答:
Be strategic and specialize. Target one industry and develop a standardized software solution for that industry that you can improve and customize over time. This will accomplish several things for you:

Rather than duplicating code for each project, you'll be building off previous work.

Each client you add will expand your software ecosystem as you add new features for their needs. And it will all be paid for.

Software quality will improve over time as you're able to add unit tests and fix bugs reported by multiple clients.

Specializing and focusing on a single industry vertical will help you earn a reputation in that market. That, in turn, will allow you to charge more.

Defining your target market will also help you hone your marketing message. Once you're able to optimize your sales funnel, it should pay for itself.

When choosing a specific industry to target, it'll take both a strong business sense and a strong development lead, so you'll have to work together with your non-technical founders to identify the best opportunity. In particular, here are some things you should consider:

Do market research. Talk to people, discover market pain points, and use that information to help inform your product selection.

Choose an industry that has a big enough problem that you can solve that they're willing to pay significant money for it.

Look at the difficulty of breaking into the market. How entrenched are the established players?

Find a market that is big enough to make it worth it.

Select a problem that can be at least partially solved quickly with a minimal solution at first. This will enable you to have a low startup cost and you'll be able to iterate with each new client.

Structure your contracts so that you retain ownership to all source code.

Factor in the cost of finding new clients. How costly is client acquisition versus their potential value to you?

Repeatedly target the same client profile, especially in the beginning.

Consider constructing a business model that allows you to charge clients regularly, either through license fees or subscription fees. SaaS will give you a predictable income, which stabilizes your financial situation and will allow you to add developers over time and pay existing developers what they're worth.

Think about how your software could potentially be used and adapted in other industries once you become in one market. Develop accordingly.

Update: I can't be completely sure from your comment, but it sounds like part of the problem might be a lack of focus from the marketing side. Perhaps an example might help:

Google Adwords is a popular method of advertising, but unfortunately, it's very easy to waste a lot of money for not very many results. Some people will buy ads for a lot of keywords related to their market, not realizing that there is a difference between broad match and phrase match keywords. They also ignore the fact that some search queries have high commercial intent and some have low commercial intent. And they may not be aware that there is a serious difference in the effectiveness of ads on search engine results pages and ads on a regular website or that ads at the top of the page perform better than ads lower on the page.

And what about the ad text? Is the title link compelling? Does it state the problem the searcher has and offer hope for a solution? Have multiple variations of the ad been tested?

What's more, it's not just the ad that matters. Does the landing page match the promise of the ad copy? What is the conversion rate of your landing page once people arrive? How can that be improved?

Suppose you're selling a product online and that your landing page has a conversion rate of 2% for paid customers. Now suppose that your CPC (cost-per click) is around $5 and that your average one-time transaction is $150. For every paid customer, you'll need an average of 50 people to visit your site, which means that you'll need to spend $250 in advertising. Clearly, it isn't worth it. You're losing $100 on every transaction, so what do you do?

In the scenario above, you have 3 variables: your conversion rate of 2%, your CPC of $5, and your average transaction value of $150. What would happen if you could double your conversion rate to 4%? Your average acquisition cost would drop $125, meaning that you're making $25 instead of losing $100. What if you find a keyword that has a CPC of only $2.50? Again, your advertising cost is reduced from $250 to $125. What if you're able to bring the average transaction value up through upsells or by providing incentive for repeat sales? Suddenly, you're profitable.

It would incredibly wasteful in a financial sense to try to fine-tune your Adwords advertising like this if you're running 30 campaigns concurrently. The best approach is to focus on one campaign at a time. Test it, optimize it, make it profitable. Start with small amounts of money (but enough to test it for meaningful results). Once you have it tuned to the point that you know, for every X dollars spend on advertising, you'll make Y dollars in revenue, then you can safely expand your advertising budget on that keyword campaign to as much as you can handle. And when you're assured that you have one profitable campaign, then move on to the next one, incorporating the lessons you learned from the first. Rinse, repeat.

It sounds like you might be running 30 campaigns at once, but in a macro sense, going after all types of customers, hoping that one of them might stick. You might get lucky, but I think you may be better off figuring out what type of customer makes the most sense for your company and then targeting them exclusively. There are so many moving parts to the sales funnel that it will take time to optimize it. You can't optimize it if you're targeting multiple groups. If you don't develop a process, this problem won't just go away over time. By trying to do everything, you may end up doing nothing.

I would try to identify your biggest opportunity that has the lowest development cost and start there. Refine your marketing and iterate on a product. Try to find a business model for recurring revenue. Once you have a well-oiled machine in that market, take it to the next market, using everything you learned. Best of luck!

Title: How can we unify business goals and technical goals?

Body:
Some background

I work at a small startup: 4 devs, 1 designer, and 2 non-technical co-founders, one who provides funding, and the other who handles day-to-day management and sales. Our company produces mobile apps for target industries, and we've gotten a lot of lucky breaks lately. The outlook is good, and we're confident we can make this thing work.

One reason is our product development team. Everyone on the team is passionate, driven, and has a great sense of what makes an awesome product. As a result, we've built some beautiful applications that we're all proud of.

The other reason is the co-founders. Both have a brilliant business sense (one actually founded a multi-million dollar company already), and they have close ties in many of the industries we're trying to penetrate. Consequently, they've brought in some great business and continue to keep jobs in the pipeline.

The problem

The problem we can't seem to shake is how to bring these two awesome advantages together. On the business side, there is a huge pressure to deliver as fast as possible as much as possible, whereas on the development side there is pressure to take your time, come up with the right solution, and pay attention to all the details.

Lately these two sides have been butting heads a lot. Developers are demanding quality while managers are demanding quantity.

How can we handle this? Both sides are correct. We can't survive as a company if we build terrible applications, but we also can't survive if we don't sell enough. So how should we go about making compromises?

Things we've done with little or no success:

Work more (well, it did result in better quality and faster delivery, but the dev team has never been more stressed out before)

Charge more (as a startup, we don't yet have the credibility to justify higher prices, so no one is willing to pay)

Extend deadlines (if we charge the same, but take longer, we'll end up losing money)

Things we've done with some success:

Sacrifice pay to cut costs (everyone, from devs to management, is paid less than they could be making elsewhere. In return, however, we all have creative input and more flexibility and freedom, a typical startup trade off)

Standardize project management (we recently started adhering to agile/scrum principles so we can base deadlines on actual velocity, not just arbitrary guesses)

Hire more people (we used to have 2 developers and no designers, which really limited our bandwidth. However, as a startup we can only afford to hire a few extra people.)

Is there anything we're missing or doing wrong? How is this handled at successful companies?

Thanks in advance for any feedback :)


问:
What exactly is "Web API" in ASP.Net MVC4?
I know what a Web API is.

I've written API's in multiple languages (including in MVC3).

I'm also well practiced in ASP.Net.

I just discovered that MVC4 has "Web API" and without going through the video examples I can't find a good explanation of what exactly it IS.

From my past experience, Microsoft technologies (especially ASP.Net) have a tendency to take a simple concept and wrap it in a bunch of useless overhead that is meant to make everything "easier".

Can someone please explain to me what Web API in MVC4 is exactly?  Why do I need it?  Why can't I just write my own API?

答:
ASP.NET Web API is a "non-opinionated" framework to build HTTP Service regardless of REST or RPC. It is Microsoft's best implementation of RFC 2616 (HTTP Spec).

Certainly you can build your own API but ASP.NET Web API:

Built based on the Russian Doll model which allows for lego-like modules to be added to the HTTP pipeline

Makes HTTP first class citizen so all common headers are strongly typed (not just name value) and helps with parsing them

Allows for both ASP.NET (IIS) hosting or self-hosting

supports content negotiation, media types, ...

Is Async from top to bottom

Uses a similar approach for clients with HttpClient

ContentLicense: CC BY-SA 3.0


问:
Why did the web win the space of remote applications and X not?
The X Window System is 25 years old, it had it's birthday yesterday (on the 15'th).

As you probably are aware of, one of it's most important features is the separation of the server side and the client side in a way that neither Microsoft's, Apples or Wayland's windowing systems have.

Back in the days (sorry for the ambiguous phrasing) many believed X would dominate over other ways to make windows because of this separation of server and client, allowing the application to be ran on a server somewhere else while the user clicks and types on her own computer at home.

This use obviously still exists, but is marginalized at best. When we write and use programs that run on a server we almost always use the web with it's html/css/js.

Why did the web win, and X not? The technologies used for the web (said html/css/js) are a mess. Combined with all the back-end-frameworks (Rails, Django and all) it really is a jungle to navigate thru. Still the web thrives with creativity and progress, while remote X apps do not.

答: It seems utterly obvious and fundamental now, but the killer innovation of the world wide web was the hyperlink.  Even if X wasn't completely unusable over a modem link, its inability to launch a completely new process on a completely new server via a single click would hamper its adoption for that sort of use case.</p>


答:
The answer is that "many technologies are adopted for arbitrary historical or socio-political reasons rather than technical reasons."  The best solution for a given problem does not always become the dominant technology.  (In fact, it rarely does.)

In 2012, where HTTP servers are being used to create interactive applications on par with Desktop applications, the comparison between HTTP and X is interesting.  In hindsight, X is probably a better technology to develop rich, interactive network-deployed applications.  Interactive Desktop-like applications don't map well to a stateless, document-oriented technology like HTTP, and this mismatch has historically resulted in all sorts of work-arounds (hacks) to create state, like cookies, sessions, etc.

But the original purpose of HTTP wasn't to develop stateful Desktop-like apps.  It was to retrieve documents and display information - information which could link to other documents that could also be instantly displayed.  The idea of a linked collection of documents goes way back to the 1960s with Theodore Nelson's "Project Xanadu". The Web was supposed to be an implementation of Nelson's concept of hypertext, which was an attempt to computerize the printed page - like the encyclopedia or the newspaper - allowing the user to instantly "jump" from one article to another with a single click.

Many iterations of this idea have come and gone, such as Apple's Hypercard, which implemented the concept of hypertext/hyperlinks, but was never deployed over networks.  The World Wide Web was CERN's network-based implementation of the concept of hypertext, and it likely took off because Tim Berners-Lee released his browser code library for free, allowing others to experiment with it.  This eventually led to Marc Andreesen's Mosaic browser, the predecessor of Netscape.  And the rest is history.

But... as with so many technologies, new possibilities began to emerge that the original designers of HTTP or hypertext didn't really think about too much.  The web became commercialized and people started to develop websites that featured stateful interactivity, like shopping carts and logins.  It became more and more apparent that the stateless and document-oriented nature of HTTP wasn't very well suited to Desktop-like applications.  But at that point, it was just too late.  Everyone was already using HTTP.  So, here we are today, with various hacky AJAX applications trying their best to pretend they are Desktop apps.

Title: Why did the web win the space of remote applications and X not?

Body:
The X Window System is 25 years old, it had it's birthday yesterday (on the 15'th).

As you probably are aware of, one of it's most important features is the separation of the server side and the client side in a way that neither Microsoft's, Apples or Wayland's windowing systems have.

Back in the days (sorry for the ambiguous phrasing) many believed X would dominate over other ways to make windows because of this separation of server and client, allowing the application to be ran on a server somewhere else while the user clicks and types on her own computer at home.

This use obviously still exists, but is marginalized at best. When we write and use programs that run on a server we almost always use the web with it's html/css/js.

Why did the web win, and X not? The technologies used for the web (said html/css/js) are a mess. Combined with all the back-end-frameworks (Rails, Django and all) it really is a jungle to navigate thru. Still the web thrives with creativity and progress, while remote X apps do not.


问:
Should all new web projects build their backend based on xml/json result sets?
If you were building a new Saas project, would it make sense to start with all of the backend services returning xml/json?

Because these days you need to build for both the web and mobile devices, and having a backend that is build from the start to return xml and json, you are ready to go mobile (all services have the business logic, so you won't be repeating anything).

Now the web would be MVC, so the controller would just be routing the request to your service backend, and converting the json or xml to html.

The obviousl downside is that you have to build a backend, and then another web project that calls your backend.  But this also goes to you favor as it forces you to seperate your concerns, and not leak business logic in your controller/view layer.

Thoughts?

答:
There is not a YES or NO answer to your question. The decision to introduce a second level of indirection in the form of an xml/json API depends on what you are about to do with your project.

As you mentioned, many projects go mobile these days, however, isn't there a simpler way to provide mobile functionality by simply presenting a customized version of your web interface? I can't answer this but maybe you can.

Other questions you may ask yourself include: Are there any others willing to write clients to my application? If the answer is yes, than an xml/json API may be a good way to go.

EDIT: PS - whatever way you go, separating the business logic from the MVC has the same importance. An API would force you to do that, but also without a second level of encapsulation you should be able to do it just fine.


答:
You are comparing apples to pears.   X windows are about separating the rendering of screen content into a local client, which could be connected by a thin wire to the source of the content.  It's really an extension of the computational model from the "glass tty" era to the domain of high quality graphics.   X originated in the era when PCs were still pretty wimpy, and most of the real computation was done on unix or mainframe boxes.  The idea was to harness the power of relatively cheap "X terminals" and relatively slow networks to make these serious computational reasources available graphically.

The reasons this didn't win on Macs and PCs is that their development was always driven
by the desire to support high end graphics in local applications, including games, editors and business graphics.  Supporting network resident applications is a recent afterthought.


问:
What is the relationship between OpenGL, GLX, DRI, and Mesa3D?
I am starting out doing some low-level 3D programming in Linux. I have a lot of experience using the higher level graphics API OpenInventor.

I know it is not strictly necessary to be aware of how all these things fit together but I'm just curious. I know OpenGL is just a standard for graphics applications. Mesa3D seems to be an open source implementation of this standard.

So where do GLX and DRI fit? Digging around on Wikipedia and all these websites, I've yet to find an explanation of exactly how it all goes together. Where does hardware acceleration happen? What do proprietary drivers have to do with this?

答:
Except OpenGL, I never used those libraries, but I'm going to try to guess, by reading wikipedia pages, like you did.

You seem right about Mesa. Here is the additional info we have :

"The X window system is a computer software system and network protocol that provides a basis GUIs for networked computers. It creates a hardware abstraction layer."

"GLX enables programs wishing to use OpenGL to do so within a window provided by the X Window System.

GLX consists of three parts:

- An API that provides OpenGL functions.

- An extension of the X protocol, which allows the client to send 3D rendering commands
- An extension of the X server that receives the rendering commands from the client and passes them on to the installed OpenGL library

If client and server are running on the same computer and an accelerated 3D graphics card is available, the former two components can be bypassed by DRI. The client program is then allowed to directly access the graphics hardware."

"Direct Rendering Infrastructure (DRI) is an interface used in the X Window System to allow user applications to access the video hardware without requiring data to be passed through the X server."

"Open Inventor is a C++ 3D graphics API designed to provide a higher layer of programming for OpenGL"

To make things simpler, let's imagine a simplified flow of data (and commands) that happens at the entries and exits of each of those APIs. At the very beginning we have your application program (compiled code), that you run from your computer. At the end we have images that are displayed on your screen.

There are several cases which I will restrain to the answers to these questions:

-does your computer have a graphic card (GPU), or only a CPU, to process graphic functions ?

-is your application embedded in a window of the x-window system ?

-if you use the x window system, is the "x server" running on your computer or on an other computer on the network ?

I'll assume you have the drivers for your GPU if you have one, and that you have Mesa for the software rendering).

First scenario : you run a graphic application written with OpenInventor, without using to the X Window System, and you don't have a graphic card. The program flow would be quite similar to :

```<code>Your application
  ↓ (uses functions of)
OpenInventor
  ↓ (calls functions declared by)
OpenGL
  ↓ (redirects function calls to implementation defined by)
Mesa
  ↓ (implemented OpenGL functions to be run on the CPU)
[Probably] Operating System rendering API
  ↓
3D Images on your screen
</code>```

What happens here is called "software rendering" : the graphics command are not handled by any graphic hardware, but instead by your usual CPU, the processor that generally runs software.

Second scenario : now imagine that with the same conditions as above, you have a graphic card. The flow would look more like this :

```<code>Your application
  ↓ (uses functions of)
OpenInventor
  ↓ (calls functions declared by)
OpenGL
  ↓ (redirects function calls to implementation defined by)
Proprietary Drivers
  ↓ (converts OpenGL commands to GPU commands)
Graphic Card
  ↓
3D Images on your screen
</code>```

What happens now is called "hardware acceleration", usually faster than the first scenario.

Third scenario : now let's introduce the X Window System flow, or at least how I think it is, based on the few Wikipedia lines I read.

Let's forget about the graphic hardware and API for a while. The flow should look like :

```<code>Your application (X Window System sees it as an "X Client")
  ↓ (sends requests defined by the X Window System Core Protocol)
X Server
  ↓ (convert your request to graphic commands)
[Probably] Operating System rendering API
  ↓
Windows or 2D images on your screen
</code>```

Note that when using the X Window System, your screen and the computer from which you run your application may not be "directly" connected, but could be connected through a network.

Fourth scenario : suppose you want to add fancy 3D graphic renderings to your X Client application from the previous example. It seems to me that the X Window System is not originally able to do this, or at least it would necessitate much convoluted code to perform the equivalent of an OpenGL API function.

Luckily you can use GLX to add support for OpenGL commands to the system. You now have :

```<code>Your application
  ↓ (sends graphic requests defined by the "GLX extension to the X Protocol")
X Server with the GLX extension
  ↓ (convert your request to OpenGL commands)
OpenGL
  ↓ (redirects function calls to implementation defined by)
 ...
</code>```

Now you can reconnect that last arrow to the one after "OpenGL" in the first scenario : you can get 3D images on your screen !

Finally about what I think understand of the DRI :

It seems to allow Mesa to have access to the GPU, so that would modify the flow of our first scenario into :

```<code>...
  ↓
Mesa
  ↓ (forwards OpenGL commands)
DRI
  ↓ (converts OpenGL commands to GPU commands)
Graphic Card
  ↓
3D Images on your screen
</code>```

And it also seems to short-circuit the flow when using GLX, given the condition that its server and client are on the same computer, and that you have a GPU. In that case the graph of our fourth scenario would simply become :

```<code>Your application
  ↓ (sends graphic requests defined by the "GLX extension to the X Protocol")
DRI
  ↓ ("catches" OpenGL commands and converts them to GPU commands)
Graphic Card
  ↓
3D Images on your screen
</code>```

That's it !

Now keep in mind that I'm not an expert in Unix environments, so my best advice is to study the documentation of each of those APIs to know precisely what they can do.

Combining the previous chart into a single one might make things easier to understand. I let this as an exercice to you!

Body:
Except OpenGL, I never used those libraries, but I'm going to try to guess, by reading wikipedia pages, like you did.

You seem right about Mesa. Here is the additional info we have :

"The X window system is a computer software system and network protocol that provides a basis GUIs for networked computers. It creates a hardware abstraction layer."

"GLX enables programs wishing to use OpenGL to do so within a window provided by the X Window System.

GLX consists of three parts:

- An API that provides OpenGL functions.

- An extension of the X protocol, which allows the client to send 3D rendering commands
- An extension of the X server that receives the rendering commands from the client and passes them on to the installed OpenGL library

If client and server are running on the same computer and an accelerated 3D graphics card is available, the former two components can be bypassed by DRI. The client program is then allowed to directly access the graphics hardware."

"Direct Rendering Infrastructure (DRI) is an interface used in the X Window System to allow user applications to access the video hardware without requiring data to be passed through the X server."

"Open Inventor is a C++ 3D graphics API designed to provide a higher layer of programming for OpenGL"

To make things simpler, let's imagine a simplified flow of data (and commands) that happens at the entries and exits of each of those APIs. At the very beginning we have your application program (compiled code), that you run from your computer. At the end we have images that are displayed on your screen.

There are several cases which I will restrain to the answers to these questions:

-does your computer have a graphic card (GPU), or only a CPU, to process graphic functions ?

-is your application embedded in a window of the x-window system ?

-if you use the x window system, is the "x server" running on your computer or on an other computer on the network ?

I'll assume you have the drivers for your GPU if you have one, and that you have Mesa for the software rendering).

First scenario : you run a graphic application written with OpenInventor, without using to the X Window System, and you don't have a graphic card. The program flow would be quite similar to :

Your application
  ↓ (uses functions of)
OpenInventor
  ↓ (calls functions declared by)
OpenGL
  ↓ (redirects function calls to implementation defined by)
Mesa
  ↓ (implemented OpenGL functions to be run on the CPU)
[Probably] Operating System rendering API
  ↓
3D Images on your screen

What happens here is called "software rendering" : the graphics command are not handled by any graphic hardware, but instead by your usual CPU, the processor that generally runs software.

Second scenario : now imagine that with the same conditions as above, you have a graphic card. The flow would look more like this :

Your application
  ↓ (uses functions of)
OpenInventor
  ↓ (calls functions declared by)
OpenGL
  ↓ (redirects function calls to implementation defined by)
Proprietary Drivers
  ↓ (converts OpenGL commands to GPU commands)
Graphic Card
  ↓
3D Images on your screen

What happens now is called "hardware acceleration", usually faster than the first scenario.

Third scenario : now let's introduce the X Window System flow, or at least how I think it is, based on the few Wikipedia lines I read.

Let's forget about the graphic hardware and API for a while. The flow should look like :

Your application (X Window System sees it as an "X Client")
  ↓ (sends requests defined by the X Window System Core Protocol)
X Server
  ↓ (convert your request to graphic commands)
[Probably] Operating System rendering API
  ↓
Windows or 2D images on your screen

Note that when using the X Window System, your screen and the computer from which you run your application may not be "directly" connected, but could be connected through a network.

Fourth scenario : suppose you want to add fancy 3D graphic renderings to your X Client application from the previous example. It seems to me that the X Window System is not originally able to do this, or at least it would necessitate much convoluted code to perform the equivalent of an OpenGL API function.

Luckily you can use GLX to add support for OpenGL commands to the system. You now have :

Your application
  ↓ (sends graphic requests defined by the "GLX extension to the X Protocol")
X Server with the GLX extension
  ↓ (convert your request to OpenGL commands)
OpenGL
  ↓ (redirects function calls to implementation defined by)
 ...

Now you can reconnect that last arrow to the one after "OpenGL" in the first scenario : you can get 3D images on your screen !

Finally about what I think understand of the DRI :

It seems to allow Mesa to have access to the GPU, so that would modify the flow of our first scenario into :

...
  ↓
Mesa
  ↓ (forwards OpenGL commands)
DRI
  ↓ (converts OpenGL commands to GPU commands)
Graphic Card
  ↓
3D Images on your screen

And it also seems to short-circuit the flow when using GLX, given the condition that its server and client are on the same computer, and that you have a GPU. In that case the graph of our fourth scenario would simply become :

Your application
  ↓ (sends graphic requests defined by the "GLX extension to the X Protocol")
DRI
  ↓ ("catches" OpenGL commands and converts them to GPU commands)
Graphic Card
  ↓
3D Images on your screen

That's it !

Now keep in mind that I'm not an expert in Unix environments, so my best advice is to study the documentation of each of those APIs to know precisely what they can do.

Combining the previous chart into a single one might make things easier to understand. I let this as an exercice to you!


答:
No.

XML/JSON are just data formats.

It makes sense to have a clear separation between business logic and presentation (unless it's a small project). If you have procedures/functions/methods whatever that expose the operations in you application, which are not "contaminated" with presentational matters (i.e. they take primitives, business-logic objects instead of HTTP requests, GUI events, etc.), it's fairly easy to expose them in different manners- XML, JSON, whatever, and of course you can invoke them directly from the applicable presentation layers.

You don't need to force a "hard" separation- it really doesn't require that much discipline, and even if you required separate projects for other reasons (e.g. different teams, etc.), I would favor using the backend as a "library" instead of as a service if possible- direct method invocation has less overhead in all senses and is highly desirable.

Title: Should all new web projects build their backend based on xml/json result sets?

Body:
If you were building a new Saas project, would it make sense to start with all of the backend services returning xml/json?

Because these days you need to build for both the web and mobile devices, and having a backend that is build from the start to return xml and json, you are ready to go mobile (all services have the business logic, so you won't be repeating anything).

Now the web would be MVC, so the controller would just be routing the request to your service backend, and converting the json or xml to html.

The obviousl downside is that you have to build a backend, and then another web project that calls your backend.  But this also goes to you favor as it forces you to seperate your concerns, and not leak business logic in your controller/view layer.

Thoughts?


问:
Can I get a C++ Compiler to instantiate objects at compile time
I am writing some code that has a very large number of reasonably simple objects and I would like them the be created at compile time.  I would think that a compiler would be able to do this, but I have not been able to figure out how.

In C I could do the the following:

```<code>#include <stdio.h>

typedef struct data_s {
    int a;
    int b;
    char *c;
} info;

info list[] = {
    1, 2, "a",
    3, 4, "b",
};

main()
{
   int i;
   for (i = 0; i < sizeof(list)/sizeof(*list); i++) {
     printf("%d %s\n", i, list[i].c);
   }
}
</code>```

Using #C++* each object has it constructor called rather than just being layed out in memory.

```<code>#include <iostream>
using std::cout;
using std::endl;

class Info {
    const int a;
    const int b;
    const char *c;
public:
    Info(const int, const int, const char *);
    const int get_a() { return a; };
    const int get_b() { return b; };
    const char *get_c() const { return c; };
};

Info::Info(const int a, const int b, const char *c) : a(a), b(b), c(c) {};

Info list[] = {
    Info(1, 2, "a"),
    Info(3, 4, "b"),
};

main()
{
    for (int i = 0; i < sizeof(list)/sizeof(*list); i++) {
        cout << i << " " << list[i].get_c() << endl;
    }
}
</code>```

I just don't see what information is not available for the compiler to completely  instantiate these objects at compile time, so I assume I am missing something.

答:
You can't really create them at compile time, but you can trick the compiler into specifying the creation of pretty complex data structures by using macros to store information, and then using multiple different definitions of the macro to deposit information as needed.

For example, you can have a macro structure like

in a header file "header.h":

```<code>foo(x,1)
foo(y,2)
</code>```

then in one place

```<code>#define foo(a,b) a = b;
#include "header.h"
#undef foo
</code>```

and in another place

```<code>#define foo(a,b) #a,

char *name = {
#include "header.h"
};
#undef foo
</code>```

and so on

Body:
You can't really create them at compile time, but you can trick the compiler into specifying the creation of pretty complex data structures by using macros to store information, and then using multiple different definitions of the macro to deposit information as needed.

For example, you can have a macro structure like

in a header file "header.h":

foo(x,1)
foo(y,2)

then in one place

#define foo(a,b) a = b;
#include "header.h"
#undef foo

and in another place

#define foo(a,b) #a,

char *name = {
#include "header.h"
};
#undef foo

and so on


答:
It depends on your application.  A lot of businesses simply don't need a web API services layer and can use standard MVC practices to serve up rendered pages from well designed thin controllers.   This can be much faster to create and easier to maintain than something like a view layer written entirely in unmaintainable javascript(most is) that hits your API.

Most frameworks assume the view will be rendered in the same application so you'll be fighting that assumption and losing out on a lot of 'free' functionality.  Business logic can leak either way so it's a question whether the extra layer of abstraction gives you anything.


问:
Are Java certifications important for an architect role?
I want to know how much Java Certifications (SCJP, SCWCD and others) are important for an architect position. If a person posses a good experience in Java development and want to pursue his career on architect level, do you guys think he need to have certification on his CV. If he has never worked on lead developer roles?

If you conducting my interview for an architect position. And I have worked as a Java web developer in different teams having 5 years of exp. Never lead any. And I am having certification badges on my CV.

How can a developer make his career path towards being an architect in a team?

答:
Bottom line - you must understand coding w/in the context of NFR's and how they solve a business problem/create a strategic advantage. Notice I did not say anything about being able to program well ( although it is usually expected. This includes most of the other comments but expands on these further.  Does choosing Spring give you a lighter weight, faster performing application, while sacrificing modifiability ? If so, what is the business impact of this attribute decision?
Does that present a configuration management and maintainability challenge to your newly formed DevOps team? Does private SaaS delivery model make sense?
As one poster said, it is very much about decision making, defending those decisions and edifying others on the best ways to proceed insupportable of those decisions all while analyzing feedback and making adjustments to technical decisions based upon the firm's business model, strategy, and departmental/business unit's context of that model and strategy.

So if you think you need certs, you probably correct. But what you would need beyond the SCJP level that is language specific, is less clear. You would do well to explore ITIL, PMI-ACP, CSSLP, TOGAF9, ArchiMate 2, SEI Software Architecture Professional Certificate & ATAM Evaluator Certificate, and moat importantly - IASA Foundation Associate. These will go much further to prepare you for becoming an Architect than SCWCD.  That said, obtaining a SCEA (now OCM Java Architect) could still be a fruitful exercise to prepare you specifically w/in the Java world and also handling board reviews, but other than that, I would focus on those that I mentioned.


问:
Why are most websites optimized for viewing in portrait mode?
I simply cannot figure this out. Almost all monitors have an aspect ratio where width is much bigger than the height and yet almost all websites are designed exactly for the other way round? I am not really a web developer and am just experimenting stuff at the moment but this madness baffles me!!!

Edit: The point is not that I would like to limit the height of a website. The point is that I'd want it to somehow fill all available space when I have my 1920x1080 in landscape mode.

Edit 2: See this to understand what I am saying

答:
I suppose that in general it is discouraged to post an answer in thread that has not seen activity for a long time. I feel, however, that there are some relevant things that have not been mentioned yet.

First, let me mention the following Firefox extension that I discovered several months ago:   Column Reader

https://addons.mozilla.org/en-US/firefox/addon/column-reader/

Why do we scroll vertically?

For comparison: consider a language that is written in vertical columns. For a language like that the current wide-screen monitors are ideal. So that is how it works out: you scroll perpendicular to the direction of your lines. Book pages are in portrait format because our lines are horizontal.

As has been pointed out in earlier answers: the reflow capabilities of our browser's layout engines are tuned to reflowing vertically.

multi-column capability

The development team of a browser may opt to add multi-column capability in the following way:
First render the entire page as a single column, then cut that into strips with the pixel height of the available window space, and display those strips side-by-side. But how wide do you make the columns? Even when very little width is used for actual text, often the page codes for a particular background color for the entire width of the available window space.

Then the rendering engine must play safe, and allocate the entire horizontal space to a single column.

Is it possible for webdesigners to implement a reflowing multi-column layout?

That would run into severe difficulities. You have to obtain the height and width of the available windows space, and do the cutting and arranging of strips into columns in Javascript. Then you must decide what to do with images that are cut in two pieces.

Dealing with that sort of thing is what a layout engine does. To try and create a Javascript library that facilitates reflowing multi-column layout is to create a rendering engine in Javascript. That's creating a platform-in-a-platform.

Monitor size

I find it frustrating that in effect computer monitors have shrunk the last couple of years. Large monitors had 1200 pixels of height, nowadays only 1050. Yes, they're wider, but for text that space cannot be utilized.

Also, in portrait orientation those monitors are too narrow.

I have a dual monitor setup, with both monitors in portrait orientation, both monitors are 1200x1600px.
For me those 1200 pixels are a minimum.

A conditional statement in CSS

A remark about fixed width layouts.

I love the CSS command that allows the web-designer to accommodate a large range of widths while avoiding scrollbars and maintaining readability: "max-width".
(There are four commands like that: min-width, max-width, min-height, max-height).
For a div containing text specify a max-width of, say, 65em.

You get an if/else.

If the available space is less than 65em then the text is reflowed accordingly: no horizontal scrollbar
If the available space is more than 65em then the containing div is set at 65em.


问:
Use switch statements for application flow?
I generally use switch statements to simplify a block of multiple if statements - for example - returning a feedback string to a user based on a multiple choice input.

I also tend to construct classes so that there is one "management" method, to avoid sequential steps or chained method invocation within other methods of the class. I've found this helps to keep methods flexible and focussed - i.e.

```<code>class MyClass{

    // this method does nothing more than invoke the relevant method
    // depending on the status following the previous. It's entire purpose
    // is to control application flow
    public function manageFlow($input){
        $status = $this->stepOne($input);
        if($status == false){
            //exit routine
        }

        $status = $this->stepTwo($input);
        if($status == false){
            //exit routine
       }
    }

    // this method has several sequential steps implemented direcly within it,
    // for example to a user logging in
    // it makes it impossible to re-use any of the intermediary steps
    public function tangledFlow($input){
         if($input == 'something){
         //100 lines of code
         }
         //then handing on to the next bit
         if($this->User->Authenticated){
         //another 100 lines...
         }
    }
}
</code>```

Then it occurred to me that I could use a switch statement to control this kind of sequential execution - so my question is: has anyone used a switch statement for this kind of flow control?

答:
In this case, it looks like you're using PHP, so using a switch statement won't have a huge impact on the performance of the code to use a switch vs. if statements in this situation, and there aren't major syntax issues you'd need to worry about.

So, that said, I would say do what you think is going to be more maintainable. If your team favors switch statements over trains of ifs, then use that. If the opposite is true, use that.

You should absolutely be using manageFlow over tangledFlow for your method design, however. tangledFlow tries to do too many things, and as such reduces maintainability (and readability!).

ContentLicense: CC BY-SA 2.5


问:
What's so special about x64 vs x86?

What is the difference between building a .NET project to target 32-bit or 64-bit?

Are there computers that aren't able to run 32-bit programs and only 64-bit?

Do x64 programs run twice as fast?

答: The .Net Programs that will be written for 64bit systems will have larger address space, and so will be much faster than x86-32 bit based programs. Also latest .NET Language compilers produce much optimized code. JIT is also improved in recent years and now you can do Multi-core JIT optimization. Debuggers are also improved. Meanwhile, better and optimized code is produced for 64bit - based systems.</p>

ContentLicense: CC BY-SA 4.0

Title: What's so special about x64 vs x86?


问:
Data architecture for event log metrics?
My service has a large ongoing number of user events, and we would like to do things like "count occurrence of event type T since date D."

We are trying to make two basic decisions:

What to store?  Storing every event vs. only storing aggregates

(Event log style) log every event and count them later, vs.

(Time-series style) store a single aggregated "count of event E for date D" for every day

Where to store the data

In a relational database (particularly MySQL)

In a non-relational (NoSQL) database

In flat log files (collected centrally over the network via syslog-ng)

What is standard practice / where can I read more about comparing the different types of systems?

Additional details:

The total event stream is large, potentially hundreds of thousands of entries per day

But our current need is only to count certain types of events within it

We don't necessarily need real-time access to the raw data or aggregation results

IMHO, "log all events to files, crawl them at a later time to filter and aggregate the stream" is a pretty standard UNIX Way, but my Rails-y compatriots seem to think that nothing is real unless it's in MySQL.

答:
I think that your idea to parse logs, count and store results in a DB is valid. Not sure you'd want all those raw logs in the DB anyway (I think that's what you said your compatriots are suggesting). You've already got the logs in files, correct? You could just archive those. I suppose that bit really depends on your use case(s).

Also agree with @Thorbjørn Ravn Andersen about moving your "comment answer" to the question.


问:
What is a "wrapper" program?
Where I work, employees use a third-party desktop program for their clients. This program saves data to a flat file. My colleague wants to write a Java program that uploads that flat file to a remote server, opens the desktop program when the flat file is downloaded from a Web site, and checks if the desktop program is running or not by looking at the Windows processes.

He keeps calling this helper/utility program a "wrapper." But it doesn't wrap anything! I tried to clear it up with him, but he said, "Well, I call it a wrapper." He now has everyone in the company calling it a "wrapper." What would you call it? I say that it's a helper program or utility program.

答:
I've always viewed wrappers as generally small programs that do pre and post processing for some other program or procedure. So typically the wrapper will be the one making the call to the program it is wrapping.

Examples for why you might do this:

It allows you to programmatically set up the environment conditions for the program being called so that they will always be in a form that makes the wrapped program happy.

It effectively allows you to mask the calling of the wrapped program, should you desire to, from the user's eyes.

Title: What is a "wrapper" program?


问:
Extracting main article from webpage/feed. Is it legal/ethical?
There are some applications like Readability and Pocket, which are letting users to read the main content of web pages, in a clean interface or such. But the articles should be bookmarked from another application, or the web browser.

However, I'm creating a news reader app (Zite and Flipboard are popular news reader apps), and I want to create a clean experience for users, so I want to show full content of articles inside my application. Some websites have fulltext feeds, and I'm using it.

But about some other websites, which don't have full text feeds: I want to know, is it legal/ethical to use for example Readability API (Or maybe writing my own code for this) to show full text of articles inside my application?

答:
Whether or not it is legal is going to depend upon a whole host of copyright law and various jurisdictions.  In some places, yes, it will be legal.  In others, no.  If you're really worried on this point, please consult an attorney that specializes in the areas where you will be pulling content from and publishing to.

Whether or not it is ethical is still difficult to answer, but can be examined.  If you are providing full attribution to the source of the articles AND you are honoring sites that request you to not copy their content, then yes it could be ethical.  If you are portraying the work(s) as your own, that would not be ethical.

It sounds like you're providing some sort of aggregation functionality.  Most aggregators don't claim the material as their own and the users generally know where the content came from.  I would look to existing applications to determine how you differ and whether or not your app's difference remain within the bounds of ethical and legal behaviour.


答: Yes, I think it makes really good sense and is an excellent architecture. It's so simple to return JSON/XML to the client transparently from the server - it does not require writing an additional layer. Javascript clients easily consume JSON. You have a clean separation of concerns. You can generate code from the shared model for compile-time validation if you choose. And of course you have the flexibility mentioned in the question of supporting additional clients e.g. mobile. Don't forget the backend technology can change too. We swapped out a .NET backend for a java/spring/tomcat backend at my last job.</p>


答:
Most probably yes, if your clients are going to consume Restful HTTP services.

There is a growing trend in web/mobile applications to extensively use HTTP services with json/xml formatted data exchange. Thus, if you are developing on .NET platform there is ASP.NET Web API technology that will ease your development, and provide a most fundamental features out of the box.

Even if you are developing for different platform, still http services and mentioned data formatted data exchange type is starting to play important role, and it is getting more and more important to move toward that direction.


问:
How can I get my progress reviewed as a solo junior developer
I am currently working for a 2 person company, as the solo primary developer. My boss gets the clients, mocks up some png design templates and hands them over to me.

This system has been working fine and i'm really enjoying it.

The types of projects I work on are for small - medium sized businesses and they usually want a CMS system. Developed from scratch i'll build a customised backend for the client to add/edit/remove categories, tags, products etc and then output them to the front end according to the design template handed to me. As time has gone on, the projects have increased in complexity, with shopping cart / ordering features and other common e-commerce type features.

Again, this system has been working fine and i'm really enjoying it.

My issue is my personal development as a programmer. I spend a lot of my spare time reading programming blogs, checking through stackexchange, reading suggested programming books (currently on 'The Pragmatic Programmer', really good so far), doing brain exercises (lumosity.com and khanacademy math problems), doing lots of physical exercise and other personal development type activities.

I can't help but feel though, that I'm missing out on feedback, critique. My boss is great and never holds back on praise in regards to my work, but he unfortunately is either to busy to check my code, or to be honest, I don't think it's one of his specialties and so can't provide feedback.

I want to know what i'm doing wrong and what i'm doing right. Should I be putting that much logic in the controller, am I modulating my code enough etc.

So what I have done is developed a little 'Family Budgeting' app and tried to do it as cleanly and effectively as I currently know how.

What i'm wanting to know is, is there somewhere I can submit this app, and have some seasoned developers provide feedback. It's not just a subsection of my code like 'codereview.stackexchange' appears to require, it's my entire workflow that I want critiqued.

I know this is a lot to ask, and I expect the main advice given will be to look for a job within a team, which is certainly something I will look into later down the track, but for now I want to persist with my current employment situation, but just don't want to develop too many bad habits.

Let me know if I can provide any further information to help clarify, or if this isn't the right place for this type of question I apologise in advance. Didn't want to use reddit as I felt this community fosters more well thought out responses.

答:
As you gain more experience you can certainly go back and review your previous projects/code to see where you went wrong. Hindsight is a beautiful thing. I know for a fact I've looked at code/documentation I wrote x ago and realised where I went wrong and where I could have improved.

The fact you read blogs, books, SE, etc. should be giving you greater insight into programming as part of your own personal development and the trial and error and the evolution of your projects and code should certainly be evidence of the fact that you're improving. Self critique can be a very good thing.

Having said that, having the critical eye of another developer always adds value and can provide opinions/options that you may not have thought of. Although I don't know of any particular site that you can dump a full project for a code review - you could put snippets of what you consider suspect onto codereview.stackexchange for their perusal and comment, then take that feedback on board and apply it elsewhere where appropriate.

Alternatively, you could write some opensource stuff and throw it up on github (or equivalent). The open source community will certainly critique your work and improve it where they see fit.

At the end of the day, if the products you are producing work as intended, meet the business requirements and are maintainable - you're doing something right.

For conceptual programming questions, patterns, etc. You can always post those questions here on PSE and for code implementation issues on SO.


答:
You are on the right track to improve your skills, and it's understandable that you are uncertain about the reliability and enterprise-readiness of your code.

This is a normal process to go through for a junior developer, and your interest to improve is very important, as it is a key to one day becoming a rock-star developer.

As a reference to learn best practices, I would recommend joining open-source projects which are hosted free for passionate/curious programmers. They would really help you understand how to use best practices and how to decide on application design. In addition, try to get involved in open-source project development, as it will boost your self-learning and improvement dramatically.

I would also recommend attending local community events for software developers . You may find some of these groups at communitymegaphone.com. Talk with local buddy programmers, they are mostly good people who would not mind helping a colleague.

Title: How can I get my progress reviewed as a solo junior developer

Body:
I am currently working for a 2 person company, as the solo primary developer. My boss gets the clients, mocks up some png design templates and hands them over to me.

This system has been working fine and i'm really enjoying it.

The types of projects I work on are for small - medium sized businesses and they usually want a CMS system. Developed from scratch i'll build a customised backend for the client to add/edit/remove categories, tags, products etc and then output them to the front end according to the design template handed to me. As time has gone on, the projects have increased in complexity, with shopping cart / ordering features and other common e-commerce type features.

Again, this system has been working fine and i'm really enjoying it.

My issue is my personal development as a programmer. I spend a lot of my spare time reading programming blogs, checking through stackexchange, reading suggested programming books (currently on 'The Pragmatic Programmer', really good so far), doing brain exercises (lumosity.com and khanacademy math problems), doing lots of physical exercise and other personal development type activities.

I can't help but feel though, that I'm missing out on feedback, critique. My boss is great and never holds back on praise in regards to my work, but he unfortunately is either to busy to check my code, or to be honest, I don't think it's one of his specialties and so can't provide feedback.

I want to know what i'm doing wrong and what i'm doing right. Should I be putting that much logic in the controller, am I modulating my code enough etc.

So what I have done is developed a little 'Family Budgeting' app and tried to do it as cleanly and effectively as I currently know how.

What i'm wanting to know is, is there somewhere I can submit this app, and have some seasoned developers provide feedback. It's not just a subsection of my code like 'codereview.stackexchange' appears to require, it's my entire workflow that I want critiqued.

I know this is a lot to ask, and I expect the main advice given will be to look for a job within a team, which is certainly something I will look into later down the track, but for now I want to persist with my current employment situation, but just don't want to develop too many bad habits.

Let me know if I can provide any further information to help clarify, or if this isn't the right place for this type of question I apologise in advance. Didn't want to use reddit as I felt this community fosters more well thought out responses.


问:
How can one manage thousands of IF...THEN...ELSE rules?
I am considering building an application, which, at its core, would consist of thousands of if...then...else statements. The purpose of the application is to be able to predict how cows move around in any landscape. They are affected by things like the sun, wind, food source, sudden events etc.

How can such an application be managed? I imagine that after a few hundred IF-statements, it would be as good as unpredictable how the program would react and debugging what lead to a certain reaction would mean that one would have to traverse the whole IF-statement tree every time.

I have read a bit about rules engines, but I do not see how they would get around this complexity.

答:
Since your looking at movement of the cow, they are stuck in 360 degree direction( cows can't fly.)  You also have a rate that your traveling. This can be defined as a vector.

Now how do you deal with things like the sun position, slope of the hill, loud noise?

Each of the degrees would be a variable signifying the desire to go in that direction. Say a twig snaps to the right of the cow at 90 degrees (assuming the cow faces 0 degrees). The desire to go to the right will go down and the desire to go 270 (left) will go up. Go through all the stimuli adding or subtracting their influence on the cows desire to go in a direction. Once all the stimuli is applied, the cow will go in the direction of highest desire.

You can also apply gradients so the stimuli doesn't have to be binary. For example a hill is not straight up in one direction. Maybe the cow is in a valley or on a road on a hill were its flat straight ahead, at 45* slight up hill at 90* slight down hill. At 180* steep up hill.

You can then adjust the weight of an event, and it's direction of influence. Rather then a list of if thens, you have one test looking for the max. Also when you want to add a stimuli you can just apply it before the test and you don't have to deal with adding more and more complexity.

Rather then saying the cow will go in any 360 direction lets just break it down into 36 directions. Each being 10 degrees

Rather then saying the cow will go in any 360 direction lets just break it down into 36 directions. Each being 10 degrees. Depending on how specific you need to be.


问:
Legally, can I re reuse code for different customers?
The company I work for develops custom factory automation applications for multiple customers. Even though each application is custom, they contain common code which is re-used across projects.

One of the customers is now looking for the source code to their application, which  has caused a major storm in the company. Management have decided that we can't give them the source to the shared components as they are used by other customers. I've been asked to modify the shared components 'enough' so as they aren't common.

So my questions are:

1) Legally, should there be any problem with re-using common components for different customer?

2) If I really need to modify the common components, then how much is 'enough' ? (I know this sucks, but I either do this or hand in my notice).

Oh yeah, and my company has no license in place with any of these customers.

答:
1) There is no problem with using the same components for multiple customers. Assuming there is no contract agreement against it. Microsoft has shipped common windows code to millions of customers in every legal system in the world.

2) Modify loops to count down instead of up. Rename things. Swap some lines of code where the sequence of execution is irrelevant. Instead of a function returning a value, add a new parameter that works via side effects to simulate a return value. Make a XOR swap instead of a normal swap. Throw in some shift operations. Replace some generics to use duplicate implementations for each type.

If you're feeling frisky make some "real" changes to the design or and core algorithms used.

It's just a game so don't take it too seriously.


问:
skills that can't be outsourced- web development related
I never know where it's acceptable to post something like this, so please forgive if it's in the wrong place. I'm very interested in going further in to web development; I know a bit of javascript, a bit of php, and so forth, but I'm now seeing these services that will go from psd to wordpress for 200 bucks and I'm wondering how the hell is anyone able to compete with this? So I'm wondering if those more knowledgeable than me could tell me what areas are the least likely to be able to be outsourced, for 5 bucks to some kid in Uzbekistan( no offense to that kid).. do you think it's on the database management side, or maybe app development? ideas appreciated. </p>

答:
The difference is are you delegating or abdicating the work. I think the success or failure of any project being outsourced depends on the person/company doing the hiring. There may be some tasks that are slightly easier to outsource, but what really matters is the importance. I also think it is easier to outsource tasks you know how to do really well and can monitor and identify if someone else is doing quality and timely work.

Everyone always underestimates how much time they will have to spend with the outsourced workers. Many companies may do better with onsight employees because they don't realize how much time is spent telling them what you want. It's more convenient to ask a quick question without scheduling a meeting. Of course they also don't realize how much time they waste.

I remember a co-partner and lead programmer gave a project to two junior programmers to convert a dos application to Windows. He let them code for months without putting any effort to supervise or review the code. He was disappointed with "them" for the terrible end result. That was his excuse to the other partner eventhough he hired both of them and he was responsible for the project.

Most people can't outsource tasks because they don't know what they're doing and just rely on the kindness of strangers.


答:
Is the rewrite intended to keep your source code secret?  If the rewrite works, won't it be just as good as having the original?  If you effectively obfuscate the code, it won't be useful to your client.  I could talk about the work involved and the ongoing maintenance to keep a rewrite in synch with the original so you can continue to send new releases to this client, but I won't because it makes no sense.  Don't rewrite anything.

I am not a lawyer, but I think you are right that this is a legal issue - you need to hire a lawyer.  At the very least, I would first make your customer sign a non-disclosure agreement, then deliver the existing source code to them.  Done.  You can probably find a boiler-plate draconian NDA on the web.  This is the industry standard practice.  If their lawyer wants changes to your NDA, you will have to hire a lawyer for just this one issue.

If there are non-friendly jurisdictions involved (e.g. your client is in Libya or Yemen), then you have to just say no to the request for the source code.  You may have to say no anyway if giving away the source code puts your other clients at risk in any way.  You have a real legal gap here, with no license whatsoever.

Why can't you fix the issue for the client without giving them the source?

Title: Legally, can I re reuse code for different customers?

Body:
The company I work for develops custom factory automation applications for multiple customers. Even though each application is custom, they contain common code which is re-used across projects.

One of the customers is now looking for the source code to their application, which  has caused a major storm in the company. Management have decided that we can't give them the source to the shared components as they are used by other customers. I've been asked to modify the shared components 'enough' so as they aren't common.

So my questions are:

1) Legally, should there be any problem with re-using common components for different customer?

2) If I really need to modify the common components, then how much is 'enough' ? (I know this sucks, but I either do this or hand in my notice).

Oh yeah, and my company has no license in place with any of these customers.


答: Every time I have had to re-purpose a screen in a web application, the new purpose has needed slightly different queries and different business logic.  The idea of reuse is great, but I haven't seen it play out that way in the 12 years I've been a professional Web Application Developer.  Your mileage may vary.</p>


答:
No, don't expose all business services 'blindly', with the one possible exception is if your app has a 100% smart-client front-end (i.e. only consider this if NONE of your dynamic Html is rendered from the server).

Rationale is:

This will slow down the performance of Controller rendered screens unnecessarily due to the additional TCP/IP stack 'hop'

It creates a larger surface area for attackers - you may forget to lock down services which you aren't actually using.

Exposing of services must be done in a formalised manner (e.g. off your controllers for JSON / browser clients, or a formal set of integration services, e.g. web services). If you don't do this, in an enterprise, you may find yourself with a bunch of consumers of your services who you don't even know about.

In many instances (in .NET anyway), exposing JSON services to a browser is best done from the MVC controller, since Ajax services are often tightly coupled to views. This  isn't the right place for exposing integration services (e.g. SOAP / WSE) to other systems.

In short, you are right about moving logic out of your views and controller into a 'back end layer', but the coupling between controller and back end isn't necessarily across a web service boundary.


答:
With the rise of the Javascript client-side UI rendering frameworks like backbone.js and other various tricks like pjax, this option is becoming more and more popular.

It's always a good idea to separate business logic from presentation concerns.

Depending on your budget/time, you may want to skip the public API (fiddling with OAUTH stuff is a big time sink by itself), and build your controllers and views to consume the json result set returned by your application specific code. I'm going with this approach for some time, and it pays back sooner than I expected.

You might want to read The Clean Architecture, a great blog post from Robert Martin(UncleBob). Some good advice in there.


问:
What do you look at first: the code or the design?
If you've just been introduced to a new project, what's the first thing you look for to get an idea of how it works?

Do you look for the design first?  If there is a design, what do you look for in it? Class diagrams or deployment diagrams or sequence diagrams or something else?

Or do you go straight for the code? If so, how do you understand how the different layers interact?

答:
The code doesn't lie.  Certainly good idea to get an overview of the project first to understand what it does.  However, if your task is to get a detailed understanding of how the project works, looking at code, at least for me, is like looking at a jigsaw puzzle piece by piece except that with each class you look at, you're adding another piece of the jigsaw puzzle.  If the code is well-structured, you can see a pattern forming from the names of the classes without even investigating what the class does.  In many cases, you can get hints and clues from the code which will assist you further.

Finally, you get what is irrequivocable idea of what the program does, a completed jigsaw puzzle.  Documentation may be incomplete or inaccurate, but the code never lies.  All of this you can do without figuring out what each individual method does.  Not everyone can learn about a project this way, but if you do it often, it comes easier to you, not to mention that you can get the gist of a medium-sized application in a couple hours of studying.  Though I suppose it all comes down to preference.


问:
Making two images move at different speeds in Java?
I am creating a basic game of space invaders. I am using a thread to animate the game and was wondering, how do I get the aliens the speed up going left and right without changing the speed of the ship you control below them?

What is the easiest method? I am quite new to Java 2d and have only created two other more basic games.

答:
First of all instead of using a thread i advise to look at active rendering.
Active Rendering article
Oracle (Sun) resource on the topic

Active rendering (Figure 2) is just the opposite. Instead of letting
  someone else decide when to paint, the program constantly repaints the
  screen in a very tight while loop. While this sort of behavior is not
  recommended for regular applications, it is exactly the kind of
  control needed to make computer games.

The main difference compared to regular rendering is that you don't wait for the paintXYZ() to be called but you intentionally redraw the screen as fast as you can (FPS) to have a smooth game experience.

Then you set up different horizontal and vertical speeed for your characters. And whenever a new 'frame' kicks in your game objects will be moved with the designed pixel distance.


问:
How can we unify business goals and technical goals?

Some background

I work at a small startup: 4 devs, 1 designer, and 2 non-technical co-founders, one who provides funding, and the other who handles day-to-day management and sales. Our company produces mobile apps for target industries, and we've gotten a lot of lucky breaks lately. The outlook is good, and we're confident we can make this thing work.

One reason is our product development team. Everyone on the team is passionate, driven, and has a great sense of what makes an awesome product. As a result, we've built some beautiful applications that we're all proud of.

The other reason is the co-founders. Both have a brilliant business sense (one actually founded a multi-million dollar company already), and they have close ties in many of the industries we're trying to penetrate. Consequently, they've brought in some great business and continue to keep jobs in the pipeline.

The problem

The problem we can't seem to shake is how to bring these two awesome advantages together. On the business side, there is a huge pressure to deliver as fast as possible as much as possible, whereas on the development side there is pressure to take your time, come up with the right solution, and pay attention to all the details.

Lately these two sides have been butting heads a lot. Developers are demanding quality while managers are demanding quantity.

How can we handle this? Both sides are correct. We can't survive as a company if we build terrible applications, but we also can't survive if we don't sell enough. So how should we go about making compromises?

Things we've done with little or no success:

Work more (well, it did result in better quality and faster delivery, but the dev team has never been more stressed out before)

Charge more (as a startup, we don't yet have the credibility to justify higher prices, so no one is willing to pay)

Extend deadlines (if we charge the same, but take longer, we'll end up losing money)

Things we've done with some success:

Sacrifice pay to cut costs (everyone, from devs to management, is paid less than they could be making elsewhere. In return, however, we all have creative input and more flexibility and freedom, a typical startup trade off)

Standardize project management (we recently started adhering to agile/scrum principles so we can base deadlines on actual velocity, not just arbitrary guesses)

Hire more people (we used to have 2 developers and no designers, which really limited our bandwidth. However, as a startup we can only afford to hire a few extra people.)

Is there anything we're missing or doing wrong? How is this handled at successful companies?

Thanks in advance for any feedback :)

答:
The dilemma is that

"Cost",

"Time",

"Quality" and

"Scope"

are interrelated: you can only choose three of them
as described in http://en.wikipedia.org/wiki/Project_management_triangle .

In most cases these dimensions are fixed:

Cost (available money)

and Time (i.e. next trade faire)

Successfull companies manage the scope or feature-list: they concentrate on features that really matter where

the customer is willing to pay for.

@VirtuosiMedia execelent answer shows a way how to identify these features.


答:
A wrapper is a layer, code portion, stuff which encapsulate the inside logic of the final task or processus.

We can say there's two main types of wrappers :

abstraction wrappers : the principle is to hide/abstract the final task to be as least bound to it as possible (ie. the wrapper caller don't need to know the final task logic).

engine/controller wrappers : they are used to add a specific or context logic which cannot -or is not supposed to- be done by the final task.

Note that a wrapper can achieve this two goals as well.

It can be used in many cases but about a program, a wrapper program is a "program launcher". Its main goal is to launch the child program.

It may pass some context parameters to the child program, handle pre-launch and after-launch steps, restart/shutdown it etc...

It can launch the child program as a new process or as an inner process but the wrapper program execution is directly linked to the child program execution : if the wrapper stops, the child program stops.

To compare to a third-party client, a third-party client don't care about the child program process. It is there to maintain the child program files/configuration/stuff but is not responsible of its execution even if it may launch it.

Title: What is a "wrapper" program?

Body:
Where I work, employees use a third-party desktop program for their clients. This program saves data to a flat file. My colleague wants to write a Java program that uploads that flat file to a remote server, opens the desktop program when the flat file is downloaded from a Web site, and checks if the desktop program is running or not by looking at the Windows processes.

He keeps calling this helper/utility program a "wrapper." But it doesn't wrap anything! I tried to clear it up with him, but he said, "Well, I call it a wrapper." He now has everyone in the company calling it a "wrapper." What would you call it? I say that it's a helper program or utility program.


答:
The logic programming language Prolog may be what you're looking for. Your problem statement is not specific enough for me to assess if it's a good fit but it's rather similar to what you say.

A Prolog program consists of facts and rules that are applied. Here's a simple example rule that states "A cow moves to a location if the cow is hungry and there is more food in the new location than in the old location":

```<code>moves_to(Cow, Location) :-
  hungry(Cow),
  current_location(Cow, OldLoc),
  food_in(OldLoc, OldFood), food_in(Location, NewFood),
  NewFood > OldFood.
</code>```

All things in capital letters are variables, things you don't know the value of. Prolog attempts to find values for these variables that satisfies all the conditions. This process is done with a powerful algorithm called unification that is the heart of Prolog and similar logic programming environments.

In addition to the rules, a database of facts is provided. A simple example that works with the rules above could be something like:

```<code>current_location(white_cow, pasture).

current_location(black_cow, barn).
hungry(black_cow).

current_location(angry_bull, forest).
hungry(angry_bull).

food_in(barn, 3).
food_in(pasture, 5).
food_in(forest, 1).
</code>```

Notice that white_cow and pasture, etc. are not written in capitals. They are not variables, they are atoms.

Finally you make a query and ask what's going to happen.

```<code>?- moves_to(white_cow, Destination).
No.
?- moves_to(black_cow, Destination).
Destination = pasture
?- moves_to(Cow, Destination).
Cow = black_cow, Destination = pasture
Cow = angry_bull, Destination = barn
Cow = angry_bull, Destination = pasture
</code>```

The first query asks where the white cow will move. Given the rules and the facts above, the answer is No. This can be interpreted as "I don't know" or "It doesn't move" depending on what you want.

The second query asks where the black cow moves. It moves to the pasture to eat.

The final query asks where do all the cows move. As a result you get all the possible (Cow, Destination) that make sense. In this case the black bull moves to the pasture as expected. However, the angry bull has two choices that satisfy the rules, it can either move to the pasture or the barn.

Note: It's been years since I last wrote Prolog, all examples may not be syntactically valid but the idea should be correct.

Title: How can one manage thousands of IF...THEN...ELSE rules?

Body:
I am considering building an application, which, at its core, would consist of thousands of if...then...else statements. The purpose of the application is to be able to predict how cows move around in any landscape. They are affected by things like the sun, wind, food source, sudden events etc.

How can such an application be managed? I imagine that after a few hundred IF-statements, it would be as good as unpredictable how the program would react and debugging what lead to a certain reaction would mean that one would have to traverse the whole IF-statement tree every time.

I have read a bit about rules engines, but I do not see how they would get around this complexity.

Body:
The logic programming language Prolog may be what you're looking for. Your problem statement is not specific enough for me to assess if it's a good fit but it's rather similar to what you say.

A Prolog program consists of facts and rules that are applied. Here's a simple example rule that states "A cow moves to a location if the cow is hungry and there is more food in the new location than in the old location":

moves_to(Cow, Location) :-
  hungry(Cow),
  current_location(Cow, OldLoc),
  food_in(OldLoc, OldFood), food_in(Location, NewFood),
  NewFood > OldFood.

All things in capital letters are variables, things you don't know the value of. Prolog attempts to find values for these variables that satisfies all the conditions. This process is done with a powerful algorithm called unification that is the heart of Prolog and similar logic programming environments.

In addition to the rules, a database of facts is provided. A simple example that works with the rules above could be something like:

current_location(white_cow, pasture).

current_location(black_cow, barn).
hungry(black_cow).

current_location(angry_bull, forest).
hungry(angry_bull).

food_in(barn, 3).
food_in(pasture, 5).
food_in(forest, 1).

Notice that white_cow and pasture, etc. are not written in capitals. They are not variables, they are atoms.

Finally you make a query and ask what's going to happen.

?- moves_to(white_cow, Destination).
No.
?- moves_to(black_cow, Destination).
Destination = pasture
?- moves_to(Cow, Destination).
Cow = black_cow, Destination = pasture
Cow = angry_bull, Destination = barn
Cow = angry_bull, Destination = pasture

The first query asks where the white cow will move. Given the rules and the facts above, the answer is No. This can be interpreted as "I don't know" or "It doesn't move" depending on what you want.

The second query asks where the black cow moves. It moves to the pasture to eat.

The final query asks where do all the cows move. As a result you get all the possible (Cow, Destination) that make sense. In this case the black bull moves to the pasture as expected. However, the angry bull has two choices that satisfy the rules, it can either move to the pasture or the barn.

Note: It's been years since I last wrote Prolog, all examples may not be syntactically valid but the idea should be correct.


问:
What is the best way to handle references in a .NET application
Recently at work we ran into a problem where we tagged/branched a project and had some compiling issues because of dll/project references that was pointing to the old folder structure.

We created an 'external bin' folder for each of the projects and copied the referenced dll's to these folders. Is this the best way or is there a specific industry standard to handle this?

答: This depends on how your solution is structured and what your version control software capabilities are. Previously, we used to keep an unbuilt/skipped project in our solutions that held documentation and a folder specifically for any third party referenced libraries. Since it was part of the solution, the path to these files could be referenced using the relative path. After we moved to TFS 2010, got rid of this project and simply added a "Support" directory in that solution's folder in the team project parallel to our main branches. In either case, the source control version of the library ends up being in the same place relatively regardless of how the developers have their machines configured.</p>


答:
I would say that nuget is the best way to handle dependencies.

nuget can manage versions AND automatically download the dependencies from your local nuget server.

It's quite easy to create/configure a local server. Simply create a new empty ASP.NET project and install the nuget-server nuget package (using nuget ;).

That also means that you wont have to check in all dependencies and/or manage their versions using TFS.

Title: What is the best way to handle references in a .NET application

Body:
Recently at work we ran into a problem where we tagged/branched a project and had some compiling issues because of dll/project references that was pointing to the old folder structure.

We created an 'external bin' folder for each of the projects and copied the referenced dll's to these folders. Is this the best way or is there a specific industry standard to handle this?


问:
Integrating with a payment provider; Proper and robust OOP approach

History

We are currently using a so called redirect model for our online payments (where you send the payer to a payment gateway, where he inputs his payment details - the gateway will then return him to a success/failure callback page). That's easy and straight-forward, but unfortunately quite inconvenient and at times confusing for our customers (leaving the site, changing their credit card details with an additional login on another site etc).

Intention & Problem description

We are now intending to switch to an integrated approach using an exchange of XML requests and responses. My problem is on how to cater with all (or rather most) of the things that may happen during processing - bearing in mind that normally simplicity is robust whereas complexity is fragile.

Examples

User abort: The user inputs Credit Card details and hits submit. An XML message to the provider's gateway is sent and waiting for response. The user hits "stop" in his browser or closes the window.

ignore_user_abort() in PHP may be an option - but is that reliable?

might it be better to redirect the user to a "please wait"-page, that in turn opens an AJAX or other request to the actual processor that does not rely on the connection?

Database goes away

sounds over-complicated, but with e.g. a webserver in the States and a DB in the UK, it has happened and will happen again: User clicks together his order, payment request has been sent to the provider but the response cannot be stored in the database. What approach could I use, using PHP to sort of start an SQL like "Transaction" that only at the very end gets committed or rolled back, depending on the individual steps? Should then neither commit or roll back have happened, I could sort of "lock" the user to prevent him from paying again or to improperly account for payments - but how?

And what else do I need to consider technically? None of the integration examples of e.g. Worldpay, Realex or SagePay offer any insight, and either my search engine or my search terms weren't good enough to find somebody else's thoughts on this.

Thank you very much for any insight on how you would approach this!

答:
In my honest opinion, the best way to to manage transactions through a Payment Gateway is through web services.  A number of different payment gateways offer these kinds of services for competitive flat percentage rates per transaction + the typical credit card commission that the customers credit card will take as well (Eg. Cybersource).  With much everything in life, you get what you pay for, a 9 cent/transaction doesn't exist with a reputable payment processor that doesn't force you to redirect users.

Tokenization and secure data

Storing credit card details on your system is just asking for trouble, and depending on where you live there may even be legal requirements and possible criminal laws against how this data is being managed.  Unless you are Amazon, you shouldn't have to worry about all that technical and legal complexity.  The payment processor takes this risk and complexity away from you by having SSL encrypted web services where credit card details can be passed through your site to your server, and from your server to the payment processor web services to submit a payment through your account with the processor.  In return, the web service will give you back an authorization code, or a token that uniquely signifies the transaction on their system, and gives you a reference number for quickly searching through your account for specific transactions.  You can retain the token in your database and it is of no real consequence to the users if the tokens are compromised on your system.  Further by not storing credit card details at all on your system, users bank accounts are safe even if your system has been compromised.

Retention of payment records

This approach to integrating with a payment processor has the added benefit of being able to maintain your own payment and purchase records that are seperate from that of your payment processor, yet linked through the token.  This allows you to run revenue reports through your system, analytical queries and users can view their purchases without actually having to query the payment processor for information.

PCI Compliance

Any reputable payment processor will have all of their systems and data hosted in PCI Compliant servers and facilities.  For more information on the details of PCI Compliance itself, and why it is important, see this site.

There are certain requirements that they must adhere to, their data center must be secured physically as well as technically.  They cannot have any unencrypted WAP's on their network, etc...  None of this will really concern you however there are a number of requirements expected of merchant systems for them to claim PCI Compliance as well.  Some of these requirements include but are not limited to:

Using SSL encryption on any payment request through your site.

Under no circumstances should there be credit card numbers stored anywhere in any of your systems, including log files and even serialized objects.

Application servers communicating with the payment processor must be behind a well configured firewall that only allows the minimum number of open ports required.

Only appropriate technical personnel should be allowed physical or remote access to these application servers on your network.

Others...

Typically most payment processors will provide an online tool that can run on your network and identify possible issues with becoming PCI Compliant.  It is still not a NECESSARY or REQUIRED thing to have to work with a payment processor, but the payment processor reserves the right to charge you additional fees if you utilize their services and do not meet PCI Compliance standards.


问:
Why setter method when getter method enough in PHP OOP
I am practicing OOP with PHP, and I am struck at setter and getter methods.

I can directly access the class properties and methods with getter method then what's the use of setter method?

See my example.

```<code><?php
class MyClass{
    public $classVar = "Its a class variable";
    public function Getter(){
        return $this -> classVar;
    }
}
$obj = new MyClass;
echo $obj -> Getter();
?>
</code>```

答:
Your class variable $classVar shouldn't be public.

One of the reasons for having getters and setters is to hide your implementation. By making the class variable public you are exposing your implementation thus negating this benefit.

Make the variable private.


问:
Is it dangerous for me to give some of my Model classes Control-like methods?
In my personal project I have tried to stick to MVC, but I've also been made aware that sticking to MVC too tightly can be a bad thing as it makes writing awkward and forces the flow of the program in odd ways (i.e. some simple functions can be performed by something that normally wouldn't, and avoid MVC related overheads).

So I'm beginning to feel justified in this compromise:

I have some 'manager programs' that 'own' data and have some way to manipulate it, as such I think they'd count as both part of the model, and part of the control, and to me this feels more natural than keepingthem separate. For instance: One of my Managers is the PlayerCharacterManager that has these methods:

```<code>void buySkill(PlayerCharacter playerCharacter, Skill skill);
void changeName();
void changeRole();
void restatCharacter();
void addCharacterToGame();
void createNewCharacter();
PlayerCharacter getPlayerCharacter();
List<PlayerCharacter> getPlayersCharacter(Player player);
List<PlayerCharacter> getAllCharacters();
</code>```

I hope the mothod names are transparent enough that they don't all need explaining.

I've called it a manager because it will help manage all of the PlayerCharacter 'model' objects the code creates, and create and keep a map of these. I may also get it to store other information in the future.

I plan to have another two similar classes for this sort of control, but I will orchestrate when and how this happens, and what to do with the returned data via a pure controller class. This splitting up control between informed managers and the controller, as opposed to operating just through a controller seems like it will simplify my code and make it flow more.

My question is, is this a dangerous choice, in terms of making the code harder to follow/test/fix? Is this somethign established as good or bad or neutral? I oculdn't find anything similar except the idea of Actors but that's not quite why I'm trying to do.

Edit: Perhaps an example is needed; I'm using the Controller to update the view and access the data, so when I click the 'Add new character to a player button' it'll call methods in the controller that then go and tell the PlayerCharacterManager class to create a new character instance, it'll call the PlayerManager class to add that new character to the player-character map, and then it'll add this information to the database, and tell the view to update any GUIs effected. That is the sort of 'control sequence' I'm hoping to create with these manager classes.

答:
The difference between Model and Controller can be subtle, but it boils down to this:  Who is in charge here?

If you make a class which manages all aspects of a PlayerCharacter, that isn't necessarily a Controller.  Somebody calls this manager, say, a class called Engine which calls all respective classes to draw, perform calculations, requests changes to made to players (PlayerCharacter gets called here presumably).  Engine is the Controller, not PlayerCharacter.

Most often, parameters to control classes are configurations, altering generic attributes but saying nothing about how that method is to behave.  Alternatively, model classes do very specific tasks and should be transparent as to what it does.  Their parameters are important because they directly influence the behavior of the method (getPlayersCharacter for instance). Since all your methods listed above are rather transparent, you can conclude that you are writing a model class, not a controller.

Methods to a controller class would look more like:

```<code>void Engine::run(Configuration c);
void Engine::run(Configuration c, Logger l);
</code>```

Notice that since it does a variety of things, it is very generic in nature.  Ideally, it is a relatively short method which relies on many higher-level model classes to do its operations, but sometimes it is necessary to have more than one Controller class to manage various aspects.  However the principle is the same.  In those classes, you would see little difference in method naming.  Just be wary to include generic controller methods in an otherwise model class.  That is the essence of MVC.

I hope that answers your question.

Body:
The difference between Model and Controller can be subtle, but it boils down to this:  Who is in charge here?

If you make a class which manages all aspects of a PlayerCharacter, that isn't necessarily a Controller.  Somebody calls this manager, say, a class called Engine which calls all respective classes to draw, perform calculations, requests changes to made to players (PlayerCharacter gets called here presumably).  Engine is the Controller, not PlayerCharacter.

Most often, parameters to control classes are configurations, altering generic attributes but saying nothing about how that method is to behave.  Alternatively, model classes do very specific tasks and should be transparent as to what it does.  Their parameters are important because they directly influence the behavior of the method (getPlayersCharacter for instance). Since all your methods listed above are rather transparent, you can conclude that you are writing a model class, not a controller.

Methods to a controller class would look more like:

void Engine::run(Configuration c);
void Engine::run(Configuration c, Logger l);

Notice that since it does a variety of things, it is very generic in nature.  Ideally, it is a relatively short method which relies on many higher-level model classes to do its operations, but sometimes it is necessary to have more than one Controller class to manage various aspects.  However the principle is the same.  In those classes, you would see little difference in method naming.  Just be wary to include generic controller methods in an otherwise model class.  That is the essence of MVC.

I hope that answers your question.


答: A "wrapper" is whatever sales, management, or marketing wants to call it.  Have you seen the new commercials touting Windows as "the cloud?"  That's right, you get your own "little cloud" right there on the desktop...</p>

Title: What is a "wrapper" program?


答:
It's all about who owns the copyright on the code.  The contract that your company has with its customers should spell out that your company owns the copyright, and you're just selling them a license.  In that case it doesn't matter if you provide them a copy of the code.  I've seen cases where your license provides for the customer to have a copy of the code and make changes as long as it's only used on the one site where it's licensed for (that particular factory).

On the other hand, if there's some ambiguity about who owns the copyright, then you've got bigger problems.


答:
Depends on your intended usage.  If you have a standard graph or report showing aggregate values, then you'll want to simply filter the events as they come in and aggregate them into the appropriate bucket.  If you need to drill down into specific events, or if you think you might want to go back and re-analyze / re-categorize events later, then you should store the individual events.

If you've got the time and space, what I typically like to do is aggregate the data, but store the details in a (compressed) file.  The details don't have to be easily accessible, since I almost never need them, but they're available for bulk re-processing if the classification criteria change.

Title: Data architecture for event log metrics?

Body:
My service has a large ongoing number of user events, and we would like to do things like "count occurrence of event type T since date D."

We are trying to make two basic decisions:

What to store?  Storing every event vs. only storing aggregates

(Event log style) log every event and count them later, vs.

(Time-series style) store a single aggregated "count of event E for date D" for every day

Where to store the data

In a relational database (particularly MySQL)

In a non-relational (NoSQL) database

In flat log files (collected centrally over the network via syslog-ng)

What is standard practice / where can I read more about comparing the different types of systems?

Additional details:

The total event stream is large, potentially hundreds of thousands of entries per day

But our current need is only to count certain types of events within it

We don't necessarily need real-time access to the raw data or aggregation results

IMHO, "log all events to files, crawl them at a later time to filter and aggregate the stream" is a pretty standard UNIX Way, but my Rails-y compatriots seem to think that nothing is real unless it's in MySQL.