问:
Can web technologies, like PHP, HTML, and CSS, be used for desktop development?
I have to develop an application for a gas agency where a database will store consumer numbers, names, addresses, and date delivered for a town with nearly 20,000 people. I only know PHP, MySQL, CSS, jQuery, and other web based technologies. Is it possible to deliver a package to the client using these technologies that can be installed on a computer and used locally?

This application will run on a single PC for a single user. I'm familiar with tools such as XAMPP, but I do not want to run a web server locally. Both the application and database will be securely running on a particular computer. In the future, if this application must be on multiple computers, I want the database and application to be portable.

I have searched for similar questions on Stack Overflow and I did find some recommendations like Jetty, Adobe Air and the recent Web SQL database. Is PHP GTK also a viable tool for building professional applications?

I would like a recommendation specific for this kind of app.

答:
I have been after the same thing, but for different purposes. My search lead me to Titanium

Its description from its website:

Titanium makes cross-platform native application development easy. A
  free and open source application development platform, Titanium lets
  you create native mobile, tablet and desktop application experiences
  using existing web skills like Javascript, HTML, CSS, Python, Ruby,
  and PHP

Alternatively you could try Server2Go. Basically it is a standalone WAMP server that you can put on a CD/USB disk etc. The problem with that would be the MySQL db would be read only if the server is to be on a CD. But then you can always use SQLLite db stored in the local disk or get around it differently.

I'm thinking Titanium will solve your problem... I should add that I haven't used it enough to know how good it is but there usually are positive reviews about it.


问:
std::shared_ptr as a last resort?
I was just watching the "Going Native 2012" streams and I noticed the discussion about std::shared_ptr. I was a bit surprised to hear Bjarne's somewhat negative view on std::shared_ptr and his comment that it should be used as a "last resort" when an object's life-time is uncertain (which I believe, according to him, should infrequently be the case).

Would anyone care to explain this in a bit more depth? How can we program without std::shared_ptr and still manage object life-times in a safe way?

答:
I prefer not thinking in absolute terms (like "last resort") but relative to the problem domain.

C++ can offer a number of different ways to manage lifetime. Some of them try to re-conduce the objects in a stack-driven way. Some other try to escape this limitation.
Some of them are "literal", some other are approximations.

Actually you can:

use pure value semantics. Works for relatively small objects where what is important are "values" and not "identities", where you can assume that two Person having an same name are the same person (better: two representation of a same person). Lifetime is granted by the machine stack, end -essentially- deosn't matter to the program (since a person is it s name, no matter what Person is carrying it)

use stack allocated objects, and related reference or pointers: allows polymorphism, and grants object lifetime. No need of "smart pointers", since you ensure no object can be "pointed" by structures that leave in the stack longer than the object they point to (first create the object, then the structures that refer to it).

use stack managed heap allocated objects: this is what std::vector and all containers do, and wat std::unique_ptr does (you can think to it as a vector with size 1). Again, you admit the object begin to exist (and end their existence) before (after) the data structure they refer to.

The weakness of this mehtods is that object types and quantities cannot vary during the execution of deeper stack level calls in respect to where they are created.
All this techniques "fail" their strength in all the situation where creation and deletion of object are consequence of user activities, so that the runtime-type of the object is not compile-time known and there can be over-structures referring to objects the user is asking to remove from a deeper stack-level function call.
In this cases, you have to either:

introduce some discipline about managing object and related referring structures or ...

go somehow to the dark side of "escape the pure stack based lifetime": object must leave independently of the functions that created them.
And must leave ... until they're needed.

C++ isteslf doesn't have any native mechanism to monitor that event (while(are_they_needed)), hence
you have to approximate with:

use shared ownership: objects life is bound to a "reference counter": works if "ownership" can be hierarchically organized, fails where ownership loops may exist. This is what std::shared_ptr does. And weak_ptr can be used to break the loop.  This works the most of the time but fails in large design, where many designer works in different teams and there is no clear reason (something coming from a somewhat requirement) about who musty own what (the typical example are dual liked chains: is the previous owing the next referring the previous or the next owning the previous referring the next? In absebce of a requirement the tho solutions are equivalent, and in large project you risk to mix them up)

Use a garbage collecting heap: You simply don't care bout lifetime. You run the collector time to time and what is unreachabe is considered "not anymore needed" and ... well ... ahem ... destroyed? finalized? frozen?. There are a number of GC collector, but I never find one that is really C++ aware. The most of them free memory, not caring about object destruction.

Use a C++ aware garbage collector, with a proper standard methods interface. Good luck to find it.

Going to the very first solution to the last one, the amount of auxiliary data structure required to manage object lifetime increase, as the time spend to organize it and maintain it.

Garbage collector have cost, shared_ptr have less, unique_ptr even less, and stack managed objects have very few.

Is shared_ptr the "last resort"?.
No, it's not: the last resort are garbage collectors.
shared_ptr is actually the std:: proposed last resort. But may be the righ solution, if you are in the situation I explained.

OwnerDisplayName: ronag

ContentLicense: CC BY-SA 3.0

Title: std::shared_ptr as a last resort?


问:
Is C++11 Uniform Initialization a replacement for the old style syntax?
I understand that C++11's uniform initialization solves some syntactical ambiguity in the language, but in a lot of Bjarne Stroustrup's presentations (particularly those during the GoingNative 2012 talks), his examples primarily use this syntax now whenever he is constructing objects.

Is it recommended now to use uniform initialization in all cases? What should the general approach be for this new feature as far as coding style goes and general usage? What are some reasons to not use it?

Note that in my mind I'm thinking primarily of object construction as my use case, but if there are other scenarios to consider please let me know.

答:
If your constructors merely copy their parameters in the respective class variables in exactly the same order in which they are declared inside the class, then using uniform initialization can eventually be faster (but can also be absolutely identical) than calling the constructor.

Obviously, this doesn't change the fact that you must always declare the constructor.

OwnerDisplayName: Robert Dailey

OwnerDisplayName: Gigi


问:
When do you know it's time to move on from your current job?
Have you ever reached a point at your job when you just know it's time to move on?

When do you move to the point that you're willing to let go of the demons you know for the ones you don't know?

What was your deciding factor final straw so to speak when you finally faced the decision to find a new job?

答: The last full time job I left was because I became 'too valuable' to maintaining our very successful - and award winning, I might add - system that they would not assign me to the task of designing a new system.  At that point I realized they werent interested in rewarding success, and didnt appreciate the notion of domain knowledge, so I jumped ship, leaving an ever more and more depressing corporate environment for a very fun dot-com.</p>

ContentLicense: CC BY-SA 2.5


答:
Coding style is ultimately subjective, and it is highly unlikely that substantial performance benefits will come from it. But here's what I would say that you gain from liberal use of uniform initialization:

Minimizes Redundant Typenames

Consider the following:

```<code>vec3 GetValue()
{
  return vec3(x, y, z);
}
</code>```

Why do I need to type vec3 twice? Is there a point to that? The compiler knows good and well what the function returns. Why can't I just say, "call the constructor of what I return with these values and return it?" With uniform initialization, I can:

```<code>vec3 GetValue()
{
  return {x, y, z};
}
</code>```

Everything works.

Even better is for function arguments. Consider this:

```<code>void DoSomething(const std::string &str);

DoSomething("A string.");
</code>```

That works without having to type a typename, because std::string knows how to build itself from a const char* implicitly. That's great. But what if that string came from, say RapidXML. Or a Lua string. That is, let's say I actually know the length of the string up front. The std::string constructor that takes a const char* will have to take the length of the string if I just pass a const char*.

There is an overload that takes a length explicitly though. But to use it, I'd have to do this: DoSomething(std::string(strValue, strLen)). Why have the extra typename in there? The compiler knows what the type is. Just like with auto, we can avoid having extra typenames:

```<code>DoSomething({strValue, strLen});
</code>```

It just works. No typenames, no fuss, nothing. The compiler does its job, the code is shorter, and everyone's happy.

Granted, there are arguments to be made that the first version (DoSomething(std::string(strValue, strLen))) is more legible. That is, it's obvious what's going on and who's doing what. That is true, to an extent; understanding the uniform initialization-based code requires looking at the function prototype. This is the same reason why some say you should never pass parameters by non-const reference: so that you can see at the call site if a value is being modified.

But the same could be said for auto; knowing what you get from auto v = GetSomething(); requires looking at the definition of GetSomething. But that hasn't stopped auto from being used with near reckless abandon once you have access to it. Personally, I think it'll be fine once you get used to it. Especially with a good IDE.

Never Get The Most Vexing Parse

Here's some code.

```<code>class Bar;

void Func()
{
  int foo(Bar());
}
</code>```

Pop quiz: what is foo? If you answered "a variable", you're wrong. It's actually the prototype of a function that takes as its parameter a function that returns a Bar, and the foo function's return value is an int.

This is called C++'s "Most Vexing Parse" because it makes absolutely no sense to a human being. But the rules of C++ sadly require this: if it can possibly be interpreted as a function prototype, then it will be. The problem is Bar(); that could be one of two things. It could be a type named Bar, which means that it is creating a temporary. Or it could be a function that takes no parameters and returns a Bar.

Uniform initialization cannot be interpreted as a function prototype:

```<code>class Bar;

void Func()
{
  int foo{Bar{}};
}
</code>```

