答:
Do nothing.

Contacting someone purely to tell them they screwed up but we fixed it, is unprofessional and no matter how hard you try is unlikely to ever be received positively.

Talking in depth enough for a conversation to be remotely useful about code to non employees is bad regardless of potential NDA issues.


问:
Should a server "be lenient" in what it accepts and "discard faulty input silently"?
I was under the impression that by now everyone agrees this maxim was a mistake. But I recently saw this answer which has a "be lenient" comment upvoted 137 times (as of today).

In my opinion, the leniency in what browsers accept was the direct cause of the utter mess that HTML and some other web standards were a few years ago, and have only recently begun to properly crystallize out of that mess. The way I see it, being lenient in what you accept will lead to this.

The second part of the maxim is "discard faulty input silently, without returning an error message unless this is required by the specification", and this feels borderline offensive. Any programmer who has banged their head on the wall when something fails silently will know what I mean.

So, am I completely wrong about this? Should my program be lenient in what it accepts and swallow errors silently? Or am I mis-interpreting what this is supposed to mean?

The original question said "program", and I take everyone's point about that. It can make sense for programs to be lenient. What I really meant, however, is APIs: interfaces exposed to other programs, rather than people. HTTP is an example. The protocol is an interface that only other programs use. People never directly provide the dates that go into headers like "If-Modified-Since".

So, the question is: should the server implementing a standard be lenient and allow dates in several other formats, in addition to the one that's actually required by the standard? I believe the "be lenient" is supposed to apply to this situation, rather than human interfaces.

If the server is lenient, it might seem like an overall improvement, but I think in practice it only leads to client implementations that end up relying on the leniency and thus failing to work with another server that's lenient in slightly different ways.

So, should a server exposing some API be lenient or is that a very bad idea?

Now onto lenient handling of user input. Consider YouTrack (a bug tracking software). It uses a language for text entry that is reminiscent of Markdown. Except that it's "lenient". For example, writing

```<code>- foo
- bar
- baz
</code>```

is not a documented way of creating a bulleted list, and yet it worked. Consequently, it ended up being used a lot throughout our internal bugtracker. Next version comes out, and this lenient feature starts working slightly differently, breaking a bunch of lists that (mis)used this (non)feature. The documented way to create bulleted lists still works, of course.

So, should my software be lenient in what user inputs it accepts?

答:
I think this is well covered in chapter 1, section 6 of TAOUP. Specifically, the rule of repair, which states that a program should do what it can with an input, pass correct data forward, and if the correct response is failure then do so ASAP.

A similar concept is defensive programming. You don't know what kind of input you will receive, but your program should be robust enough to cover all cases. This means there should be programmed in recovery cases for known problems like mangled input, and a catch all case to handle unknowns.

So discarding faulty input silently is fine, so long as you are handling that input. You should never just drop it on the floor, as it were.

For an API, I think being lenient is the same as for a program. The input is still wrong, but you are attempting to repair as much as possible. The difference is what is considered valid repair. As you point out, a lenient API can cause problems as people use "features" that don't exist.

Of course, an API is just a lower level version of the rule of composition. As such, it is really covered under the rule of least surprise, since it is an interface.

As the quote from Spencer notes, avoid superficial similarity, which can be argued about "fuzzy" inputs. Under these conditions, I'd normally argue that everything points to the program being unable to repair, because it won't know what is desired, and it is least surprising for the userbase.

However, you are dealing with dates which have many "standards". Sometimes these even get mixed in a single program(chain). Since you know that a date is expected, attempting to recognize the date is just good design. Especially if the date comes from some external program and gets passed unmodified through a second on it's way to you.

OwnerDisplayName: romkyns

ContentLicense: CC BY-SA 3.0


问:
When is an object oriented program truly object oriented?
Let me try to explain what I mean:

Say, I present a list of objects and I need to get back a selected object by a user. The following are the classes I can think of right now:

```<code>ListViewer

Item

App [Calling class]
</code>```

In case of a GUI application, usually click on a particular item is selection of the item and in case of a command line, some input, say an integer representing that item. Let us go with command line application here.

A function lists all the items and waits for the choice of object, an integer. So here, I get the choice, is choice going to conceived as an object?
And based on the choice, return back the object in the list.

Does writing this program like the way explained above make it truly object oriented? If yes, how? If not, why?

Or is the question itself wrong and I shouldn't be thinking along those lines?

答:
Good question. I have personally considered this and have watched dogmatic colleagues struggle with a notion of strict adherence to methodology.

My answer is: It is a balance. This is true, especially in Front-End Systems and most UI. Here is why:

In C, C++, and Java Object-Oriented methodology is a best-practice because the three tenets of OO can be defined clearly in code. That is to say, Inheritance, Polymorphism, and Abstraction improve maintenance, reuse, and extensibility.

Enter JavaScript and we have opened a can of worms. This is because JavaScript can be more expressive without the three tenets. This is for a myriad of reasons but the prime one being JS is object-oriented with objects only; no classes. So there is a simplification in practice.

Attempting to force classical inheritance into that environment, in short, can result in added complexity, not reduced complexity. Designing constructs such as private members can be added maintenance.

That said, let me answer your questions in succession:

Is the choice an object?

-> It can be, but it depends. Should it be reusable? Can it contain behavior or other member variables? In JavaScript, it is an object... always. So this is potentially something of minimal concern.

Is it truly object-oriented?

My perspective is that this is boils down to a matter of opinion, how 'true' the methodology is implemented. There is, perhaps, always a way to refactor something to more closely match a paradigm. So again, to me, this can potentially be of minimal concern. I'll explain why in a moment.

Is the question wrong, and is there another approach?

Correct sir. There are other approaches. Object-Oriented Design is a good idea when it is a good fit with implementation. If you are writing your GUI interface in Qt C++, then by all means, yes it is a good fit. In Java, yes, inherit. However, if you are following a new Windows 8 Metro JavaScript approach, there are a number of topics for consideration.

Another approach.

My suggestion for consideration would be for Design Patterns. Why? Because they are a set of designed patterns to commonly solved problems. The notable achievement here is that this knowledge is highly transferable across language. Implementation is then follows suit of the pattern.

Design Pattern Example.

So, as an alternative to applying scrutiny on implementation, one can take a step back and review the overall design. For example, not-is it truly object oriented, but- do we desire a master-detail pattern, a double-list, or.. etc.

By defining the Design Pattern, implementation becomes self-evident. Sometimes it will be pure Object-Oriented Design, sometimes it will be a higher level Design Pattern.

Thus, it is a balance of implementation in practice and design methodology.

Here is a link, and link.

My humble advice is to understand the 3 tenets, the Design Patterns, and then to flexibly craft the best-fit (maintainable, reusable, extensible, etc.) into each given environment.


问:
Legality of collaborative reverse-engineering
I have been disassembling a large software project on my own, as a hobby. It is an educational exercise and I have learned a lot in the process. That said, I feel that my progress would be considerably quicker if I was to collaborate on the project with other like-minded individuals.

Herein lies the problem -- maybe. I am reversing this software for personal interest and potentially (but unlikely; given the magnitude of the codebase in question) implementing an interoperable service to interact with this software, replacing the vendor's own service. My (very limited) understanding is that this particular use-case is protected under copyright law.

However, my wish is to collaborate with others freely on the Internet, in a similar system employed by open source projects: version control repositories of assembly files, wikis to coordinate and share knowledge, public mailing lists, et cetera. I have a feeling this may be iffy at best.

Is what I want to do blatantly illegal, a gray area or even legally defensible? Would the situation be any different if the collaboration was in private rather than public? If it has any bearing on the answer, I am located in Australia and the software vendor in located in the USA.

答:
Maybe read this http://lwn.net/Articles/134642/

I think reverse engineering is always a gray area legally. But that doesn't worry big corp, they will just use their lawyers to squash you legal or not if you are doing something they don't like. I think they key is to not make noise.

ContentLicense: CC BY-SA 2.5


问:
Is this a pattern? Proxy/delegation of interface to existing concrete implementation
I occasionally write code like this when I want to replace small parts of an existing implementation:

```<code>public interface IFoo
{
    void Bar();
}

public class Foo : IFoo
{
    public void Bar()
    {
    }
}

public class ProxyFoo : IFoo
{
    private IFoo _Implementation;

    public ProxyFoo(IFoo implementation)
    {
        this._Implementation = implementation;
    }

    #region IFoo Members

    public void Bar()
    {
        this._Implementation.Bar();
    }

    #endregion
}
</code>```

This is a much smaller example than the real life cases in which I've used this pattern, but if implementing an existing interface or abstract class would require lots of code, most of which is already written, but I need to change a small part of the behaviour, then I will use this pattern.

Is this a pattern or an anti pattern? If so, does it have a name and are there any well known pros and cons to this approach?

Is there a better way to achieve the same result? Rewriting the interfaces and/or the concrete implementation is not normally an option as it will be provided by a third party library.

答:
Yep, this is a decorator pattern and it certainly has its place.

My only advice here would be not to call the class a proxy as some people might associate that with a proxy design pattern and get a bit confused.  Proxies generally do not change behavior but rather serve as some kind of channel to the real object. This channel could be used for communications, authorization, caching or controlling/scheduling calls to the real object. In all instances, proxy wouldn't alter actual "business logic" of the real component but add some "out-of-band" qualities.