Bar{} always creates a temporary. int foo{...} always creates a variable.

There are many cases where you want to use Typename() but simply can't because of C++'s parsing rules. With Typename{}, there is no ambiguity.

Reasons Not To

The only real power you give up is narrowing. You cannot initialize a smaller value with a larger one with uniform initialization.

```<code>int val{5.2};
</code>```

That will not compile. You can do that with old-fashioned initialization, but not uniform initialization.

This was done in part to make initializer lists actually work. Otherwise, there would be a lot of ambiguous cases with regard to the types of initializer lists.

Of course, some might argue that such code deserves to not compile. I personally happen to agree; narrowing is very dangerous and can lead to unpleasant behavior. It's probably best to catch those problems early on at the compiler stage. At the very least, narrowing suggests that someone isn't thinking too hard about the code.

Notice that compilers will generally warn you about this sort of thing if your warning level is high. So really, all this does is make the warning into an enforced error. Some might say that you should be doing that anyway ;)

There is one other reason not to:

```<code>std::vector<int> v{100};
</code>```

What does this do? It could create a vector<int> with one hundred default-constructed items. Or it could create a vector<int> with 1 item who's value is 100. Both are theoretically possible.

In actuality, it does the latter.

Why? Initializer lists use the same syntax as uniform initialization. So there have to be some rules to explain what to do in the case of ambiguity. The rule is pretty simple: if the compiler can use an initializer list constructor with a brace-initialized list, then it will. Since vector<int> has an initializer list constructor that takes initializer_list<int>, and {100} could be a valid initializer_list<int>, it therefore must be.

In order to get the sizing constructor, you must use () instead of {}.

Note that if this were a vector of something that wasn't convertible to an integer, this wouldn't happen. An initializer_list wouldn't fit the initializer list constructor of that vector type, and therefore the compiler would be free to pick from the other constructors.

Title: Is C++11 Uniform Initialization a replacement for the old style syntax?

Body:
I understand that C++11's uniform initialization solves some syntactical ambiguity in the language, but in a lot of Bjarne Stroustrup's presentations (particularly those during the GoingNative 2012 talks), his examples primarily use this syntax now whenever he is constructing objects.

Is it recommended now to use uniform initialization in all cases? What should the general approach be for this new feature as far as coding style goes and general usage? What are some reasons to not use it?

Note that in my mind I'm thinking primarily of object construction as my use case, but if there are other scenarios to consider please let me know.

Body:
Coding style is ultimately subjective, and it is highly unlikely that substantial performance benefits will come from it. But here's what I would say that you gain from liberal use of uniform initialization:

Minimizes Redundant Typenames

Consider the following:

vec3 GetValue()
{
  return vec3(x, y, z);
}

Why do I need to type vec3 twice? Is there a point to that? The compiler knows good and well what the function returns. Why can't I just say, "call the constructor of what I return with these values and return it?" With uniform initialization, I can:

vec3 GetValue()
{
  return {x, y, z};
}

Everything works.

Even better is for function arguments. Consider this:

void DoSomething(const std::string &str);

DoSomething("A string.");

That works without having to type a typename, because std::string knows how to build itself from a const char* implicitly. That's great. But what if that string came from, say RapidXML. Or a Lua string. That is, let's say I actually know the length of the string up front. The std::string constructor that takes a const char* will have to take the length of the string if I just pass a const char*.

There is an overload that takes a length explicitly though. But to use it, I'd have to do this: DoSomething(std::string(strValue, strLen)). Why have the extra typename in there? The compiler knows what the type is. Just like with auto, we can avoid having extra typenames:

DoSomething({strValue, strLen});

It just works. No typenames, no fuss, nothing. The compiler does its job, the code is shorter, and everyone's happy.

Granted, there are arguments to be made that the first version (DoSomething(std::string(strValue, strLen))) is more legible. That is, it's obvious what's going on and who's doing what. That is true, to an extent; understanding the uniform initialization-based code requires looking at the function prototype. This is the same reason why some say you should never pass parameters by non-const reference: so that you can see at the call site if a value is being modified.

But the same could be said for auto; knowing what you get from auto v = GetSomething(); requires looking at the definition of GetSomething. But that hasn't stopped auto from being used with near reckless abandon once you have access to it. Personally, I think it'll be fine once you get used to it. Especially with a good IDE.

Never Get The Most Vexing Parse

Here's some code.

class Bar;

void Func()
{
  int foo(Bar());
}

Pop quiz: what is foo? If you answered "a variable", you're wrong. It's actually the prototype of a function that takes as its parameter a function that returns a Bar, and the foo function's return value is an int.

This is called C++'s "Most Vexing Parse" because it makes absolutely no sense to a human being. But the rules of C++ sadly require this: if it can possibly be interpreted as a function prototype, then it will be. The problem is Bar(); that could be one of two things. It could be a type named Bar, which means that it is creating a temporary. Or it could be a function that takes no parameters and returns a Bar.

Uniform initialization cannot be interpreted as a function prototype:

class Bar;

void Func()
{
  int foo{Bar{}};
}

Bar{} always creates a temporary. int foo{...} always creates a variable.

There are many cases where you want to use Typename() but simply can't because of C++'s parsing rules. With Typename{}, there is no ambiguity.

Reasons Not To

The only real power you give up is narrowing. You cannot initialize a smaller value with a larger one with uniform initialization.

int val{5.2};

That will not compile. You can do that with old-fashioned initialization, but not uniform initialization.

This was done in part to make initializer lists actually work. Otherwise, there would be a lot of ambiguous cases with regard to the types of initializer lists.

Of course, some might argue that such code deserves to not compile. I personally happen to agree; narrowing is very dangerous and can lead to unpleasant behavior. It's probably best to catch those problems early on at the compiler stage. At the very least, narrowing suggests that someone isn't thinking too hard about the code.

Notice that compilers will generally warn you about this sort of thing if your warning level is high. So really, all this does is make the warning into an enforced error. Some might say that you should be doing that anyway ;)

There is one other reason not to:

std::vector<int> v{100};

What does this do? It could create a vector<int> with one hundred default-constructed items. Or it could create a vector<int> with 1 item who's value is 100. Both are theoretically possible.

In actuality, it does the latter.

Why? Initializer lists use the same syntax as uniform initialization. So there have to be some rules to explain what to do in the case of ambiguity. The rule is pretty simple: if the compiler can use an initializer list constructor with a brace-initialized list, then it will. Since vector<int> has an initializer list constructor that takes initializer_list<int>, and {100} could be a valid initializer_list<int>, it therefore must be.

In order to get the sizing constructor, you must use () instead of {}.

Note that if this were a vector of something that wasn't convertible to an integer, this wouldn't happen. An initializer_list wouldn't fit the initializer list constructor of that vector type, and therefore the compiler would be free to pick from the other constructors.

OwnerDisplayName: Nicol Bolas


问:
Mission critical embedded language
Maybe the question sounds a bit strange, so I'll explain a the background a little bit.

Currently I'm working on a project at y university, which will be a complete on-board software for an satellite. The system is programmed in C++ on top of a real-time operating system. However, some subsystems like the attitude control system and the fault detection and a space simulation are currently only implemented in Matlab/Simulink, to prototype the algorithms efficiently. After their verification, they will be translated into c++.

The complete on-board software grew very complex, and only a handful people know the whole system. Furthermore, many of the students haven't program in C++ yet and the manual memory management of C++ makes it even more difficult to write mission critical software.

Of course the main system has to be implemented in C++, but I asked myself if it's maybe possible to use an embedded language to implement the subsystem which are currently written in Matlab. This embedded language should feature:

static/strong typing and compiler checks to minimize runtime errors

small memory usage, and relative fast runtime

attitude control algorithms are mainly numerical computations, so a good numeric support would be nice

maybe some sort of functional programming feature, matlab/simulink encourage you to use it too

I googled a bit, but only found Lua. It looks nice, but I would not use it in mission critical software. Have you ever encountered a situation like this, or do you know any language, which could satisfies the conditions?

EDIT: To clarify some things: embedded means it should be able to embed the language into the existing C++ environment. So no compiled languages like Ada or Haskell

答:
I'm not certain what "mission-critical" is, but for what it's worth I have 10+ years of experience in software development for safety-critical embedded systems.

No matter what language you pick, you will definitely need a coding standard. That is, rules for how to write programs, which mechanisms that are allowed and which ones that are banned. The rules should be in the manner of "don't use goto", "don't use function-like macros" etc.

This is particularly important if you have junior programmers participating in the project. Because they might not know what mechanisms that are regarded as good practice and which ones that are bad. And they will almost certainly not know about all the hundreds of obscure and subtle cases of undefined behavior that the language contains, and other such advanced, yet extremely important topics. For example, one can probably write a very thick book just on the topic of all the undefined/unspecified/implementation-defined behavior in C++.

In addition, industry safety standards like DO178B or IEC 61508 enforce the use of a well-defined subset of the programming language, and then you must have a coding standard.

The sensible thing to do if you have no experience of coding standards is to pick one of the pre-made, widely recognized ones that are industry de-facto standard: MISRA-C, MISRA-C++, SPARK ADA, Cert C etc. The advantage of such industry coding standards is that there are already software testing tools, aka static/dynamic code analyzers with support for them. Don't even consider this project without a proper code analyzer tool!

(Parenthesis regarding technical specifics: you will any form of dynamic memory management banned with bold letters in any coding standard for high integrity systems, no matter language. Generally, it doesn't make sense for such systems to behave in non-deterministic ways, and dynamic memory only makes sense in non-deterministic scenarios.)

Title: Mission critical embedded language


问:
Should I use WADL to describe my RESTful API?
I'm about to embark on a project that makes extensive use of a properly RESTful approach. That is, it uses HATEOAS and serves up resources in a manner that allows for general exploration by a client.

I would like to ensure that I provide a description of my endpoints in a manner that would allow client applications to be automatically generated in a wide variety of languages. I understand that for SOAP based web services I can use WSDL and that apparently there is WSDL2 that provides greater definition of the HTTP verbs in use with REST. However I see many articles swinging back and forth over it's utility.

So, should I use WADL to allow external code generators to quickly build a client for my web application or is there a better standard that is expected?

答:
My advice is not to bother. WADL has not been that widely adopted See this question on Stack Overflow and there are some strong views that's it's not a good fit with the kind of 'proper' REST you describe, as shown here on another Stack Overflow question.

WADL descriptions are time consuming to build (and mostly manual) and they add a brittleness that HATEOAS is designed to avoid - i.e. you'll have some well defined entry points but exactly how your client proceeds is then determined by opaque links, not a predefined 'contract'.

That's not to say you should run away entirely from documentation, schema definition, etc, though theres an end of the RESTifarian spectrum that would suggest you can approach such a high level of self-description you don't need them. I've not found this to be the case in practice. A few solid worked examples should be all an unfamiliar developer needs. And knock up a few clients for your own API to try it out (easy enough from JQuery). That will give you a good indication whether you're building something consumable or not.

A good source of information in this area is the Hypertext Application Language. I find some of it a little heavyweight, but the debates on the mailing list are good and current and relevant.

Hope that helps you get started.


问:
What do you absolutely have to know about a candidate before hiring him?
What essential questions do you have to know the answer for, about a prospective software development candidate, before hiring him/her?

I'm not seeking specific interview problems (e.g. sort this 3D array of numbers in O(1) complexity), but simply for things you need to find about, for yourself, about a new hire. (e.g. which source control systems / languages / frameworks / OS has he used?)

Cross-posted to Quora

答:
you have to know if he has project experience in the field that you are hiring right now ; )
you also have to know if he is open to learning new things, and see that if he is excited about what you do. To understand this, you have to make him ask you about the stuff you are working on. </p>


问:
Programming with a group of people I've never met
I've been assigned a group project from my AP computer science class, and I am required to work with three other people. I've never talked to them before, I have no idea their skill level, and all I have is their email address. The assignment, summed up, is this:

"As a team you will complete a minimum of three Modules to a Class...."

I going to try and become "Team captain" because none of them have attempted to contact each other but I am curious: how to go about this? I've emailed them and asked them if there are any methods of communication they prefer over emailing each other, but once we actually start the project I'll have to figure out who is doing what.

What should I do? How do I "take charge" and lead three people that I've never met?

Here is an excerpt of the actual assignment:

Therefore you will need to discuss the various roles each team member
  will take in this project early in the week.  You can communicate via
  Pronto (or Blackboard IM), email, a wiki, a google group, blog or any
  other method that you see fit. If a group member does not engage the
  group by the end of week let your instructor know and they will
  provide additional guidance.

  ...

  Also due at the end of a project will be a team evaluation in which you will rate each team members contribution to the completion of this project along with a suggested grade.

Edit: Many people suggested that I meet them in a coffee shop, or something like that. Only problem is, all of us are in different states. I also figured out one of them isn't allowed to use Facebook/Skype/twitter, so I have to resort to messaging them over yahoo messenger and emails.

答:
I have been in a similar position a few times as I am sure have a lot of people. The main thing though is to do your best to keep everyone content and happy, so I think it is good that you want to take on the task of team leader, however like someone mentioned above - this does need to be approached carefully as someone else may feel they should do the job instead.

I know you said that no one has taken it upon themselves to contact each other but sometimes these situations can be difficult for people, like you said you are working with people you have never met and it can be difficult to communicate etc.

I would begin with an email just addressing everyone and letting them know who you are how you feel the project should be addressed and make it known that you want to lead the project taking responsibility for setting roles, goal, deadlines, communication time, meetups (if wanted/desired) and project updates.

Although you can not completely influence other people you can keep track of who is doing what and who is not. Delegating jobs allows the work to be split up evenly or appropriately to people with different skill sets or levels.

This way if certain work is not being done you can take it upon yourself to divide the work between the people who are actually keen to work on it. This way you wont end up with a failed project at the end and you will have records of trying to communicate dates, times and all the relevant information you can show at the end if things go wrong. ALl things which keep you in the right if some people dont pull their weight.

In terms of tips:

I personally love a collaborative working environment found here: https://docs.google.com/

This allows you to share word documents, spreadsheets etc. It is a great way of collaboratively working. I cant stress how useful this is sometimes. I use it with some people I work with who aren't in the country at the moment.

Hope this helped someone, there are so many aspects of leading a project we could go on forever but it just depends on so many things. At least this is a tiny bit to help.


问:
Problems (such as maintenance) in development with unpopular language
I'm developing some application with clojure(lisp) alone in my team. It starts as small application. No problem. But as it's having features and extending the area, it's becoming important program.

I worried about maintenance or something. No one in my team knows clojure or lisp nor is interested in languages such as them.

So, isn't it wrong to do programming in unpopular languages? (for my own fun?) Should I use more popular languages? (at least such as python)

I'm sure if I leave the team, --not saying I'm leaving. :)-- no one would maintain it. This program will be destroyed and some will develop with other language.

I'm very enjoying developing with clojure though, I came across with that this might be not for my team.

What do you think about this? I think many programmers loving unpopular languages have been concerning similar issue.

答:
I'm sure if I leave the team, --not saying I'm leaving. :)-- no one would maintain it.

Possibly False.

If the program has value, and management sees the value, they will task someone with learning Clojure and maintaining it.

Happens all the time.

This program will be destroyed and some will develop with other language.

Always true. So why worry about it?

All programs must eventually be replaced.

OwnerDisplayName: Hybrid


答:
Adopting new languages or "stand alone" language by some task is an high risk in a project.

If that part of system have a problem or that part must be dismiss instead you must find a programmer who must learn the skills about that language. In both cases you lost a lot of time.

In some case this problem can be used to improve and diversify the skills of a team by future task.

Title: Problems (such as maintenance) in development with unpopular language

Body:
I'm developing some application with clojure(lisp) alone in my team. It starts as small application. No problem. But as it's having features and extending the area, it's becoming important program.

I worried about maintenance or something. No one in my team knows clojure or lisp nor is interested in languages such as them.

So, isn't it wrong to do programming in unpopular languages? (for my own fun?) Should I use more popular languages? (at least such as python)

I'm sure if I leave the team, --not saying I'm leaving. :)-- no one would maintain it. This program will be destroyed and some will develop with other language.

I'm very enjoying developing with clojure though, I came across with that this might be not for my team.

What do you think about this? I think many programmers loving unpopular languages have been concerning similar issue.


答: Whether or not the program is continued after your departure does not concern you in my view. You can use the programming language you to make something your boss likes, sounds pretty good to me. Worrying about continuation is something your boss should do.</p>


答:
I would list the following areas which are a must before recruiting a candidate.

Attitude to learn: During the course of the interview, you can assess the candidates’ attitude to learn new things with case based analysis.

Passion for Programming: When the developer has passion for his work, his ability to bring out quality code is greater and he would be a great value edition once he adapts to your project.

Practical Knowledge: If the developer is experienced, they must have more practical knowledge in solving problems than theoretical knowledge.

Good luck.

Title: What do you absolutely have to know about a candidate before hiring him?

Body:
What essential questions do you have to know the answer for, about a prospective software development candidate, before hiring him/her?

I'm not seeking specific interview problems (e.g. sort this 3D array of numbers in O(1) complexity), but simply for things you need to find about, for yourself, about a new hire. (e.g. which source control systems / languages / frameworks / OS has he used?)

Cross-posted to Quora


答: A degree is in my view quite unmistakeable. That shows that a candidate can finish something hard and persevere. In addition, you could give his references a ring, although they might be biased...</p>


问:
How should I include third-party models in my domain model?
I'm currently trying to design a little application using Domain Driven Design but I'm afraid I don't really get the concept yet. Let me try to explain this as clearly as possible.

```<code>public interface IMyDomainRepository
{
    void Add(IAnInterfaceFromAThirdParty element);
}
</code>```

The interface above is defined in my domain model and this will be used in a different project called ThirdPartyImplementionVersionX.

Now IAnInterfaceFromAThirdParty is not defined in my domain model but comes from my third party library.

I could create a class/interface in my domain model which implements the same properties and methods as the interface IAnInterfaceFromAThirdParty but this interface has 20 methods defined thus making it a difficult task to implement the same logic.

Is this the way to go or am I missing something?

答:
A third party component has its own model expressed in its own language. Moreover, generally the third party component addresses a general-purpose problem which is normally a portion of the more context-specific problem you are trying to solve.

The first thing to do is be aware that your model, and the third party one are different and form two separate bounded contexts. Once you've clarified that, you might choose the strategy you want to apply when dealing with the third party component:

Protect your model with an anti-corruption layer thus keeping your model physically separated from the third party, by putting an adapter-like structure in the middle. This allows for sophisticated modeling in your domain without compromising with the external model.

Adhere to the external model (the pattern here is known as conformist): not so much sophisticated modeling, but that might still be viable a conscious decision, in non-core portions of the system.

Don't try to do both: if you are looking for nice sophisticated modeling, you need to protect the borders of your domain, without leaking from external domains. In other words, the anti-corruption layer tends to be the preferred choice.

In the example you're bringing, this would probably end up in defining interfaces in terms of your domain language, and relying on the functionalities provided by the third-party component only at the implementation level.


答:
I'd say more power to you! Lisp is the Grandaddy of computer languages and is still relevant today; the fact that it is not so popular I think is due to the fact that it doesn't have the warm fluffy IDEs of C# and Java and the main compiler implementation in Windows only runs under Cygwin (yuk!). Development seems to take place in Emacs and I guess it plays better with Linux or a Mac.

This coding competition was won by a Lisp program in 2010: http://planetwars.aichallenge.org/

Way back in the day they could debug it live from about 100 million miles: http://www.flownet.com/gat/jpl-lisp.html

You are definitely waiving a maintenance red flag, but think of it as providing a learning opportunity for someone else. If you were using some nightmare language (like MUMPS) or some tedious language (like TCL) then I think questions should be asked. But I think you should be thought of as a guy trying to uphold the best of the old traditions :)


答:
I feel your pain, I would love to do more coding in functional programming (Haskell looks so fun!). I feel like I have only just scratched the surface because I have yet to use it in a business context.

I would strongly suggest against doing it though. If you program in a language only you know then only you will be able to support it. Unless you want to have to deal with every support issue (Even when you have other deadlines/priorities) then code in a language your team know and can support. What happens when something breaks while you are on holiday? What happens if you want to get promoted?

I would recommend you get at least one other team member on board with you. Show them some cool language features. With two people on board it becomes workable and you wont be loaded with all the support.


问:
Using XML field Vs. creating a table for unstable organization
I am in the middle of design an application to issue and store invoices for an organization. The problem is the organization is not stable at all. There are many types of invoices and they may increase and change.

First, I tried to use tables in my DAL, one table to store invoices, one for invoice fields, and one for invoice field values. The problem was, this way needs Reflection to detect fields later, and this may slow the application when invoice contains plenty items.

Second, I tried to keep core of invoice data as two tables: invoices and invoice items. Other fields are fully catchable from other tables. I mean, Business Layer should provide different results per invoice type. It should choose the right queries, and process the results according to the type of invoice. Two problems with this solution are:

I still have lots of join between other tables when I want to show
an invoice, for per invoice item. I should recalculate everything
every time for every invoice item.

What if the invoice items table doesn’t support a new type of
invoice? Then I probably should add a new table to store that kind of invoices items.

My client asked me to keep all data related to an invoice, they do
not want me to recalculate it every time. They want something like a
snapshot of related data at the time invoice is creating.

Now, what I’m think can I use the benefit of XML in table? I can save the invoice, with whatever fields as xml.

I can save the different version of their invoices.

On changes, I only update my Business.dll and no DAL change required.

Linq to XML is not slow.

What do you suggest?

答:
i would suggest you to stick XML for such highly unpredictable and unstructured architecture. A web based solution's to your problem can be seen at
http://www.oreillynet.com/xml/blog/2008/05/xrx_a_simple_elegant_disruptiv_1.html
this wouldn't be a plugin solution for you problem. but you can see in the above link how this problem can be tackled elegantly. this would definitely help you the architecture your database.</p>


问:
When calling a method should we use base.methodname and this.methodname?
In C#, with an inherited class set -- when calling a method should we use keywords 'base.methodname and this.methodname'... irrespective of whether it is a overridden method or not?

The code is likely to undergo changes in terms of logic and maybe some IF-ELSE like conditions may come in at a later date. So at that time, the developer has to be compelled to revisit each line of code and ensure that he/she makes the right choice of which method is being called --- base.methodname() or this.methodname() ELSE the .NET framework will call the DEFAULT (I think its base.methodname()) and the entire logic can go for a toss.

答:
this keyword : There is no hard and fast rule to apply this keyword as it is a personal preference but your code could get cluttered.

Pros and cons of using this keyword in C#

base keyword (re-usability) : There are already answers indicating the use of base. I would like to add a point.

Common functionality for all derived classes would come in the base class and you can call the base method followed by the specific implementation in the method in the derived class achieving re-usability.


答:
I would suggest that if you're explicitly calling a base method from a class in which that method is overridden, you have a serious problem with both logic and readability. base should really only appear where calling the base implementation of an overridden method from that overridden method.

Everywhere else, it should be this (if the method isn't overridden then it will go to the base class anyway) and there is nothing wrong with allowing the compiler to infer that.

Title: When calling a method should we use base.methodname and this.methodname?

Body:
In C#, with an inherited class set -- when calling a method should we use keywords 'base.methodname and this.methodname'... irrespective of whether it is a overridden method or not?

The code is likely to undergo changes in terms of logic and maybe some IF-ELSE like conditions may come in at a later date. So at that time, the developer has to be compelled to revisit each line of code and ensure that he/she makes the right choice of which method is being called --- base.methodname() or this.methodname() ELSE the .NET framework will call the DEFAULT (I think its base.methodname()) and the entire logic can go for a toss.


答:
Using the base keyword is not a question of preference, it's a question of correctness. If you want to call the base class implementation in overridden method, you have to use base. If you don't want to call that, you can't use base.

The this keyword, on the other hand, is a question of preference in most cases. I think it only unnecessarily clutters the code, so I don't use it if I don't have to. Where it's useful is if you have a method parameter with the same name as field (or property). I would use this in such case. But if I'm writing new code, I tend to use naming conventions that avoid this problem.


答:
First I would suggest using dynamic types (such as ExpendoObject) to represent the unstructured data in you business layer. This would mean less custom classes.

Second I would recommend using json instead of xml since it would take up much less space in the database/storage engine.

Thirdly, have you considered using a nosql storage solution for the invoices? It's much more suited to less structured data than normal sql.

Title: Using XML field Vs. creating a table for unstable organization

Body:
I am in the middle of design an application to issue and store invoices for an organization. The problem is the organization is not stable at all. There are many types of invoices and they may increase and change.

First, I tried to use tables in my DAL, one table to store invoices, one for invoice fields, and one for invoice field values. The problem was, this way needs Reflection to detect fields later, and this may slow the application when invoice contains plenty items.

Second, I tried to keep core of invoice data as two tables: invoices and invoice items. Other fields are fully catchable from other tables. I mean, Business Layer should provide different results per invoice type. It should choose the right queries, and process the results according to the type of invoice. Two problems with this solution are:

I still have lots of join between other tables when I want to show
an invoice, for per invoice item. I should recalculate everything
every time for every invoice item.

What if the invoice items table doesn’t support a new type of
invoice? Then I probably should add a new table to store that kind of invoices items.

My client asked me to keep all data related to an invoice, they do
not want me to recalculate it every time. They want something like a
snapshot of related data at the time invoice is creating.

Now, what I’m think can I use the benefit of XML in table? I can save the invoice, with whatever fields as xml.

I can save the different version of their invoices.

On changes, I only update my Business.dll and no DAL change required.

Linq to XML is not slow.

What do you suggest?


答:
When I am working with models from a third-party I usially create an Adapter and my own models. The Adapter should map the items from the third-party to my models.

The problem behind it is that a third-party-assemblie or something like that could allways change. What are you doing when you switch from a to b?!? CHanging all the lines where you have implemented the model from the third-party product?

Title: How should I include third-party models in my domain model?

Body:
I'm currently trying to design a little application using Domain Driven Design but I'm afraid I don't really get the concept yet. Let me try to explain this as clearly as possible.

```<code>public interface IMyDomainRepository
{
    void Add(IAnInterfaceFromAThirdParty element);
}
</code>```

The interface above is defined in my domain model and this will be used in a different project called ThirdPartyImplementionVersionX.

Now IAnInterfaceFromAThirdParty is not defined in my domain model but comes from my third party library.

I could create a class/interface in my domain model which implements the same properties and methods as the interface IAnInterfaceFromAThirdParty but this interface has 20 methods defined thus making it a difficult task to implement the same logic.

Is this the way to go or am I missing something?


答:
The state of REST interfaces as driven from anything other than an interactive browser isn't very good. HATEOAS is a nice principle, but it leads to interfaces that are very strongly people-oriented and it tends to lead to the burden of the user interface being put on the service developer (who is usually pretty busy making the service itself work).

WADL itself isn't too great; it doesn't really capture enough of the semantics of the service to make it possible to tool things up. Of course, this is a hard problem in general. WSDL rarely exposes enough information either, and that's had a lot more effort put into the problem (it's possible to attach enough information, but hardly anybody actually does so).