A decorator would implement the same interface, but it could add or remove business logic behavior that's actually being exposed to the client.

For example I work in video and we have presentation objects that expose information regarding live and recorded data available for a given video source. In certain places we only want to expose live video. In other places we want to expose only small segments of recorded video. Instead of recreating an entire presentation object for each of the special cases, we used "LiveOnlyPresentation" and "RecordedSegmentPresentation" decorators to override one function each and simply limit what the client can see.


问:
How can I speed up the process of typing up specification during a meeting with developers?
I'm studying source code with other developers, and my job is to type up the specifications as the lead programmer  describes what each function does. Are there any tips/tricks to doing this faster? a lot of times I have to ask him to repeat himself, as I didn't hear it well.

How can I be a better specification  writer?

答: Combine your fastest method, in your case typing, with a voice recorder.  Partially complete any section where the lead is going too fast, tap your recorder so it makes a CLACK and you can find it easily, then fill in the details later.


答:
I like to use this pattern for repository caching: you can separate the caching logic from the data-access logic, but since the expected contract is essentially the same (the method will return the data it's asked for, regardless of whether it's retrieved from a cache or the underlying repository), it can safely implement the same interface.

```<code>public interface IPersonRepository
{
    Person GetById(int personId);
}
public class PersonRepositoryCache : IPersonRepository
{
    private static ConcurrentDictionary<int, Person> cacheById =
       new ConcurrentDictionary<int, Person>();
    private IPersonRepository _repository;
    public PersonRepositoryCache(IPersonRepository repository)
    {
        _repository = repository;
    }
    public Person GetById(int personId)
    {
        return cacheById.GetOrAdd(personId, id => _repository.GetById(id));
    }
}
</code>```

You'll want to be wary that you don't use this pattern to change the contractual behavior expected of the interface, as this would violate the Liskov Substitution Principle. Only change implementation details, while ensuring that users' expectations of the class's behavior are preserved.

To get the most out of this pattern, consider using an IoC container, so that classes that use the interface are unaware of the implementation details.

This pattern is used effectively by Aspect-Oriented Programming to add behaviors like logging to method calls. Again, these are behaviors that do not alter the contractual behavior of the method in question.

Hat-tip to DXM for pointing out that this is called the Decorator Pattern.

Title: Is this a pattern? Proxy/delegation of interface to existing concrete implementation

Body:
I occasionally write code like this when I want to replace small parts of an existing implementation:

```<code>public interface IFoo
{
    void Bar();
}

public class Foo : IFoo
{
    public void Bar()
    {
    }
}

public class ProxyFoo : IFoo
{
    private IFoo _Implementation;

    public ProxyFoo(IFoo implementation)
    {
        this._Implementation = implementation;
    }

    #region IFoo Members

    public void Bar()
    {
        this._Implementation.Bar();
    }

    #endregion
}
</code>```

This is a much smaller example than the real life cases in which I've used this pattern, but if implementing an existing interface or abstract class would require lots of code, most of which is already written, but I need to change a small part of the behaviour, then I will use this pattern.

Is this a pattern or an anti pattern? If so, does it have a name and are there any well known pros and cons to this approach?

Is there a better way to achieve the same result? Rewriting the interfaces and/or the concrete implementation is not normally an option as it will be provided by a third party library.

Body:
I like to use this pattern for repository caching: you can separate the caching logic from the data-access logic, but since the expected contract is essentially the same (the method will return the data it's asked for, regardless of whether it's retrieved from a cache or the underlying repository), it can safely implement the same interface.

public interface IPersonRepository
{
    Person GetById(int personId);
}
public class PersonRepositoryCache : IPersonRepository
{
    private static ConcurrentDictionary<int, Person> cacheById =
       new ConcurrentDictionary<int, Person>();
    private IPersonRepository _repository;
    public PersonRepositoryCache(IPersonRepository repository)
    {
        _repository = repository;
    }
    public Person GetById(int personId)
    {
        return cacheById.GetOrAdd(personId, id => _repository.GetById(id));
    }
}

You'll want to be wary that you don't use this pattern to change the contractual behavior expected of the interface, as this would violate the Liskov Substitution Principle. Only change implementation details, while ensuring that users' expectations of the class's behavior are preserved.

To get the most out of this pattern, consider using an IoC container, so that classes that use the interface are unaware of the implementation details.

This pattern is used effectively by Aspect-Oriented Programming to add behaviors like logging to method calls. Again, these are behaviors that do not alter the contractual behavior of the method in question.

Hat-tip to DXM for pointing out that this is called the Decorator Pattern.


问:
How to explain OOP to a matlab programmer?
I have a lot of friends who come from electrical / physical / mechanical engineering background, and are curious about what is "OOP" all about. They all know Matlab quite well, so they do have basic programming background; but they have a very hard time grasping a complex type system which can benefit from the concepts OOP introduces.

Can anyone propose a way I can try to explain it to them? I'm just not familiar with Matlab myself, so I'm having troubles finding parallels. I think using simple examples like shapes or animals is a bit too abstract for those engineers. So far I've tried using a Matrix interface vs array-based / sparse / whatever implementations, but that didn't work so well, probably because different matrix types are already well-supported in Matlab.

答:
Vectorized MATLAB code has a strongly functional, declarative feel to it, where matrices are frequently viewed as samples in some space, and operations on those matrices as transformations of that space. When a phenomenon, process or entity is modeled using (vectorized) MATLAB, there often exists an explicit numerical representation that operates as an intermediary between the program logic and the conceptual elements of the entity being modeled. As a result, complexities in the problem domain tend to be reflected as numerical complexity, rather than complexity of program logic or control flow.

The Object-Oriented paradigm has a very different feel: It is frequently used in conjunction with a much more direct approach to modelling structural relationships in the world. In many cases, the OO program is a direct model of an entity, where program logic constructs mirror, directly or indirectly, attributes and properties of the system being modeled. As a result of this, OO program logic tends to have more structural "depth" (and possibly complexity), as it reflects more directly the intricacies of the system under test.

Having said that, there are many situations where the Object-Modelling paradigm is very well aligned with the way that a particular problem is understood and described. This is particularly the case when one is attempting to model discrete entities with a more diverse range of attributes and behavior, such that considering each entity individually and in isolation is more informative than considering each property individually, and the entities together as a population.

With OOP you spend time thinking about individual entities and their properties. Collective behavior is harder to visualize & observe. Structures and relationships tend to be expressed explicitly in code.

With vectorized MATLAB, you spend time thinking about populations of entities. Collective behavior is easier to observe. Structures and relationships tend to be expressed implicitly in code.


问:
Any empirical evidence on the efficacy of CMMI?
I am wondering if there are any studies that examine the efficacy of software projects in CMMI-oriented organizations. For example, are CMMI organizations more likely to finish projects on time and/or on budget than non-CMMI organizations?

CMMI stands for "Capability Maturity Model Integration". It's developed by the Software Engineering Institute at Carnegie-Mellon University (SEI-CMU).

It's not a certification, but there are various companies that will "appraise" your organization to various levels of CMMI, such as level 2 and level 3. (I believe CMMI level 1 is an animalistic, Hobbesian free-for-all that nobody aspires to. In other words, everybody is at least CMMI level 1, even if you've never heard of CMMI before.)

I'm definitely not an expert, but I believe that an organization can be appraised for CMMI levels within different scopes of work: i.e. service delivery, software development, foobaring, etc. My question is focused on the software development appraisal: is an organization that has been appraised to CMMI Level X for software projects more likely to finish a software project on time and on budget than another organization that has not been appraised to CMMI Level X?

However, in the absence of hard data about software-oriented CMMI, I'd be interested in the effect that CMMI appraisals have on other activities as well.

I originally asked the question because I've seen various studies conducted on software (e.g. the essays in The Mythical Man Month refer to numerous empirical studies, as does McConnell's Code Complete), so I know that there are organizations performing empirical studies of software development.

答:
The SEI has published some material regarding the impacts of CMMI on various aspects of software development. There are a few samples of benefits that companies have seen from adopting either CMMI or the SW-CMM. In addition, some companies have provided their success stories to the SEI. Of particular interest might be the technical report Demonstrating the Impact and Benefits of CMMI: An Update and Preliminary Results. Although these are all curated by the SEI, I tend to trust this data since the SEI is a federally-funded research and development center with significant ties to the academic and government communities rather than a commercial/for-profit entity.

You might also be interested in the January/February 2012 issue of CrossTalk, which is a journal for defense industry software engineering. This issue focuses specifically on the benefits of achieving high CMMI maturity (typically defined as Level 4 and Level 5) and reveal data from a couple of defense contractors on the impact to project cost, schedule, and quality (all positive) as they moved into the high maturity levels.


问:
multitenancy with some data sharing
I'm in the planning stages of a new webapp, and I am leaning strongly toward a multitenancy model.  The app has a file storage function, where the user can upload (and operate on) files.

I would like the ability of the user to share these files, however.  How is this typically accomplished in a multi-tenant model?

The example would be something like google docs.  Each user has their own files; they can edit and tag and build collections with these files.  Then, they can share a doc or a collection with someone else for collaboration.

If every user has their own Database and tables, what strategy would one use to allow this kind of sharing while minimizing duplication of files and associated metadata?