Yet it is telling that a colleague of mine has spent months working on a library that uses a REST interface to a service, and the WSDL-described interface to the same service[*] was tooled automatically to nearly the same quality in seconds; going the rest of the way was about a day of writing wrapping classes. My hunch (based on a limited sample size) is that you cannot get rid of all brittleness in a complex service because the semantics of the service will inevitably evolve over time, and that REST is better at driving interfaces for humans while SOAP is better for interface libraries (there's good WSDL/SOAP client tooling for almost all languages of note). Unless you've got the luxury of doing both, which one to focus on should depend on which set of clients you care about most.

I wouldn't put much effort into WADL, but if your REST framework will produce it for you (Apache CXF does this) then there's no particular reason to not provide it. Anyone who wants to tool off your code will want WSDL+SOAP.

[*] As the author of the service in question, I can say for sure that both interfaces supported the same operations — there was a common underlying abstract model — and in a “natural” style for both interface types. On the service side, it was definitely the case that some things were easier with REST and others with SOAP.

Title: Should I use WADL to describe my RESTful API?

Body:
I'm about to embark on a project that makes extensive use of a properly RESTful approach. That is, it uses HATEOAS and serves up resources in a manner that allows for general exploration by a client.

I would like to ensure that I provide a description of my endpoints in a manner that would allow client applications to be automatically generated in a wide variety of languages. I understand that for SOAP based web services I can use WSDL and that apparently there is WSDL2 that provides greater definition of the HTTP verbs in use with REST. However I see many articles swinging back and forth over it's utility.

So, should I use WADL to allow external code generators to quickly build a client for my web application or is there a better standard that is expected?


问:
Abstract methods vs instance variables for reusable objects
I have quite a bit of Java code that I'm re-working to be re-used.  The problem is that there are many pieces that are project specific so there are ends up being a higher level of coupling between the application project and the code base project.

Compare to following situations where we use a class that implements the use of abstract methods to get the resources out of the child class, and one where we simply declare instance variables.

Abstract methods:

```<code>public abstract class SuperBaseClass {

    public abstract int getNumberOne();
    public abstract String getStringOne();
    public abstract String getStringTwo();

    public printStuff() {
        Log.i("IntAndTwoStrings", String.format("%i %s and %s",
                            getNumberOne(), getStringOne(), getStringTwo()));
    }

}

public class ReusedAppClass extends SuperBaseClass {

    public int getNumberOne() {
        return 1;
    }
    public String getStringOne() {
        return "String1";
    }
    public String getStringTwo() {
        return "String2";
    }

    public ReusedAppClass() {
        printStuff();
    }

}
</code>```

Instance variables:

```<code>public class SuperBaseClass {

    protected int numberOne;
    protected String stringOne;
    protected String stringTwo;

    public printStuff() {
        //Possibly throw RuntimeExceptions if the app didnt set these
        Log.i("IntAndTwoStrings", String.format("%i %s and %s",
                            numberOne, stringOne, stringTwo));
    }

}

public class ReusedAppClass extends SuperBaseClass {

    public ReusedAppClass() {
        numberOne = 1;
        stringOne = "String1";
        stringTwo = "String2";
        printStuff();
    }

}
</code>```

Is there a trade-off? Is the abstract method situation overkill, or is this what abstract classes were created for?

答:
IMHO a better approach is to use composition and avoid inheritance altogether if it's just for the sake of customising some fields. You say "to get the resources out of the child class", so do it:

```<code>public class MyResources() {

private int numberOne;
private String stringOne;
private String stringTwo;

public int getNumberOne() {
    return numberOne;
}

public void setNumberOne(int numberOne) {
    this.numberOne = numberOne;
}

public String getStringOne() {
    return stringOne;
}

public void setStringOne(String stringOne) {
    this.stringOne = stringOne;
}

public String getStringTwo() {
    return stringTwo;
}

public void setStringTwo(String stringTwo) {
    this.stringTwo = stringTwo;
}
}
</code>```

Then instantiate MyResources objects in your classes and customise them as required.
If you still need to have a hierarchy of classes you can have your resource object in the base class and inherit it in the child classes:

```<code>public abstract class SuperBaseClass {

protected MyResources resources;

public SuperBaseClass() {
    resources.setStringOne("Hello");
}

public class ReusedAppClass extends SuperBaseClass {

public ReusedAppClass () {
    super();
    resources.setStringOne("Hi");
}
}
</code>```

Body:
IMHO a better approach is to use composition and avoid inheritance altogether if it's just for the sake of customising some fields. You say "to get the resources out of the child class", so do it:

public class MyResources() {

private int numberOne;
private String stringOne;
private String stringTwo;

public int getNumberOne() {
    return numberOne;
}

public void setNumberOne(int numberOne) {
    this.numberOne = numberOne;
}

public String getStringOne() {
    return stringOne;
}

public void setStringOne(String stringOne) {
    this.stringOne = stringOne;
}

public String getStringTwo() {
    return stringTwo;
}

public void setStringTwo(String stringTwo) {
    this.stringTwo = stringTwo;
}
}

Then instantiate MyResources objects in your classes and customise them as required.
If you still need to have a hierarchy of classes you can have your resource object in the base class and inherit it in the child classes:

public abstract class SuperBaseClass {

protected MyResources resources;

public SuperBaseClass() {
    resources.setStringOne("Hello");
}

public class ReusedAppClass extends SuperBaseClass {

public ReusedAppClass () {
    super();
    resources.setStringOne("Hi");
}
}


答:
At one job, I had a recurring dream that my model soldiers were going to show up and rescue me, despite their size and the fact that they were lifeless metal.

At another job, I got into trouble for following standard promotion procedure from development to test to production, as somebody else had, with management approval, hacked the production system directly without making sure to keep a backup.

Both were good signs that I needed to get out of there.

Title: When do you know it's time to move on from your current job?

Body:
Have you ever reached a point at your job when you just know it's time to move on?

When do you move to the point that you're willing to let go of the demons you know for the ones you don't know?

What was your deciding factor final straw so to speak when you finally faced the decision to find a new job?


问:
What's the best way to build a factory using NInject?
I am pretty comfortable with dependency injection using NInject in MVC3. While working in an MVC3 application, I developed a custom Controller Creation Factory using NInject, so any controller that is created will have dependencies injected in it through this Controller Factory.

Now I am starting to develop a windows application, I want to use Application wide Dependency Injection. i.e. Every object must be created through NInject, so as to ease Unit Testing. Please guide me to ensure that every object created must be though the NInject Factory only.

For example, if on any windows form on Button_Click event I write:

```<code>TestClass testClass = new TestClass()
</code>```

and TestClass has any dependency on, say, ITest then it must be automatically resolved. I know I can use:

```<code>Ikernel kernel = new StandardKenel()
//AddBinding()
TestClass testClass = kenel.get<TestClass>();
</code>```

But I find it tedious to do this every time I want to create an object. It also the forces developer to create the object in a particular way. Can it be made better?

Can I have a central repository for object creation and then every object creation will automatically use that repository?

答:
Good use of Dependency Injection usually relies on seperating the code which creates objects and the actual business logic. In other words, I would not want my team to frequently use new and create an instance of a class that way. Once it is done, there is no way to easily swap out that created type for another, since you have already specified the concrete type.

So there are two ways to go about fixing this:

Inject the instances that a class will need. In your example, inject a TestClass into your Windows Form so that it already has an instance when it needs it. When Ninject instantiates your form, it automatically creates the dependency.

In cases where you really don't want to create an instance until you need it, you can inject a factory into the business logic. For example, you can inject an IKernel into your Windows Form, and then use that to instantiate TestClass. Depending on your style, there are other ways to accomplish this as well (injecting a factory class, factory delegate, etc).

Doing this makes it easy to swap out both the concrete type of TestClass, as well as modify the actual construction of the test class, without actually modifying the code which uses the test class.


答:
I always write an Adapter wrapper for any IoC Container, which looks like this:

public static class Ioc
{
    public static IIocContainer Container { get; set; }
}

public interface IIocContainer
{
    object Get(Type type);
    T Get<T>();
    T Get<T>(string name, string value);
    void Inject(object item);
    T TryGet<T>();
}
```

<p>For Ninject, specifically, the concrete Adapter class looks like this:</p>

<pre class="lang-cs prettyprint-override"><code>public class NinjectIocContainer : IIocContainer
{
    public readonly IKernel Kernel;
    public NinjectIocContainer(params INinjectModule[] modules)
    {
        Kernel = new StandardKernel(modules);
        new AutoWirePropertyHeuristic(Kernel);
    }

    private NinjectIocContainer()
    {
        Kernel = new StandardKernel();
        Kernel.Load(AppDomain.CurrentDomain.GetAssemblies());

        new AutoWirePropertyHeuristic(Kernel);
    }

    public object Get(Type type)
    {
        try
        {
            return Kernel.Get(type);
        }
        catch (ActivationException exception)
        {
            throw new TypeNotResolvedException(exception);
        }
    }

    public T TryGet<T>()
    {
        return Kernel.TryGet<T>();
    }

    public T Get<T>()
    {
        try
        {
            return Kernel.Get<T>();
        }
        catch (ActivationException exception)
        {
            throw new TypeNotResolvedException(exception);
        }
    }

    public T Get<T>(string name, string value)
    {
        var result = Kernel.TryGet<T>(metadata => metadata.Has(name) &&
                     (string.Equals(metadata.Get<string>(name), value,
                                    StringComparison.InvariantCultureIgnoreCase)));

        if (Equals(result, default(T))) throw new TypeNotResolvedException(null);
            return result;
    }

    public void Inject(object item)
    {
        Kernel.Inject(item);
    }
}
</code>```

The primary reason for doing this is to abstract out the IoC framework, so I can replace it at any time -- given that the difference between frameworks is generally in configuration rather than in usage.

But, as a bonus, things also become a lot easier for using the IoC framework inside other frameworks that don't inherantly support it. For WinForms, for example, it is two steps:

In your Main method, simply instantiate a container before doing anything else.

static class Program
{
    ///
    /// The main entry point for the application.
    ///
    [STAThread]
    static void Main()
    {
        try
        {
            Ioc.Container = new NinjectIocContainer( /* include modules here */ );
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MyStartupForm());
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
}
```

<p>And then have a base Form, from which other forms derive, which calls Inject on itself.</p>

<pre class="lang-cs prettyprint-override"><code>public IocForm : Form
{
    public IocForm() : base()
    {
        Ioc.Container.Inject(this);
    }
}
</code>```

This tells the auto-wiring heuristic to attempt to recursively inject all properties in the form which fit the rules set up in your modules.

Title: What's the best way to build a factory using NInject?

Body:
I am pretty comfortable with dependency injection using NInject in MVC3. While working in an MVC3 application, I developed a custom Controller Creation Factory using NInject, so any controller that is created will have dependencies injected in it through this Controller Factory.

Now I am starting to develop a windows application, I want to use Application wide Dependency Injection. i.e. Every object must be created through NInject, so as to ease Unit Testing. Please guide me to ensure that every object created must be though the NInject Factory only.

For example, if on any windows form on Button_Click event I write:

```<code>TestClass testClass = new TestClass()
</code>```

and TestClass has any dependency on, say, ITest then it must be automatically resolved. I know I can use:

```<code>Ikernel kernel = new StandardKenel()
//AddBinding()
TestClass testClass = kenel.get<TestClass>();
</code>```

But I find it tedious to do this every time I want to create an object. It also the forces developer to create the object in a particular way. Can it be made better?

Can I have a central repository for object creation and then every object creation will automatically use that repository?

Body:
I always write an Adapter wrapper for any IoC Container, which looks like this:

public static class Ioc
{
    public static IIocContainer Container { get; set; }
}

public interface IIocContainer
{
    object Get(Type type);
    T Get<T>();
    T Get<T>(string name, string value);
    void Inject(object item);
    T TryGet<T>();
}

For Ninject, specifically, the concrete Adapter class looks like this:

public class NinjectIocContainer : IIocContainer
{
    public readonly IKernel Kernel;
    public NinjectIocContainer(params INinjectModule[] modules)
    {
        Kernel = new StandardKernel(modules);
        new AutoWirePropertyHeuristic(Kernel);
    }

    private NinjectIocContainer()
    {
        Kernel = new StandardKernel();
        Kernel.Load(AppDomain.CurrentDomain.GetAssemblies());

        new AutoWirePropertyHeuristic(Kernel);
    }

    public object Get(Type type)
    {
        try
        {
            return Kernel.Get(type);
        }
        catch (ActivationException exception)
        {
            throw new TypeNotResolvedException(exception);
        }
    }

    public T TryGet<T>()
    {
        return Kernel.TryGet<T>();
    }

    public T Get<T>()
    {
        try
        {
            return Kernel.Get<T>();
        }
        catch (ActivationException exception)
        {
            throw new TypeNotResolvedException(exception);
        }
    }

    public T Get<T>(string name, string value)
    {
        var result = Kernel.TryGet<T>(metadata => metadata.Has(name) &&
                     (string.Equals(metadata.Get<string>(name), value,
                                    StringComparison.InvariantCultureIgnoreCase)));

        if (Equals(result, default(T))) throw new TypeNotResolvedException(null);
            return result;
    }

    public void Inject(object item)
    {
        Kernel.Inject(item);
    }
}

The primary reason for doing this is to abstract out the IoC framework, so I can replace it at any time -- given that the difference between frameworks is generally in configuration rather than in usage.

But, as a bonus, things also become a lot easier for using the IoC framework inside other frameworks that don't inherantly support it. For WinForms, for example, it is two steps:

In your Main method, simply instantiate a container before doing anything else.

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        try
        {
            Ioc.Container = new NinjectIocContainer( /* include modules here */ );
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MyStartupForm());
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
}

And then have a base Form, from which other forms derive, which calls Inject on itself.

public IocForm : Form
{
    public IocForm() : base()
    {
        Ioc.Container.Inject(this);
    }
}

This tells the auto-wiring heuristic to attempt to recursively inject all properties in the form which fit the rules set up in your modules.


问:
How can I properly compare double values for equality in a unit test?
I recently designed a time series module where my time series is essentially a SortedDictionnary<DateTime, double>.

Now I would like to create unit tests to make sure that this module is always working and producing the expected result.

A common operation is to compute the performance between the points in the time series.

So what I do is create a time series with, say, {1.0, 2.0, 4.0} (at some dates), and I expect the result to be {100%, 100%}.

The thing is, if I manually create a time series with the values {1.0, 1.0} and I check for equality (by comparing each point), the test would not pass, as there will always be inaccuracies when working with binary representations of real numbers.

Hence, I decided to create the following function:

private static bool isCloseEnough(double expected, double actual, double tolerance=0.002)
{
    return squaredDifference(expected, actual) < Math.Pow(tolerance,2);
}
```

Is there another common way of dealing with such a case?

答:
I can think of two other ways to deal with this problem:

You can use Is.InRange:

```<code>Assert.That(result, Is.InRange(expected-tolerance, expected+tolerance));
</code>```

You can use Math.Round:

```<code>Assert.That(Math.Round(result, sigDigits), Is.EqualTo(expected));
</code>```

I think that both ways are more expressive than a dedicated function, because the reader can see precisely what's going on with your number before it gets compared to the expected value.

Body:
I can think of two other ways to deal with this problem:

You can use Is.InRange:

Assert.That(result, Is.InRange(expected-tolerance, expected+tolerance));

You can use Math.Round:

Assert.That(Math.Round(result, sigDigits), Is.EqualTo(expected));

I think that both ways are more expressive than a dedicated function, because the reader can see precisely what's going on with your number before it gets compared to the expected value.


问:
How should I handle exposing Java beans to end users?
I need to create some Java interfaces to query some database tables and some web services for new framework I'm building. In a previous Java Spring web application, I used Java Beans to handle the results of the query.

In this case, I need to write some interfaces to publish the methods that will be available to end users. I'm a little bit of a newbie in this particular aspect of Java and I was wondering: is it better to allow the end user to see and use the Java beans in JSP, or to hide them using some generic type?

答: It's okay to use those Java beans (which I'll call domain objects) to hold the results for a query. Then if you need to return them as a web service, you'll use the service to convert those objects to JSON or the desired format.</p>


问:
Maintainability of Boolean logic - Is nesting if statements needed?
Which of these is better for maintainability?

```<code>if (byteArrayVariable != null)
    if (byteArrayVariable .Length != 0)
         //Do something with byteArrayVariable
</code>```

OR

```<code>if ((byteArrayVariable != null) && (byteArrayVariable.Length != 0))
  //Do something with byteArrayVariable
</code>```

I prefer reading and writing the second, but I recall reading in code complete that doing things like that is bad for maintainability.

This is because you are relying on the language to not evaluate the second part of the if if the first part is false and not all languages do that.  (The second part will throw an exception if evaluated with a null byteArrayVariable.)

I don't know if that is really something to worry about or not, and I would like general feedback on the question.

Thanks.

答: The second form is more readable, especially if you are using {} blocks around each clause, because the first form will lead to nested {} blocks and multiple levels of indentation, which can be a pain to read (you have to count indentation spaces to figure out where each block ends).</p>


问:
Javascript client - which is likely to be better serverside? WCF or MVC3 controller with restful messages?
I'm looking to write a server side service, which will be accessed from a Javascript/HTML5 client.

The client will likely be sending a bunch of restful messages over HTTPS.

All other things being equal, which is better designed to support this kind of scheme on the serverside - WCF or MVC3 (ie., a controller with only restful messages, no real view or model)?

答:
Do you anticipate needing to support other clients down the road? For instance SOAP, message queue, TCP/IP?  WCF has a strong interoperability story here.

Personally, I like working with Data Contracts and Service Contracts, and love the flexibility of being able to do one way asynchronous architecture when I want durability or scalability one day and use RESTlike HTTP the next day while still maintaining compatibility with SOAP clients.


答: As RichardM suggested, if you do not use NUnit, the best way seems to be using Assert.AreEqual(double,double,double), where the last one is the precision.</p>

Title: How can I properly compare double values for equality in a unit test?

Body:
I recently designed a time series module where my time series is essentially a SortedDictionnary<DateTime, double>.

Now I would like to create unit tests to make sure that this module is always working and producing the expected result.

A common operation is to compute the performance between the points in the time series.

So what I do is create a time series with, say, {1.0, 2.0, 4.0} (at some dates), and I expect the result to be {100%, 100%}.

The thing is, if I manually create a time series with the values {1.0, 1.0} and I check for equality (by comparing each point), the test would not pass, as there will always be inaccuracies when working with binary representations of real numbers.

Hence, I decided to create the following function:

private static bool isCloseEnough(double expected, double actual, double tolerance=0.002)
{
    return squaredDifference(expected, actual) < Math.Pow(tolerance,2);
}
```

Is there another common way of dealing with such a case?


答: Abstract class approach also forces the extending class to "initialize" the variables whereas with the protected instance variables the defaults could easily be used leading to confusion/bugs if not extended.</p>

Title: Abstract methods vs instance variables for reusable objects

Body:
I have quite a bit of Java code that I'm re-working to be re-used.  The problem is that there are many pieces that are project specific so there are ends up being a higher level of coupling between the application project and the code base project.

Compare to following situations where we use a class that implements the use of abstract methods to get the resources out of the child class, and one where we simply declare instance variables.

Abstract methods:

```<code>public abstract class SuperBaseClass {

    public abstract int getNumberOne();
    public abstract String getStringOne();
    public abstract String getStringTwo();

    public printStuff() {
        Log.i("IntAndTwoStrings", String.format("%i %s and %s",
                            getNumberOne(), getStringOne(), getStringTwo()));
    }

}

public class ReusedAppClass extends SuperBaseClass {

    public int getNumberOne() {
        return 1;
    }
    public String getStringOne() {
        return "String1";
    }
    public String getStringTwo() {
        return "String2";
    }

    public ReusedAppClass() {
        printStuff();
    }

}
</code>```

Instance variables:

```<code>public class SuperBaseClass {

    protected int numberOne;
    protected String stringOne;
    protected String stringTwo;

    public printStuff() {
        //Possibly throw RuntimeExceptions if the app didnt set these
        Log.i("IntAndTwoStrings", String.format("%i %s and %s",
                            numberOne, stringOne, stringTwo));
    }

}

public class ReusedAppClass extends SuperBaseClass {

    public ReusedAppClass() {
        numberOne = 1;
        stringOne = "String1";
        stringTwo = "String2";
        printStuff();
    }

}
</code>```

Is there a trade-off? Is the abstract method situation overkill, or is this what abstract classes were created for?


答:
There are lot of good answers but I would like to add a point.

I have been in similar situation but with a different language. I had to learn everything the hard way i.e through trial and error method due to lack of guidance. What I learnt' from my experience as you pointed out maintenance / extensibility would become an issue as one might not be knowing effective approaches due to lack of guidance.

I suggest you talk to your manager for adequate help so that you can avoid any issues in the future.

Good luck!


问:
How to optimize methodology to collect Market Data?
I am working on Application which goes and get's market data from different sources, I am using polling mechanism where vendor/broker put his data file and my application would go and hit that ftp location multiple times during the day to get data.

Right now, we hit location every 5 mins and if data is not there then again after 5 mins. In it's current software architecture system using lot of resources between time window of 3 hrs where we do this polling mechanism.

I want to improve performance of application and so what would best practices to solve this kind of software problem?

Note:

Some might say that this problem is engineering and should not be post here but my target audience is software guys working in finance and so i have posted this question here, if you feel that this is not right location for this then please feel free to migrate it to stackoverflow or programmers.stackexchange.com

答:
If you cannot have the information "pushed" to you, you have to build your own "push".

That is, you should have one application that does your FTP polling and the other, not directly connected to the first one, that retrieves the new data and treats it. Your second application should "subscribe" to the first one in order to receive a notification for the availability of a new file. This way, you should use very few resources since your main application will only launch/work when receiving a notification. Disconnecting into at least two applications is also more flexible since with the notifier/subscriber architecture any other new application you write would only need to subscribe to your polling service to be  able to work with it.

Also, to use even less resources, you can poll with an increasing time frame. For example, let's say your polling time frame is between a minimum of 2 and 10 minutes. You start with 2 minutes. If the polling application does not find a new file, the time is increased by 1 minute, until you reach a maximum of 10 minutes. If the polling application finds a new file, the time is set back to 2 minutes. You can even imagine a decreasing time frame...

Finally, to improve your architecture even more, you can even break the problem into 3 applications: one for the polling, one for retrieving the data and storing it somewhere (like a cache), and another application that treats the data (and therefore has no relationship whatsoever with the "source" of the data, be it FTP, HTTP, or a web service)

Edit: below, an example of an architecture based on web applications and web services for my first proposal (two applications).

The Poller Service can be a web application composed of:

One Web Service composed of two methods:

Subscribe for allowing a client application/web service to register for receiving
information that a new file is available. One of the parameters of this web method should be  the HTTP address where this "client" could be reached at.

Unsubscribe for not receiving anything anymore.

One service triggered every x minutes for polling an FTP for new files. When a new file is found, the service calls every subscribed "client" Web Service's NewFile web method (which I describe right below)

Now, a client application can be really anything but it should have a web service facade with at least the following web method:

NewFile, for allowing the poller to push the information on the availability of the new file. Within this web method the poller may also send some more information on the file such as the size, when it was modified and of course its exact location.

When this application starts, it calls the Subscribe method of the Poller web service.

When this application exits, it calls the Unsubscribe method of the Poller web service.

Edit: you asked how it would be with REST services.

Well, the definitions of the services do not change. The Subscribe REST service should receive an URL that is in fact the location of the NewFile REST service on the client web application. As for how the services should be written:

the Subscribe and Unsubscribe on the server web application should probably accept respectively POST and DELETE HTTP requests (for both I guess POST would work too).

the NewFile REST service on the client web application should accept POST HTTP requests.

When a new file is detected, the server web application posts the location of the file to each URL that has been registered as an active NewFile compatible REST service. That's it.

OwnerDisplayName: Rachel


答: It depends what you do with the numbers. If you are testing a method which is supposed to e.g. select an appropriate value from an input set based on some criteria, then you should test for strict equality. If you're doing floating-point calculations, usually you will need to test with a non-zero tolerance. How big the tolerance is depends on the calculations, but with double precision a good starting point is to choose 1E-14 relative tolerance for simple calculations and 1E-8 (tolerance) for more complicated ones. YMMV of course, and you need to add some small absolute tolerance if the expected result is 0.


答:
If the use case is pretty simple and you've already got to support a MVC site then I think MVC is a pretty good choice. I'd also generally agree that standard WCF is perhaps a bit too much ceremony and boilerplate and difficult to IoC in a sane and rational manner.

All that said, you might want to check out the WCF Web API. It is pretty simple to implement at first, plays well with your existing MVC site while also having some pretty powerful message handling facilities. Your typical MVC controllers start to fall down a bit -- or at least the level of complexity increases dramatically -- when you get into stuff like ETags, cache hinting and such. The Web API bridges that gap nicely and it is definitely worth checking out.

Title: Javascript client - which is likely to be better serverside? WCF or MVC3 controller with restful messages?

Body:
I'm looking to write a server side service, which will be accessed from a Javascript/HTML5 client.

The client will likely be sending a bunch of restful messages over HTTPS.

All other things being equal, which is better designed to support this kind of scheme on the serverside - WCF or MVC3 (ie., a controller with only restful messages, no real view or model)?


答:
For client applications, it's often best to adapt a pattern like MVP (or MVVM) and use data-binding from the form to the underlying ViewModel or Presenter.

For the ViewModels, you can inject the required dependencies using standard Constructor Injection.

In your application's Composition Root you can wire up the entire object graph for your application. You don't need to use a DI Container (such as Ninject) for this, but you can.


答:
Don't worry, be happy.

Clearly the program has value, or you wouldn't be extending it.  Congratulations on a successful project.  Presumably you chose Clojure because doing so saved time and hence saved your employer money.  If you had written it in Java, the program would be therefore be even more difficult to maintain.  Even if your colleagues could more easily understand the program line-by-line, would they be able to maintain it and extend it?


答:
You sound like you want what is known as a Service Repository or a Service Registry.  The following diagram I found on Wikipedia.

I have seen where a Service Repository had its own web service interface where one would request what kinds of web services and where the WSDL's are from a given component.  The WSDL specifically will define what operations exist for the given service.

For more information on SOA, see Wikipedia.

Title: How should I handle exposing Java beans to end users?

Body:
I need to create some Java interfaces to query some database tables and some web services for new framework I'm building. In a previous Java Spring web application, I used Java Beans to handle the results of the query.

In this case, I need to write some interfaces to publish the methods that will be available to end users. I'm a little bit of a newbie in this particular aspect of Java and I was wondering: is it better to allow the end user to see and use the Java beans in JSP, or to hide them using some generic type?


问:
What legal considerations do I need to have when programming?
Recently I worked with a group to create a logging system for tutoring labs to track Tutor hours, and usage of the labs. We had to change the design a fair amount to be in compliance with FERPA. </p>

<p>My question stems from the curiosity that in my course of study there has never been a real mention of how people in this field have to deal with complying with the law in their work. So I would like to know how much programmers have to consider the law in the work they do. </p>

答: One Sarbanes-Oxley control I'm familliar with is the requirement where no developer is permitted to deploy into production... only a System Administrator may deploy binaries.</p>


问:
Regulation of the software industry
Every few years someone proposes tighter regulation for the software industry.

This IEEE article has been getting some attention lately on the subject.

If software engineers who write programs for systems that expose the public to physical or financial risk knew they would be tested on their competence, the thinking goes, it would reduce the flaws and failures in code—and maybe save a few lives in the bargain.

I'm skeptical about the value and merit of this. To my mind it looks like a land grab by those that proposed it.

The quote that clinches that for me is:

The exam will test for basic knowledge, not mastery of subject matter

because the big failures (e.g. THERAC-25) seem to be complex, subtle issues that "basic knowledge" would never be sufficient to prevent.

Ignoring any local issues (such as existing protections of the title Engineer in some jurisdictions):

The aims are noble - avoid the quacks/charlatans1 and make that distinction more obvious to those that buy their software. Can tighter regulation of the software industry ever achieve it's original goal?

1 Exactly as regulation of the medical profession was intended to do.

答:
One can never eliminate the charlatans and quacks completely because they exist in nearly every profession, even medical professions despite the long established practices and traditions.

On this statement being a land grab though, I am not sure what dark scary overlord of all things IT is diabolically plotting his unfettered control and regulation of software development.  If you are in fact talking about the IEEE they certainly have a regulatory aspect but compliance with IEEE standards is more or less at will, and not at gunpoint.  They are trying to develop universal industry standards so that we all talk the same language and increase efficiency across the board.

Further the standards that they lay out help legitimize common practices and lay the ground work for software development to eventually become a more disciplined field of engineering, not unlike mechanical engineering, or chemical engineering.  While software is getting closer to that goal, it will likely never completely be a universally accepted as an engineering discipline.

The core problem is that a software developer could be doing anything from writing a pretty desktop widget, to implementing missle guidance systems.  In one the severity and consequence of error is much higher than the other, and thus demands a strictly regulated engineering discipline to approach reasonably, safely, and efficiently.  This is much like the severity of error in a bridge being designed incorrectly and having it collapse as a result.  The designers of the bridge must be abiding my engineering standards to ensure quality.

Title: Regulation of the software industry


答:
In 1999, the ACM issued a statement on licensing when it largely pulled out of the IEEE SWEBOK work. After reviewing the publicly available SWEBOK documents and the ACM statement, I support the ACM's opinion.

Glancing at the article, someone with 4-6 years of experience is required to take the exam, which tests for basic knowledge. That's beyond ridiculous, and should be laughed out the door.

Title: Regulation of the software industry

Body:
Every few years someone proposes tighter regulation for the software industry.

This IEEE article has been getting some attention lately on the subject.

If software engineers who write programs for systems that expose the public to physical or financial risk knew they would be tested on their competence, the thinking goes, it would reduce the flaws and failures in code—and maybe save a few lives in the bargain.

I'm skeptical about the value and merit of this. To my mind it looks like a land grab by those that proposed it.

The quote that clinches that for me is:

The exam will test for basic knowledge, not mastery of subject matter

because the big failures (e.g. THERAC-25) seem to be complex, subtle issues that "basic knowledge" would never be sufficient to prevent.

Ignoring any local issues (such as existing protections of the title Engineer in some jurisdictions):

The aims are noble - avoid the quacks/charlatans1 and make that distinction more obvious to those that buy their software. Can tighter regulation of the software industry ever achieve it's original goal?

1 Exactly as regulation of the medical profession was intended to do.


答:
History has shown, aptly I believe, that the difference between an excellent craftsman and a mediocre one cannot be tested with any form of objective measure. Basic knowledge does not make a great programmer, wisdom and experience--which cannot really be taught or measured objectively--  of how to apply that basic knowledge does.

Also, these tests usually just end up being a few buzz words and concrete procedures and fail to measure anything substantive to begin with.

If the software industry wanted to develop a guild of some sort, that would be a much better way to approach the issue. However, centralization only has the power to destroy excellence: not create it.

In addition, the problems that this measure is trying to prevent would probably not be caught by a test anyhow. Anyways, I also would love to see @ThomasOwens answer this one.

What would be the government's role, at least from American ideology, would be to hold software companies responsible for any property damage caused by their defective or insecure software. This would encourage the companies to enforce their own standards and to take personal responsibility for the matter. This is always a better solution, and it doesn't contain a centralized government overstepping its bounds.

Update

I was thinking about this some more last night over a beer or ten.

All that regulating the medical field did was to exterminate all paradigms but one.
If their goal was to weed out homeopathic and naturopathic doctors, whom the o.p. kindly referred to as "quacks" then such regulation was successful. However, I disagree that such a thing is profitable for anyone except the people writing the legislation. Think about what this has done. It has driven up the cost of health care to unsustainable levels, greatly increased the liability levels for M.D.s , and has removed all of the consumer's power of choice and self-determination from the marketplace. There is no more marketplace for ideas in the medical community, and new treatments and ways of thinking about medicine are now suppressed. Furthermore, the barrier for entry into the field is incredibly high and as a result, we have a shortage of good M.D.s.  In addition, the regulating agencies have the power to control the supply of doctors so that they can in turn control the price that doctors are paid.

There are indeed some gains that we have received from the medical regulation, but the costs are entirely too high.

This same thing will happen to software engineers if such regulation is passed. I can see it now, the regulating agencies will rule that object-oriented programming is the only standard of design and the functional and procedural programmers will not be allowed to practice. Then they will start telling us that we are not allowed to manage our own memory because it isn't safe. Then they will cram JAVA and C# down all of our throats and tell us we have to use it while Oracle and Microsoft get fatter and happier. Innovation will be stifled and creativity will be outlawed. Microsoft and Google will write the legislation, so the rules of the market will be bent towards their own profitability and against the social well-being.

Also, let me remind everyone that computers started out as a hobbyist and Academic endeavor. Other than the Unix wars of the 80's and early 90's we have had free operating systems, free compilers, free programs, and so on... This would come to an end quickly. The world that Richard Stallman, Linus Torvalds, and Dennis Richtie bequeathed to us will gradually fade from existence.

In summary, do I get tired of having to compete with "I'll design you a wordpress CMS site for $25 per hour" or the "any iPhone app for $500" guys? Not really, why? Because I am damn good at what I do and the customers that I want are willing to pay for excellence. When I take on a project independently or at my place of employment, I take the risk of my f*&^ ups upon my own head and reputation. That will follow me wherever I go. Also, most people know that they get what they pay for. A customer who is only willing to pay me the price that they pay their lawn guy is going to be a nightmare to deal with anyways. If the government fixed the legal structure to force service providers to compensate for their damages, then there would be very few bad programmers that still had employment in the field.

By the way, we still have bad doctors, the only difference is that there are very few forces to remove them from the market. If they had to take responsibility for their own actions, they would be out of business before they had another chance to wreak incompetent havoc upon their customers.

Title: Regulation of the software industry


答:
I've not used Ninject, but the standard way of creating stuff when you are using a IoC is to do so via a Func<T> where T is the type of object you want to create. So if object T1 needs to create objects of type T2 then the constructor of T1 must have parameter of type Func<T1> which is then stored as a field / property of T2. Now when you want to create objects of type T2 in T1 you invoke the Func.

This totally decouples you from your IoC framework and is the right way to code in an IoC mindset.

The downside to doing this is that it can get annoying when you need to manually wire Funcs or example when your creator requires some parameter, so the IoC cannot autowire the Func for you.

http://code.google.com/p/autofac/wiki/RelationshipTypes


答: I would definitely have them access your beans via interface types, to give you flexibility on the back end.  It also provides more complete separation, as your UI code only depends on the interfaces (which can be kept in a separate jar file), not any particular implementation code.  Plus, you can re-use front end code more easily.  E.g., if you've got an address maintenance page, you can use it for anything that supports the IUpdatableAddress interface, regardless of whether it's a Person, Organization or Event.  As long as you don't display or invoke anything that isn't part of the interface, you'll be fine.


答:
If government regulations are passed, the software industry in the USA will contract significantly, because the cost associated with meeting those regulations will be higher than startups and small businesses can afford.

The scarcity and cost associated with a Law degree or a Doctor of Medicine will become more or less visible in our industry.  Not good when the alternative is that every joe could potentially build the next Facebook.

People make mistakes, and no amount of regulation will prevent disasters from occurring.  Consider NASA, which has by far the most stringent requirements for software development known to man.  Do they still have software bugs? (Yes, yes, and many times, yes!)

The marketplace sorts out these problems a lot better than regulations can.  Companies that create software that causes problems are held responsible by the people they injured.  The rest of us need not pay for their mistakes.

Title: Regulation of the software industry


答:
The software components of a device are an implementation detail.  For instance, in the control systems industry, all safety devices used to be hardwired, and people didn't trust software.  However, we are now seeing software-based safety devices like Safety Relays and Safety PLCs.  These are permissible because they still have to meet the industry regulations for safety devices (depending on the safety category).  Therefore, in some cases the devices need redundant processors, and redundant code written by two different teams, etc.

It's the product that needs to meet safety guidelines if it's to be sold to and consumed by the public.  Those rules don't change because the product contains software.  It's the Engineer's job to make sure that the product meets all regulatory criteria, and if it contains software, then they have to review the software and be competent in that field.  If they're not, they (or their company) is liable if they approved the design and it turns out to be faulty.

You don't really need to regulate all programmers just because some products need to live up to more stringent requirements.  In the cases where such products involve software, you need a well-developed engineering discipline that can reliably determine that the software component meets the requirements.  If anything, that's what the IEEE means: the relatively young field of Software Engineering needs to be developed to the level of reliability and trust of other engineering disciplines.

It really has nothing to do with "programming" and everything to do with "engineering".

This, of course, brings us back to the contentious issue of the difference between a developer and and engineer.  These are generally two different roles that regularly overlap.  The developer part means you make software.  The engineering part of the role means if you stamp the design you're taking responsibility for public safety.  You can be one without the other.

Title: Regulation of the software industry