答:
You'll want to avoid duplicating the files and dealing with locking mechanisms and conflict resolutions as a result. You can follow a model whereby editing rights are shared on a file as opposed to duplicating the file to be edited by another party.

Sharing editing rights can be enhanced with collaboration by allowing multiple users to edit the same document at the same time (if your app has such a feature) and helps users avoid overwriting each others changes. You can avoid the overwriting issue by keeping a history of saves of course but in my experience, a user may not notice that an update was just made to a document they were working on or uploaded unless the UI makes that fact stand out.

Title: multitenancy with some data sharing


问:
Should I tell a departed coworker about their "sev 1" defect?
I had a co-worker leave our company recently. Before leaving, he coded a component that had a severe memory leak that caused a production outage (OutOfMemoryError in Java).  The problem was essentially a HashMap that grew and never removed entries, and the solution was to replace the HashMap with a cache implementation.

From a professional standpoint, I feel that I should let him know about the defect so he can learn from the error.  On the other hand, once people leave a company,  they often don't want to hear about legacy projects that they have left behind for bigger and better things.

What is the general protocol for this sort of situation?

答: With a mistake that simple, odds are good if it bothered the coworker, they probably realized the issue a couple days later while musing about it. I know I've gone home from work and realized "....crap, that algorithm is totally flawed, I'll have to redo it tomorrow" while unwinding and reminiscing about my day. </p>


答: If you do decide to tell him be sure that you tell all the reviewers of his code too! They're equally responsible! To me it sounds like you didn't get on with this guy and want to have a dig at him. Let it go, he's unlikely to care.</p>

Title: Should I tell a departed coworker about their "sev 1" defect?

Body:
I had a co-worker leave our company recently. Before leaving, he coded a component that had a severe memory leak that caused a production outage (OutOfMemoryError in Java).  The problem was essentially a HashMap that grew and never removed entries, and the solution was to replace the HashMap with a cache implementation.

From a professional standpoint, I feel that I should let him know about the defect so he can learn from the error.  On the other hand, once people leave a company,  they often don't want to hear about legacy projects that they have left behind for bigger and better things.

What is the general protocol for this sort of situation?


问:
I'm doing 90% maintenance and 10% development, is this normal?
I have just recently started my career as a web developer for a medium sized company. As soon as I started I got the task of expanding an existing application (badly coded, developed by multiple programmers over the years, handles the same tasks in different ways, zero structure).

So after I had successfully extended this application with the requested functionality, they gave me the task to fully maintain the application. This was of course not a problem, or so I thought. But then I got to hear I wasn't allowed to improve the existing code and to only focus on bug fixes when a bug gets reported.

From then on I have had three more projects just like the above, that I now also have to maintain. And I got four projects where I was allowed to create the application from scratch, and I have to maintain those as well.

At this moment I'm slightly beginning to get crazy from the daily mails of users (read managers) for each application I have to maintain. They expect me to handle these mails directly while also working on two other new projects (and there are already five more projects lined up after those). The sad thing is I have yet to receive a bug report on anything that I have coded myself. For that I have only received the occasional let's-do-things-180-degrees-different change requests.

Anyway, is this normal? In my opinion I'm doing the work equivalent of a whole team of developers.

Was I an idiot when I initially expected things to be different?

I guess this post has turned into a big rant, but please tell me that this is not the same for every developer.

P.S. My salary is almost equal if not lower than that of a cashier at a supermarket.

答:
If I were you, I would spend some late hours after work rebuilding the application for free. It would probably be a fun task. When you finish it, show it to your boss. If it works and you're doing maintenance on it, he should have nothing to worry about. This will make your job much easier and would open the eyes of the higher ups to your potential in the company.

I'm a full time college student working a part time internship for US$10 an hour. I do QA stuff that's boring, repetitive, and easy. I consider myself to be extremely lucky, because I know one day this will open doors to bigger and better places.


答:
It sounds like your management fundamentally does not respect you or understand your work load.

You should not be implementing every feature request that comes through. Your manager should act as a buffer between you and incoming requests (except perhaps the most simple of break/fix requests). Then he or she should sit down with you and determine the feasibility and priority for any approved requests.

Also, you should be making probably 2x (at least) what they're paying you.

It sounds like they probably really need at least 1 more developer to work alongside you, but with what they're paying you that sounds pretty unlikely.

If they are unwilling to adequately pay you or help you manage your workload, I'd be looking for a new job. You want to work someplace where you're part of a team, and where your management works with you to complete your projects. Get off that sinking ship as soon as you can.

Being a hero on a team of one is only going to burn you out.

Title: I'm doing 90% maintenance and 10% development, is this normal?

Body:
I have just recently started my career as a web developer for a medium sized company. As soon as I started I got the task of expanding an existing application (badly coded, developed by multiple programmers over the years, handles the same tasks in different ways, zero structure).

So after I had successfully extended this application with the requested functionality, they gave me the task to fully maintain the application. This was of course not a problem, or so I thought. But then I got to hear I wasn't allowed to improve the existing code and to only focus on bug fixes when a bug gets reported.

From then on I have had three more projects just like the above, that I now also have to maintain. And I got four projects where I was allowed to create the application from scratch, and I have to maintain those as well.

At this moment I'm slightly beginning to get crazy from the daily mails of users (read managers) for each application I have to maintain. They expect me to handle these mails directly while also working on two other new projects (and there are already five more projects lined up after those). The sad thing is I have yet to receive a bug report on anything that I have coded myself. For that I have only received the occasional let's-do-things-180-degrees-different change requests.

Anyway, is this normal? In my opinion I'm doing the work equivalent of a whole team of developers.

Was I an idiot when I initially expected things to be different?

I guess this post has turned into a big rant, but please tell me that this is not the same for every developer.

P.S. My salary is almost equal if not lower than that of a cashier at a supermarket.


问:
Should program behavior be modified using a config file or environmental variables?
I'm referring to *nix command line applications primarily, where you want to permanently modify the behavior from defaults.

Environmental variables are easily understood and implemented, usually requiring the user to modify their ~/.bashrc for a permanent change. However, namespace collision might be a problem (but unlikely if you're careful).

On the other hand, a lot of programs use ~/.programrc config files.

Is it simply verbosity? If your program only has 2 configuration settings, then a simple export APP_SETTING=1 works just fine. However if you're starting to offer 5+ options then it should be time to start looking into a config file?

答: Config files (for the sake of keeping a record of configuration changes), overridden by (optional) environment variables (for the sake of temporary modifications in uncontrolled environments).</p>


答:
Nobody can tell you what "truly object-orientated" is. That's like asking for the true religion.

And there is nothing wrong with your sample program. Do you need an Index type? Well, probably not. There's no reason to over-complicate things here.

Title: When is an object oriented program truly object oriented?

Body:
Let me try to explain what I mean:

Say, I present a list of objects and I need to get back a selected object by a user. The following are the classes I can think of right now:

```<code>ListViewer

Item

App [Calling class]
</code>```

In case of a GUI application, usually click on a particular item is selection of the item and in case of a command line, some input, say an integer representing that item. Let us go with command line application here.

A function lists all the items and waits for the choice of object, an integer. So here, I get the choice, is choice going to conceived as an object?
And based on the choice, return back the object in the list.

Does writing this program like the way explained above make it truly object oriented? If yes, how? If not, why?

Or is the question itself wrong and I shouldn't be thinking along those lines?


问:
Should Version Control Softwares be used from Command Line or GUI
I was going through some tutorials on TortoiseHg. Despite having a rich GUI, the first examples are given using command line options.
Does the ideal usage involve command line or it was started that way so one has idea of what is happening under the hood and GUI internally uses this command anyway.</p>

答:
TortoiseSVN for SVN on Win32/64, because of the icon overlays for visual feedback.

Otherwise: GUI for less-frequent operations (superior discoverability & better affordances), command-line for most common operations (increased parsimony, fewer keystrokes).


问:
What are the advantages of version control systems that version each file separately?
Over the past few years I have worked with several different version control systems. For me, one of the fundamental differences between them has been whether they version files individually (each file has its own separate version numbering and history) or the repository as a whole (a "commit" or version represents a snapshot of the whole repository).

Some "per-file" version control systems:

CVS

ClearCase

Visual SourceSafe

Some "whole-repository" version control systems:

SVN

Git

Mercurial

In my experience, the per-file version control systems have only led to problems, and require much more configuration and maintenance to use correctly (for example, "config specs" in ClearCase). I've had many instances of a co-worker changing an unrelated file and breaking what would ideally be an isolated line of development.

What are the advantages of these per-file version control systems? What problems do "whole-repository" version control systems have that per-file version control systems do not?

答:
There is no advantage whatsoever to per-file versioning.

The disadvantages on the other hand, are plentiful and manifest.


问:
What is an "ontology" in the context of the Semantic Web?
Okay, I have been learning SPARQL to query dbpedia and I can't seem to find clear and practical tutorials related to SPARQL and the Semantic Web. If I say that an ontology is analogous to an SQL table definition or maybe a specification of an object's members should I be slapped?</p>

答:
Most basically, the term "ontology" is roughly equivalent to the "domain model". It is the set of all objects that represent real world objects or concepts, including all defined relationships, rules, attributes and other metadata that is known or must be assumed as true about these objects within the bounds of this domain.

In the Semantic Web, the "ontology" being discussed is the definition of the information available from a Semantic Web data store. It's contained in documents that conform to a standard called RDF (Resource Description Framework), which can be implemented or serialized as an XML document. Think of these definitions as having a similar purpose for Web 3.0 as WSDL  or JSDL documents have for web services; they contain the metadata needed for a computer to generate the DTOs and make the calls to obtain the data.


答:
There is no advantage on the per-file approach when you have related files. Which is the most common case in a development settings.

In a few peculiar cases -- /etc or . files in your home directory in Unix is the only one I routinely have -- you are handling (mostly) unrelated files. And then having a system which insists on keeping in sync unrelated changes can be a nuisance.

Title: What are the advantages of version control systems that version each file separately?

Body:
Over the past few years I have worked with several different version control systems. For me, one of the fundamental differences between them has been whether they version files individually (each file has its own separate version numbering and history) or the repository as a whole (a "commit" or version represents a snapshot of the whole repository).

Some "per-file" version control systems:

CVS

ClearCase

Visual SourceSafe

Some "whole-repository" version control systems:

SVN

Git

Mercurial

In my experience, the per-file version control systems have only led to problems, and require much more configuration and maintenance to use correctly (for example, "config specs" in ClearCase). I've had many instances of a co-worker changing an unrelated file and breaking what would ideally be an isolated line of development.

What are the advantages of these per-file version control systems? What problems do "whole-repository" version control systems have that per-file version control systems do not?


答:
There's two types of "lenient":  One is to accept incorrect input and try to make sense of it, and the other is to accept different types of input.

Generally, you always want the second one when it's feasible.  The first one is when you die fast and hard.  An example:  Dates.

Here're some example inputs, including valid, invalid, and ambiguous.

2011-01-02

01/02/2011

Jan 2, 2011

2-Jan-2011

Green

There's only one invalid input here:  Green.  Don't even try to accept it as a date.  Since Green is obviously not a date, this is a case where silent failing is acceptable.

01/02/2011 is valid, but ambiguous.  You don't necessarily know whether or not it's been entered as a US date (Jan 2) or not (Feb 1).  Here, it's probably best to fail loudly, and ask the user for an unambiguous date.

2011-01-02 is usually considered unambiguous, so it's often fine to go ahead and assume it's the format "YYYY-MM-DD", and only fail further down the line.  It's a bit of a judgment call, though, when dealing with user input.

Jan 2, 2011 and 2-Jan-2011 are valid and unambiguous, they should be accepted.  However, The Second of January of the year 2011 is also valid and unambiguous, but going that far for the sake of leniency is overkill.  Go ahead and fail it silently, just like Green.

In short, the answer is "it depends".  Take a look at what can be inputted, and make sure you're never accepting conflicting types of input (like DD/MM/YYYY vs MM/DD/YYYY).

In the context of the linked question/comment, That is a case of 2011-01-02.  The input looks like JSON and will validate like JSON even if the mimetype is wrong; go ahead and try to use it even if it fails at some point further down the line.

Title: Should a server "be lenient" in what it accepts and "discard faulty input silently"?

Body:
I was under the impression that by now everyone agrees this maxim was a mistake. But I recently saw this answer which has a "be lenient" comment upvoted 137 times (as of today).

In my opinion, the leniency in what browsers accept was the direct cause of the utter mess that HTML and some other web standards were a few years ago, and have only recently begun to properly crystallize out of that mess. The way I see it, being lenient in what you accept will lead to this.

The second part of the maxim is "discard faulty input silently, without returning an error message unless this is required by the specification", and this feels borderline offensive. Any programmer who has banged their head on the wall when something fails silently will know what I mean.

So, am I completely wrong about this? Should my program be lenient in what it accepts and swallow errors silently? Or am I mis-interpreting what this is supposed to mean?

The original question said "program", and I take everyone's point about that. It can make sense for programs to be lenient. What I really meant, however, is APIs: interfaces exposed to other programs, rather than people. HTTP is an example. The protocol is an interface that only other programs use. People never directly provide the dates that go into headers like "If-Modified-Since".

So, the question is: should the server implementing a standard be lenient and allow dates in several other formats, in addition to the one that's actually required by the standard? I believe the "be lenient" is supposed to apply to this situation, rather than human interfaces.

If the server is lenient, it might seem like an overall improvement, but I think in practice it only leads to client implementations that end up relying on the leniency and thus failing to work with another server that's lenient in slightly different ways.

So, should a server exposing some API be lenient or is that a very bad idea?

Now onto lenient handling of user input. Consider YouTrack (a bug tracking software). It uses a language for text entry that is reminiscent of Markdown. Except that it's "lenient". For example, writing

```<code>- foo
- bar
- baz
</code>```

is not a documented way of creating a bulleted list, and yet it worked. Consequently, it ended up being used a lot throughout our internal bugtracker. Next version comes out, and this lenient feature starts working slightly differently, breaking a bunch of lists that (mis)used this (non)feature. The documented way to create bulleted lists still works, of course.

So, should my software be lenient in what user inputs it accepts?


答:
It should not be the decision of your employer to micromanage you to the extent, that you are prohibited from improving the existing code. Use your own professional judgement. When you are estimating work, I would factor in additional time to allow for some refactoring, if it will increase productivity in the future.

Anyway, it seems like you aren't effectively communicating with your employer.

You have evidence that refactoring will save money. Draft a proposal for a refactoring project and demonstrate how much time and money the business could save. Outline precisely what changes you would make to the code, and how long it would take.

Keep an accurate log to record how much time you spend on coding, meetings, and answering emails. This will protect you if you fall behind schedule.

Slow down. This may seem a little counter intuitive, but your time will only be abused if you do everything quickly. People will respect your time more if you do less. For example, I would only check email once or twice per day. Otherwise, you risk burnout.

Considering your pay rate, it isn't worth getting a headache over. Make sure you leave on time every day. Don't put in extra hours without additional compensation. The exception is if there are good advancement options, or if the reputation of the company will greatly boost your resume, then you will just have to suck it up.

Without knowing more, I would just suggest that you try to be more open with your managers. Maybe start increasing your task estimates. Constantly remind them about how busy your workload is. Also, you should meet with your boss and explain that you would like a salary increase within the next six months, and ask how you could improve your performance in order to achieve this pay increase.

Good luck.


问:
Bringing in New Architecture During Maintenance on Legacy Systems
I have been tasked with adding some new features to a legacy ASP.NET MVC2 project. The codebase is a disaster and I want to write these new features with some thought behind the implementation and not just throw these new features into the mess. I would like to introduce things like dependency injection and the orchestrator pattern; just to the code that I am going to write. I don't have enough time to try to refactor the entire system.

Is it OK to not be consistent with the rest of the codebase and add new features following different design principles? Should I not introduce new patterns and just get the features implemented?

I feel like it might be confusing to the next person to see parts of the system using a design that other parts are not following.

答:
I've been in a similar situation, and it's a tough decision. As you've pointed out, it would be nice to start cleaning up the code and (ideally) be able to clean it all up over time. On the other hand, it would be rather annoying for future developers to see these sore thumb in the code, regardless of how good the code is written.

In the situation I was in, I tried many different things. The code was, and still lis, horrible. Some of the changes I tried were drastic, and others were less so. But whenever I tried to refactor the code, I found that doing so would just make the code more complicated and harder to understand.

Ultimately I tried to find patterns that existed in the spaghetti. Once I identified a few, I started to simply formalize it. This required very little changes, because I was mostly adding interfaces and identifying areas of the code base that could be made a little more generic with out drastic changes. This turned out to work very well. Now the mess felt like it had a structure, and that alone made it easier to reason about.

If you can do this in one key area (probably related to the feature requests) and branch them out to similar areas of the code base, you'll leave the code just a little better than you found it, but with out turning the forest into a shopping mall.

Also, check out Code stinks! What do I do? on the Programmers Community Blog.


答:
I think it's better that at least part of the system is written "correctly", rather than the whole system being consistent, but hard to use.

I would make notes that the unchanged code should be changed at some point (hopefully soon), and proceed to refactor things as you go along.

It's pretty unlikely that you would refactor the whole system in one go anyway, so it's ok if there are temporary moments of inconsistency, as long as you are going towards a cleaner codebase.

Title: Bringing in New Architecture During Maintenance on Legacy Systems

Body:
I have been tasked with adding some new features to a legacy ASP.NET MVC2 project. The codebase is a disaster and I want to write these new features with some thought behind the implementation and not just throw these new features into the mess. I would like to introduce things like dependency injection and the orchestrator pattern; just to the code that I am going to write. I don't have enough time to try to refactor the entire system.

Is it OK to not be consistent with the rest of the codebase and add new features following different design principles? Should I not introduce new patterns and just get the features implemented?

I feel like it might be confusing to the next person to see parts of the system using a design that other parts are not following.


答:
I would advise not letting the status quo dictate the future, generally speaking.  While there is something to be said for continuity, there is really very little to be said for continuing to suck (pardon the expression).  Any small advantage in readability/understandability by not introducing new development patterns is likely to be offset by the nature of the mess itself.

If there are a lot of other people working on the project, and they've worked in and contributed to the mess, then I think they need to see what "non-mess" looks like.  If you never introduce "non-mess", nobody will have any example to follow other than mess.  Good design has to start somewhere, and if you are clear in your purpose and good about explaining the philosophy, other parts of the code will start to align with your effort.


问:
Mercurial release management. Rejecting changes that fail testing
Researching distributed source control management (specifically mercurial).
My question is more or less what is the best practice for rejecting entire sets of code that fail testing?

Example:

A team is working on a hello world program.  They have testers and a scheduled release coming up with specific features planned.

```<code>Upcoming Release:
   Add feature A
   Add feature B
   Add feature C
</code>```

So, the developers make their clones for their features, do the work and merge them into a QA repo for the testers to scrutinize.

Let's say the testers report back that "Feature B is incomplete and in fact dangerous",  and they would like to retest A and C.

End example.

What's the best way to do all this so that feature B can easily be removed and you end up with a new repo that contains only feature A and C merged together?

Recreate the test repo? Back out B? Other magic?

答:
Your best bet is to have the coded tested before it's committed. Backing out B is your best bet, if you can't do that.

Backing out changeset is the process of applying the inverse patch of that changeset.  By extension, you can backout a range of changesets by applying the inverse of patch of all the changesets.  This should be the default methodology of "reverting" a change or set of changes as it will maintain the consistency and completeness of the repository.

```<code>hg pull
hg up # Now your working directory and local repo are up to date
hg up -r revLast # Update to the latest revision you want to backout
hg revert -a -r revFirst-1 # Creates an inverse patch of revFirst to revLast
hg ci -m "Backed out revFirst - revLast" # Commit inverse patch
hg merge # Merge inverse patch to tip in my working directory
hg ci -m "Merged change back into the tip" # Commit inverse patch to tip in local repo
hg push # Push to master
</code>```

Body:
Your best bet is to have the coded tested before it's committed. Backing out B is your best bet, if you can't do that.

Backing out changeset is the process of applying the inverse patch of that changeset.  By extension, you can backout a range of changesets by applying the inverse of patch of all the changesets.  This should be the default methodology of "reverting" a change or set of changes as it will maintain the consistency and completeness of the repository.

hg pull
hg up # Now your working directory and local repo are up to date
hg up -r revLast # Update to the latest revision you want to backout
hg revert -a -r revFirst-1 # Creates an inverse patch of revFirst to revLast
hg ci -m "Backed out revFirst - revLast" # Commit inverse patch
hg merge # Merge inverse patch to tip in my working directory
hg ci -m "Merged change back into the tip" # Commit inverse patch to tip in local repo
hg push # Push to master


答:
I'm only a student (still) but that's pretty normal (from my internship experience). That's what you get when working in support and web applications.

I'd advise you to understand what the client (manager) wants before starting coding. That could be tricky because sometimes they don't know it themselves so work with them till they agree on something. Make sure you both agree on the final solution before you code it.

Also if you are a maintainer you can pretty much change anything in the code - just make sure it doesn't change the behaviour or introduce bugs. I expect managers do not 'allow' you to change anything because they are used to and happy with how it is now and they don't want to pay for any new changes.

Finally, don't worry if you can't handle something because you're doing something else. I'd advise you to let people know that you are overwhelmed with work and their request will take time. If you don't managers would just think you're lazy. Do let them know you already have work and they might hire more people. There is no other way for them to know that the work is too much for a single person.


问:
Product agnostic book on Message Queues?
Are there any recommendations for book(s) that are largely agnostic (with examples of MQ implementations is fine) on vendor but go to great details on the architecture, management, nomenclature, atomicity, durability, patterns, and logical deployments on Message Queue systems?

Surely there are enough shared concepts between MQ Series, MSMQ, SysV IPC (OK, that might be stretching it), RabbitMQ, &c &c?

答:
Have you tried Enterprise Integration Patterns? It's not exclusively on message queues, but on messaging systems.

The book Enterprise Integration Patterns provides a consistent vocabulary and visual notation to describe large-scale integration solutions across many implementation technologies. It also explores in detail the advantages and limitations of asynchronous messaging architectures. You will learn how to design code that connects an application to a messaging system, how to route messages to the proper destination and how to monitor the health of a messaging system. The patterns in the book are technology-agnostic and come to life with examples implemented in different messaging technologies, such as SOAP, JMS, MSMQ, .NET, TIBCO and other EAI Tools...


答:
I don't think one can give a definitive answer, because there is significant debate nowadays about what Object Oriented design actually is. I will try to outline somewhat of a consensus below, and point out where my own opinion dissents.

Established OOP has its roots in studies in the early 1970s discussing principles, methods & patterns for dealing with complex code - such as the principle of Separations of Concerns (Dijkstra) (while aware that Smalltalk was around before that, I believe that this particular leap in theoretical understanding stands at the foundation of today's OOP). In pure object-oriented design, each type of object (class) should represent a singular/atomic idiom qualifying a relevant aspect of your solution, because OOP is an orthodox practical implementation of SoC theory. Therefore, as a generic rule of thumb, if you are describing a solution, and can drill down the use-case to words which are specific enough such that they can't be broken down further (as per SoC) while still being directly relevant to your solution, they will usually correspond in some way to your classes.

It is difficult to give an example to this based on your question (it is too vague), but App isn't usually a type of object (because it can usually be broken down in features and aspects), while list item may be a type of object (a UI element representing one component of the model). The click event, going from your UI to your model, is in somewhat of a gray area: you may choose to represent it as an object (ex. an implementation of the Command pattern) if it is handled in a way specific to your application (i.e. lifecycle - triggering and consuming, not necessarily its implementation), but most of the times it is generic enough to be a language idiom.

Going further, there are several principles and stereotypes which people have identified as good practice when pursuing object-oriented design, which are actually the living definition of the concept. The theoretical basics are abstraction, encapsulation and polymorphism (another personal opinion: inheritance, is not a first-class citizen, for theoretical reasons - it is actually a kind of subtype polymorphism, and for practical reasons - I'm with the GoF here, favor composition). Consequently, when designing your objects, try to consider the application of these principles, because in an overwhelming majority of cases they will lead to what most people consider OOP.

A lot more can be derived starting from the above: unlike modules, objects are small and many (stricter observation of encapsulation and abstraction). Because they are so, the structural relationships between objects become more important, therefore one needs to consider design patterns more carefully than in modular design. Also, since objects have smaller, well defined areas of responsibility within the context of your solution, their life cycle will not usually coincide with the life cycle of your application, therefore, their creation and destruction becomes a design problem. Even more so, since you now have many objects covering the same responsibility as a large module, you really need to consider how they communicate while observing SoC, hence it is important to design with decoupled interface contracts, otherwise the objects will end up exposing too much of their state to their peers.

Programming languages supporting modern OOP will give you an even wider array of tools - which are themselves derived as implementations of the theoretical principles above: they will have features which support the basic "tenets" (ex. some form of interface, some form of enforcing encapsulation), features which separate vertical concerns (your solution's implementation, from abstract to specific) from horizontal concerns (aspects & policy applicable to all features - life cycle, object persistence), features reconciling the simplicity of linear control flow with the granularity of OOP design (exception handling, task parallelism, lambdas). Using correctly, and maybe even mastering a powerful language which was designed with OOP in mind (such as Java, C# or maybe even C++ - the latter with a lot of protest including from yours truly) is a great way to gain good insight into how to drive your designs.

Finally, OOP applied to the letter may indeed be too orthodox for practical purposes, therefore always consider the hows and whys (I think a good consensus between answers to this question will be to take everything with a grain of salt). OOP is a vehicle, not a purpose in itself, always put your solution's restrictions before theory - maybe even with a YAGNI approach.


问:
Is it common for a programmer not to know the difference between C and C++?
During an interview, I was asked whether I knew the difference between C and C++.

I was wondering why such question being asked?

答:
There are also a small percentage of people (such as myself) who learned C++ before they
learned C.

I'm sure you know the differences, but if you are a student who has only had a C++
class, and not a C class the parts of C++ that are not C compatible will not
be obvious.

Some of the more obvious differences I've learned (not an exhaustive list)
() struct data types originally could not contain functions,
    and can't have private members, meaning it
    is very difficult to Enforce the validity rules of an abstract data type in C.
() classes are not supported in C
() passing by reference using the ampersand operator is specific to C++
() C doesn't support streams or templates
(*) malloc and free are intended for use only in C and not in C++


问:
Should functions of a C library always expect a string's length?
I'm currently working on a library written in C. Many functions of this library expect a string as char* or const char* in their arguments. I started out with those functions always expecting the string's length as a size_t so that null-termination wasn't required. However, when writing tests, this resulted in frequent use of strlen(), like so:

```<code>const char* string = "Ugh, strlen is tedious";
libFunction(string, strlen(string));
</code>```

Trusting the user to pass properly terminated strings would lead to less safe, but more concise and (in my opinion) readable code:

```<code>libFunction("I hope there's a null-terminator there!");
</code>```

So, what's the sensible practice here? Make the API more complicated to use, but force the user to think of their input, or document the requirement for a null-terminated string and trust the caller?

答:
In C, the idiom is that character strings are NUL-terminated, so it makes sense to abide by common practice - it is actually relatively unlikely that users of the library will have non-NUL-terminated strings (since these need extra work to print using printf and use in other context). Using any other kind of string is unnatural and probably relatively rare.

Also, under the circumstances, your testing looks a little odd to me, since to work correctly (using strlen), you are assuming a NUL-terminated string in the first place. You should be testing the case of non-NUL-terminated strings if you intend your library to work with them.


答:
Most definitely and absolutely carry the length around. The standard C library is infamously broken this way, which has caused no end of pain in dealing with buffer overflows. This approach is the focus of so much hatred and anguish that modern compilers will actually warn, whine and complain when using this kind standard library functions.

It is so bad, that if you ever come across this question at an interview - and your technical interviewer looks like he's got a few years of experience - pure zealotry may land the job - you can actually get pretty far ahead if you can cite the precedent of shooting someone implementing APIs looking for the C string terminator.

Leaving the emotion of it all aside, there is much that can go wrong with that NULL at the end of your string, in both reading and manipulating it - plus it is really in direct violation of modern design concepts such as defense-in-depth (not necessarily applied to security, but to API design). Examples of C APIs which carry the length abound - ex. the Windows API.

In fact, this problem was settled sometime in the '90s, today's emerging consensus is that you shouldn't even touch your strings.

Later edit: this is quite a live debate so I'll add that trusting everyone below and above you to be nice and use the library str* functions is OK, until you see classic stuff like output = malloc(strlen(input)); strcpy(output, input); or while(*src) { *dest=transform(*src); dest++; src++; }. I can almost hear Mozart's Lacrimosa in the background.

Title: Should functions of a C library always expect a string's length?

Body:
I'm currently working on a library written in C. Many functions of this library expect a string as char* or const char* in their arguments. I started out with those functions always expecting the string's length as a size_t so that null-termination wasn't required. However, when writing tests, this resulted in frequent use of strlen(), like so:

```<code>const char* string = "Ugh, strlen is tedious";
libFunction(string, strlen(string));
</code>```

Trusting the user to pass properly terminated strings would lead to less safe, but more concise and (in my opinion) readable code:

```<code>libFunction("I hope there's a null-terminator there!");
</code>```

So, what's the sensible practice here? Make the API more complicated to use, but force the user to think of their input, or document the requirement for a null-terminated string and trust the caller?


答:
Your "safety" argument doesn't really hold. If you don't trust the user to hand you a null-terminated string when that's what you documented (and what's "the norm" for plain C), you can't really trust the length they give you either (which they'll probably get by using strlen just as you're doing if they don't have it handy, and which will fail if the "string" wasn't a string in the first place).

There are valid reasons to require a length though: if you want your functions to work on substrings, it is possibly much easier (and efficient) to pass a length than to have the user do some copying magic back and forth to get the null byte at the right place (and risk off-by-one errors along the way).

Being able to handle encodings where null bytes are not terminations, or being able to handle strings that have embedded nulls (on purpose) can be useful in some circumstances (depends on what exacltly your functions do).

Being able to handle non-null-terminated data (fixed-length arrays) is also handy.

In short: depends on what you're doing in your library, and what type of data you expect your users to be handling.

There's also possibly a performance aspect to this. If your function needs to know the length of the string in advance, and you expect your users to at least usually already know that information, having them pass it (rather than you calculating it) could shave a few cycles.

But if your library expects ordinary plain ASCII text strings, and you don't have excruciating performance constraints and a very good understanding of how your users will interact with your library, adding a length parameter doesn't sound like a good idea. If the string isn't properly terminated, chances are the length parameter will be just as bogus. I don't think you'll gain much with it.


答: You should always keep your length around. For one, your users may wish to contain NULLs in them. And secondly, don't forget that strlen is O(N) and requires touching the whole string- bye bye cache. And thirdly, it makes it easier to pass around subsets- for example, they could give less than the actual length.


问:
When is an object oriented program truly object oriented?
Let me try to explain what I mean:

Say, I present a list of objects and I need to get back a selected object by a user. The following are the classes I can think of right now:

```<code>ListViewer

Item

App [Calling class]
</code>```

In case of a GUI application, usually click on a particular item is selection of the item and in case of a command line, some input, say an integer representing that item. Let us go with command line application here.

A function lists all the items and waits for the choice of object, an integer. So here, I get the choice, is choice going to conceived as an object?
And based on the choice, return back the object in the list.

Does writing this program like the way explained above make it truly object oriented? If yes, how? If not, why?

Or is the question itself wrong and I shouldn't be thinking along those lines?

答:
Looking at your example I think that you can be ok with the choice being non-object, but imagine your program become more complex, for example you could introduce undo/history or your layout can start support a tree instead of a linear list so at some point you can consider making the item of choice an object and probably the subject to future inheritance. This is because maitaining such complexity would become too difficult. </p>

<p>So your "oop rate" should not be the result of purism or theoretical requirements, but the consequence of your program becoming more complex. </p>

Body:
Looking at your example I think that you can be ok with the choice being non-object, but imagine your program become more complex, for example you could introduce undo/history or your layout can start support a tree instead of a linear list so at some point you can consider making the item of choice an object and probably the subject to future inheritance. This is because maitaining such complexity would become too difficult.

So your "oop rate" should not be the result of purism or theoretical requirements, but the consequence of your program becoming more complex.


答:
Answer

Yes, its common. I have seen this situation, either myself, coworkers, or third party libraries code.

Myself, for example, sometimes work with other programming languages or programming frameworks, and have to link, or update, to either "pure c" or "c++" libraries.

I just had the problem of modifying some "Pure C" code. And using "new" & "delete" memory allocation functions, that are "c++". The rest of the code was not object oriented

The compiler was C++. Later, I sued another compiler, and discovered the error.

Bonus

If some one ask, verbally, or in a written test, or web online test:

"Do you know the difference between C or C++"

And you answer "Yes" or "No".

They really mean:

"Do you know the difference between C or C++, if you do please tell me ?"

So, you have to answer:

"Yes. The difference its that C++ its Object Oriented, although, you may use Pure C, inside a C++ program, for backward compatibility."

Sometimes, they will not ask you "if you do please tell me", and they will assume that you don't know. Don't just answer "yes", or "no".

Title: Is it common for a programmer not to know the difference between C and C++?

Body:
During an interview, I was asked whether I knew the difference between C and C++.

I was wondering why such question being asked?


问:
MPL 1.1 and APL 2.0 License compatibility
I am working a project that is licensed under the MPL 1.1 and would like to incorporate some code that is licensed under the APL 2.0.

I know in 2010 Mozilla announced they were updating the MPL to make it more "Apache compatible" among other things.

I'm no lawyer. Exactly what part(s) of the MPL 1.1 don't jive with the APL 2.0 and vice versa? The project has very few of its original contributers still actively involved so I doubt I'd be able to contact all of them to get permission to change the license.

答:
Unless your project has been using "Mozilla 1.1 only",
it is implicitly using "Mozilla 1.1 or higher".
Therefore, the project can be upgraded to Mozilla 2.0 (or even forked,
without the consent of the contributors).

If you want to stay with Mozilla 1.1, all you need to do
is to not mix Apache and Mozilla licensed code in the same source file.
Your project will then be a mixed-license work.
Browse the "copyright" files at http://packages.debian.org
to see how ordinary this situation is.

=========== full background

The Apache license (2.0; 1.0 is unrelated!) is "permissive", meaning derivates can be be commercial and closed.  Prior to Apache, all of the popular permissive licenses (BSD, Athena(MIT/X11), zLib, ~ Public Domain) were quite simple.
So they are compatible with nearly all other licenses  (well, except
if there was an advertizement clause, which is now rare).

The Apache license tries to address more modern needs.
It has procedures for tracking the history of a work.
It has a MAD (Mutually Assured Destruction)-style patent clause.
None of that is really opposed by GPL or Mozilla,
it's just not among the "restrictions" that they allow.

The Mozilla license requires less crediting, but requires
deriviatives to be made available to the "initial developer"
of the project without restriction,  and made available to the public under the Mozilla license.  It was intended allow code to be open sourced without the owner losing her advantage over competitors.

The Mozilla license infects up to the source code file boundary,
but generally, no further than that.  (The GPL infects much more,
up to the linker / kernel-call boundary.)  Patch files are an exception,
since they tend to be derived works of the target of the patch.

You can freely aggregate files under Mozilla, LGPL, and any permissive license such as Apache.
This is the norm in large open-source applications.
Especially so for Java, where GPL is considered too infective, and Apache.org is the biggest infrastructure provider.

A single file of source code cannot comply with both Mozilla 1.1 AND Apache
license, because Mozilla (like GPL) does not tolerate any additional
encumberance.  A single piece of source can
comply with Mozilla OR Apache, or almost any other license.
For example, Firefox is released under Mozilla OR GNU OR LGNU license.

Due to Apache's growing influence, GPLv3 and Mozilla v2
made sure that they were compatible.
Opting out of the "version upgrade clause" is the only encumberance that
GPL and Mozilla allow a user to add.
The only major license that users actually did "opt out" of
was GPLv3, due to it being more infective than GPLv2.
The Linux kernel, for example, is GPLv2 only.


问:
Handle all authentication logic in database or code?
We're starting a new(ish) project at work that has been handed off to me. A lot of the database sided stuff has been fleshed out, including some stored procedures. One of the stored procedures, for example, handles creation of a new user. All of the data is validated in the stored procedure (for example, password must be at least 8 characters long, must contain numbers, etc) and other things, such as hashing the password, is done in the database as well.

Is it normal/right for everything to be handled in the stored procedure instead of the application itself?

It's nice that any application can use the stored procedure and have the same validation, but the application should have a standard framework/API function that solves the same problem. I also feel like it takes away the data from the application and is going to be harder to maintain/add new features to.

答: No, it is not typical that a stored procedure handles all data validation. From my observations, stored procedures should use assertions as a last line of defense against bad data. Like making sure string data doesn't exceed n character length for a particular field.  Stuff like the password must meet certain criteria like having at least 1 special character, 1 number, and not have spaces is usually handled in the application layer.The application layer should be doing the major validation work before the data gets to the stored procedure.


答:
Probably not literally, in that they think C++ and C are one and the same, but in terms of truly understanding and being able to use the different features of C++, yes.

The main cause is the binary nature of listing languages / tools on your resume/CV.  Essentially, the standard seems to be that if you got "Hello World" to compile and run in a language, than it is OK to list it on your resume/CV.

As it happens, the C version of "Hello, World!" also compiles and runs in C++.  So, absent any other information, all that seeing "C++" on a resume tells me is that this person knows enough C to get "Hello, World!" running, and knows that most C programs will compile in C++.

Given that, I'm going to need to probe that a little bit on the interview.  I probably wouldn't do so by asking a "Yes/No" "Do you know the difference?" question, in short because it has an obvious "right" answer.  I would probably ask the candidate which language she liked better, why, and if there were any advantages to the one she didn't pick.


问:
What are the main components, technologies, and features of the next generation of web applications?
What's next in the web industry, as social media reaches a plateau, what are the next milestones in this "experiment"?

I guess I'm looking for in depth opinions on what's next in our beloved industry? What's beyond facebook, wikis, collaboration, shiny buttons, and interactive instantaneous communications?

What will drive the next dot com boom?

答:
Kevin Kelly gave a tedtalk on the subject, titled "Predicting the next 5,000 days of the web." He has some interesting theories.

(The projections start about eight minutes into the video.)


答:
This co-worker is your FRIEND which you continue to have close contact after the leaving?
If yes, talk about that if/when you are taking beers on the bar.

Otherwise, why bother?

PS.: On the NDA thing, what is the secret here? Mr X is the one that wrote the code anyway and if the leaving is recent, the software continue on the same level of disclosure.

Things would be different if this talk happens 3 years after the leaving and you tell things that he wouldn't have to know except for you...


问:
Where to start when digging into an existing J2EE codebase?
I work for a company that produces enterprise applications to be used by schools and districts to manage all of their tests and standards data. Their existing application is written in J2EE and is very large. I personally am a seasoned PHP and Ruby = RoR developer and I have been asked to attempt to implement easily added but crucial features to an existing J2EE codebase. I am very familiar with Java SE and know the architecture of a web application well.

What I am asking for is, will this suffice for the task ahead and what tips can you give me in digging into the code base and actually efficiently adding these new features? Is there anything important I need to know before beginning and what can I expect in terms of problems and issues coming from a Java SE, PHP, RoR background?

Time isn't too much of an issue, I should have plenty of time to familiarize myself with J2EE.Please also note, syntax will not be a problem here.

答:
Java EE is very broad. There are a lot of libraries and frameworks out there, so my suggestion would be to get to know the ones used by the application. At the very least understand the problems they are solving and how they are solving them. Some concepts will be familiar, others will take more time to understand.

Questions to ask yourself:

Are you using servlet engine (Tomcat) or a full enterprise server (JBoss, WebLogic)? If an enterprise server, figure out which features of the server the application is using, and which ones are being outsourced to other frameworks or libraries. At the very least, understand what a Servlet is and how they are configured and managed by the server itself. Understand what WAR (and possibly EAR) files are, and how the files in them are structured.

Is there a dependency injection framework such as Spring or Guice? If there is, these frameworks will likely dictate much about how the application is structured. Get to know them well.

How is database persistence handled? Does it use plain SQL, Hibernate (or some other JPA implementation), or something completely different? It's likely that there will be some things to learn in this area, especially if a DI framework is used.

Is it using plain servlets and JSPs or, is it using some other web framework? If there is a DI framework, it is likely that the web framework is configured with it. Figure out how objects (such as HTTP requests) are scoped in relation to the rest of the application.

If the application is not using JSPs, then it's likely using some other template engine such as Velocity or Freemarker. Even if it is using JSPs, some web frameworks have their own JSP tags and expect you to use them.

I think those are all the major points to consider when diving into a Java EE app for the first time.


答:
There is logic that must must live in the database, such as RI and PK uniqueness check.

The good point about extra logic in the data layer, is that creating code in stored procedures simplifies the the client code significantly and may let you forget about a middle tear altogether if scalability is not the primary concern. It could also reduce the trips between the calling code and the database in the 'happy scenarios/cases'. In addition, as you have identified, it allows 'the enterprise' to share the logic. The downside is that, the more code you put in your data layer, the more your application would be tied to the database and its vendor. You will need the skill in both your front end and backhand in your team. If your team is OO centric, they may not enjoy the SP procedural nature. For example, the ease of using objects in LINQ, may have to be substituted for using experience in SQL. I also think that when you have stored procedure you many not be able to scale your application by adding database servers, but I am not sure about this point. If this is a concern, you may need to research it. You may also be interested in this post: arguments-for-against-business-logic-in-stored-procedures

Edit, It may worth mentioning that version control may be more difficult with code distributed in more than 1 environment.

Title: Handle all authentication logic in database or code?

Body:
We're starting a new(ish) project at work that has been handed off to me. A lot of the database sided stuff has been fleshed out, including some stored procedures. One of the stored procedures, for example, handles creation of a new user. All of the data is validated in the stored procedure (for example, password must be at least 8 characters long, must contain numbers, etc) and other things, such as hashing the password, is done in the database as well.

Is it normal/right for everything to be handled in the stored procedure instead of the application itself?

It's nice that any application can use the stored procedure and have the same validation, but the application should have a standard framework/API function that solves the same problem. I also feel like it takes away the data from the application and is going to be harder to maintain/add new features to.


问:
Is unit testing development or testing?
I had a discussion with a testing manager about the role of unit and integration testing. She requested that developers report what they have unit and integration tested and how. My perspective is that unit and integration testing are part of the development process, not the testing process. Beyond semantics what I mean is that unit and integration tests should not be included in the testing reports and systems testers should not be concerned about them. My reasoning is based on two things.

Unit and integration tests are planned and performed against an interface and a contract, always. Regardless of whether you use formalized contracts you still test what e.g. a method is supposed to do, i.e. a contract.

In integration testing you test the interface between two distinct modules. The interface and the contract determine when the test passes. But you always test a limited part of the whole system. Systems testing on the other hand is planned and performed against the system specifications. The spec determines when the test passes.

I don't see any value in communicating the breadth and depth of unit and integration tests to the (systems) tester. Suppose I write a report that lists what kind of unit tests are performed on a particular business layer class. What is he/she supposed to take away from that?

Judging what should and shouldn't be tested from that is a false conclusion because the system may still not function the way the specs require even though all unit and integration tests pass.

This might seem like useless academic discussion but if you work in a strictly formal environment as I do, it's actually important in determining how we do things. Anyway, am I totally wrong?

答:
It is worth mentioning the approach discussed in the book "How Google Tests Software": Testing and Quality Control is everybody's responsibility, and the standards are rigorous.

The real role of what is traditionally called the "Testing" department, is actually developer productivity; i.e. automation to enable the organization to reach the required level of rigor economically.

Title: Is unit testing development or testing?


问:
Is beginner knowledge of Java enough to develop for Android?
I just finished the book "Tech Yourself Java in 24 Hours, 6th Edition" I have an understanding of the language (by understanding I mean, the basics and everything covered in the book) and I have been experimenting and building little things with my knowledge. I want to learn about Android and was wondering if I need to increase my knowledge in Java before moving on to Android or can I just go straight to Android?</p>

答:
Learn by doing: Jump straight into Android; follow the tutorials and Google all the things you do not understand.

It will be laborious work at first, but will speed up after a few days of study.


问:
Relationship between C#, .NET, ASP, ASP.NET etc
I'm really unclear on the difference between C#, C#.NET and the same for ASP and other '.NET' languages.

From what I understand, .NET is a library/framework of... things. I think they're essentially access to Windows data such as form elements etc, but that doesn't seem to apply for ASP.NET.

In addition, I see people calling themselves '.NET' developers. Does this mean they're fluent in C#, ASP and other languages?

Finally, I never see C# without .NET attached. Is C# tied that closely to .NET as to be unusable without it?

In summary: what exactly does .NET provide? How does it relate to C# and ASP etc? What does 'a .NET developer' mean? And finally, why do you never see C# without .NET?

[As an aside, I realise these are multiple questions, but I think they are very inter-related (or at least that is the impression that browsing Programmers / SO etc has given me)].

答: the other answers do a good job of explaining what each technology, but I think they miss one of the major reasons for confusion. C# and C#.NET are essentially synonymous, however VB.NET and VB are different and ASP and ASP.NET are also different. VB generally refers to VB6 and older, and ASP refers to classic ASP. These technologies were radically redesigned with the release of the .NET framework and rather than come up with new names for products Microsoft appended .NET to pretty much everything, but C# was also new so both names really refer to the same thing.</p>


答:
The basics of all web related in the Java world is the Servlet API and its specification.  If you do not know it, now is a very good time to learn it.  For Java EE you must stay away from Servlet 3.0 (the newest) and only look at 2.5 or even 2.4.

Then write a few servlets (image generation are usually good candidates for this) and then look into how to write Java web apps.  This includes JSP-pages and WAR-deployments.   Get familiar with that - especially with library jars, and JSP taglibs etc.  Learn how to debug them in your IDE (very important).

The full Java EE stack is perhaps 10 or 20 times larger to learn than this.  At that step you can determine if you are willing to go the rest of the way.

Title: Where to start when digging into an existing J2EE codebase?

Body:
I work for a company that produces enterprise applications to be used by schools and districts to manage all of their tests and standards data. Their existing application is written in J2EE and is very large. I personally am a seasoned PHP and Ruby = RoR developer and I have been asked to attempt to implement easily added but crucial features to an existing J2EE codebase. I am very familiar with Java SE and know the architecture of a web application well.

What I am asking for is, will this suffice for the task ahead and what tips can you give me in digging into the code base and actually efficiently adding these new features? Is there anything important I need to know before beginning and what can I expect in terms of problems and issues coming from a Java SE, PHP, RoR background?

Time isn't too much of an issue, I should have plenty of time to familiarize myself with J2EE.Please also note, syntax will not be a problem here.


问:
Is it possible to develop apps with Kendo UI to submit to iOS App Store?
The number of platforms I have to develops apps for is increasing and It brings me lots of stress to learn new technologies for each target platform. I found out that Telerik's Kendo UI is very good to build websites that look and feel native on mobile platforms (e.g. iOS and Android). My question is, is it possible to build HTML5 apps to deploy them on iTunes App Store and Google Play? Please note that I am eager to know the possibility of creating apps (complete apps bundled in standard format of Apple and Google for distribution in their respective mobile app markets) but not websites.</p>

答:
The best advice I can give you is to ask the folks who make Kendo UI.

In general, though, unless the framework targets the web browser specifically, then it's likely their tools compile whatever front-end HTML-like code you've written to native code for the target devices. So unless the native code violoates some other rule pertaining to the "app store" in question, then there shouldn't be an issue. The only other option is to bundle some sort of browser-like thing that acts like a VM for the target device.


答: Web 3.0 is just made up term like web 2.0 that means nothing. Just throw around a few cliches like HTML5, Cloud computing and you will be there.</p>

Title: What are the main components, technologies, and features of the next generation of web applications?

Body:
What's next in the web industry, as social media reaches a plateau, what are the next milestones in this "experiment"?

I guess I'm looking for in depth opinions on what's next in our beloved industry? What's beyond facebook, wikis, collaboration, shiny buttons, and interactive instantaneous communications?

What will drive the next dot com boom?


问:
Which would be a better way to load data via ajax
I am using google maps and returning html/lat/long from my MySQL database

Currently

A user picks a business category e.g; "Video Production".

an ajax call is sent to a CodeIgniter controller

the Controller then queries the db, and returns the following data via JSON

Lat/Long of the marker

HTML for the popup window

this is approximately 34 rows in the database across two tables per business

the ajax call receives this data and then plots the marker along with the html onto the map

The data that is returned from the controller is one big json object... This is done for all businesses that exist in the Video Production category (currently approx 40 businesses). As you can see, pulling this data for multiple categories (100s of businesses) can get very very taxing on the server.

My question is

Would it be more beneficial to modify the process flow as such:

a user picks a business category e.g; "Video Production".

an ajax call is sent to a CodeIgniter controller

the controller then queries the database for the location base information

lat/long

level (used to change marker icon color)

This would be a single row per business with several columns

the ajax call receives this data and then plots the marker on the map

when the user clicks a marker an ajax call is sent to a CodeIgniter Controller

the controller queries the database for the HTML and additional data based on business_id

and if not, what are some better suggestions to this problem?

In summary this means rather than including the HTML and additional data along for each business, only submitting minimal location information and then re-query for that information when each business marker is clicked.

Potential Downsides

longer load times when a user clicks a marker icon

more code??

more queries to the database

答:
Unless you notice that this is causing some sort of performance issue, I would leave as is.

Generally, network round trips are the slowest item, and should be minimized as much as possible.  I would only worry about such an optimization once you get to the point where there is an observable performance issue.  Without profiling, it is impossible to tell which method will be truly faster, and it could be different for each user.  JSON is a fairly terse format,  and a lot of stuff can be condensed.

Also, if you do find that performance is an issue, you might want to look into client side templating (such as KnockoutJS, jQuery templates, Handlebars, Mustache, ...) for the popup window, assuming that the content is based off of a template.  This may allow you to minimize the data sent.


答:
Since only one answer mentions Mono without going into detail:

Though C# as a language was originally developed at Microsoft as part of .NET Framework, it was later standardised by ECMA, meaning that independent standard-compliant implementations of the language can be developed, and indeed they were. The most prominent of those is Mono.

Mono is an open source implementation of an ECMA standard compliant set of tools compatible with .NET Framework, including a C# compiler and a CLI implementation (Mono Runtime, the equivalent of Microsoft's CLR - the virtual machine of .NET Framework). It's aim is to run .NET applications cross-platform. As of today, it supports C# 4.0 and substantial part of .NET Framework features. In addition to mirroring Microsoft implementation, the Mono team is also making innovations of its own.

So, yes, it's possible and feasible to work in C# without .NET. It's unlikely however that Mono will be able to rival Microsoft's market share and .NET Framework's position, not now, and not in the immediate future.

Title: Relationship between C#, .NET, ASP, ASP.NET etc

Body:
I'm really unclear on the difference between C#, C#.NET and the same for ASP and other '.NET' languages.

From what I understand, .NET is a library/framework of... things. I think they're essentially access to Windows data such as form elements etc, but that doesn't seem to apply for ASP.NET.

In addition, I see people calling themselves '.NET' developers. Does this mean they're fluent in C#, ASP and other languages?

Finally, I never see C# without .NET attached. Is C# tied that closely to .NET as to be unusable without it?

In summary: what exactly does .NET provide? How does it relate to C# and ASP etc? What does 'a .NET developer' mean? And finally, why do you never see C# without .NET?

[As an aside, I realise these are multiple questions, but I think they are very inter-related (or at least that is the impression that browsing Programmers / SO etc has given me)].


问:
Pattern for Accessing MySQL connection
We have an application which is C++ trying to access MySQL database.

There are several (about 5 or so) threads in the application (with Boost library for threading) and in each thread has a few objects, each of which is trying to access Database for its' own purpose. It has a simple ORM kind of model but that really is not an important factor here.

There are three potential access patterns i can think of:

There could be single connection object per application or thread and is shared between all (or group). The object needs to be thread safe and there will be contentions but MySQL will not be fired with too many connections.

Every object could initiate connection on its own. The database needs to take care of concurrency (which i think MySQL can) and the design could be much simpler. There could be two possibilities here.
a. either object keeps a persistent connection for its life OR
b. object initiate connection as and when needed.

To simplify the contention as in case of 1 and not to create too many sockets as in case of 2, we can have group/set based connections. So there could be there could be more than one connection (say N), each of this connection could be shared connection across M objects.

Naturally, each of the pattern has different resource cost and would work under different constraints and objectives.

What criteria should i use to choose the pattern of this for my own application?

What are some of the advantages and disadvantages of each of these pattern over the other?

Are there any other pattern which is better?

PS: I have been through these questions:

mysql, one connection vs multiple
and

MySQL with mutiple threads and processes

But they don't quite answer exactly what i am trying to ask.

答:
There could be single connection object per application or thread and is shared between all (or group). The object needs to be thread safe and there will be contentions but MySQL will not be fired with too many connections.

This is essentially doing what the server is already doing, on client side. Unless the client side may fire a crazy number of connections and you don't have control on it, better just create connections and let server handles the synchronization.

Your second option does not necessarily incur a lot of connections. Take a look at Dynamic Scoping. It's easy to implement dynamic scoping in C++ so you basic have one connection per thread.

The 3rd option is more or less as opposite to option 1 - if you stick with one connection per thread approach, why not simply restrict the number of threads?

Title: Pattern for Accessing MySQL connection


问:
Is embedded programming closer to electrical engineering or software development?
I am being approached with a job for writing embedded C on micro controllers. At first I would have thought that embedding programming is too low on the software stack for me, but maybe I am thinking about it wrong.

Normally I would have shrugged off an opportunity to write embedded code, as I don't consider myself an electrical engineer. Is this a bad assumption? Am I able to write interesting and useful software for embedded systems, or will I kick myself for dropping too low on the software stack?

I went to school for computer science and really enjoyed writing a compiler, thinking about concurrent algorithms, designing data structures, and developing frameworks. However, I am currently employed as a web developer, which doesn't scream the interesting things I just described. (I currently deal with issues like: "this check box needs to be 4 pixels to the left" and "this date is formatted wrong".)

I appreciate everyone's input. I know I have to make the decision for myself, I just would like some clarification on what it means to be a embedded programmer, and if it fits what I find to be interesting.

答:
In my experience, one gets better results approaching embedded system software development with a "software developer" hat rather than an "electronics engineer" hat. (practices like TDD & CI are less common in hardware engineering)

On the other hand, I think that the experience of developing for an embedded system makes one a better; more well-rounded software developer.