答:
Let's look at what a CMS is for:

From http://en.wikipedia.org/wiki/Content_management_system

A content management system (CMS) is a computer application that
  allows publishing, editing and modifying content, organizing, deleting
  as well as maintenance from a central interface.

Now, there have been some moves by some CMS providers (like WordPress and Drupal) to enable some PHP coding through the content management interface. This is a terrible idea - as your experience showed.

A good CMS has a well-documented API (I know Drupal does) and well-documented approaches to writing modules and plugins to enhance the behaviour of the CMS framework.

As for you question - a developer should use a CMS for when they want publish content simply and efficiently - like a developer who blogs. Or if you're a solo developer working for an ecommerce store - use a CMS with modules to support ecommerce, and you will have a much simpler time managing the product line.

Ultimately, as a solo developer, you may choose not to use an off-the-shelf CMS and write a custom script framework. But eventually, I'm pretty sure you will end up developing something that looks and behaves like a CMS.

Title: Is there a common reason a more technical/traditional web developer should use a CMS for his/her own purposes?

Body:
Note

When this question was originally posted months ago, I worded it to sound relatively neutral.  Whereas it has been answered in a way that seems probably valid and that I would be tempted to accept, I think I just really need to update the question to bring my basic concern front-and-center at the beginning, leaving all the earlier, more neutral contents in place:

As far as I have seen, CMSs get in the programmer's way a lot for what seems to be little to no benefit for a developer.  Maybe a journalist needs this kind of hand-holding to build a website, but when I tried a CMS out myself (it was WordPress), there was zero perceivable benefit, even in terms of content management!  Do a programmer, an artist, and a journalist all need to work together in a way that the artist and journalist can change their content without involving the developer?  Fine - that's why you put content in its own separate files and code accordingly.  Do you need to load the same, updated contents in multiple places? Use scripting languages and such to accomplish this. You do not need a CMS that disables and hinders the programmer in many ways in order to do this.

It was not my intention to put something like this at the top, but I think part of the problem I'm having understanding this is not being communicated well below, so I've put this at the top for clarity.  If someone can answer this in a way I can understand, I'll pretty much accept their answer.

The Concept of a CMS

The basic idea behind a CMS is to combine web development, artistry, journalism, and so on into a single, user-friendly* aggregate, by which an organization can not only develop a website, but also better coordinate such an effort and potentially more easily automate certain parts of the process.

.

.

.

*...Well..."user-friendly" seems to be somewhat conditional on there being a team of people working together on a project, particularly if they are not all programmers.

Background behind the Question

I remember being tested by an organization some time ago to see if I could write something in particular and get it up and working on a cloned WordPress instance, and part of this had to do with the fact that I had not previously been exposed to WordPress.  In fact, this was my first time using a CMS, and I developed a little bit of a bad taste for the concept.  What should have been a relatively trivial programming assignment with HTML, CSS, JavaScript, and PHP turned out to be a minefield just trying to circumnavigate all sorts of seemingly unreasonable restrictions, assumptions, and so on built in to the CMS.

I'm going to come back to the positive side of a CMS in just a second, but first some example negatives in the case of WordPress:

PHP was not supported natively.  If memory serves me correctly, it took a plugin to enable it, not a configuration change.

It was unnecessarily difficult to read, let's say, a list of countries out of a json file.   The file had to be stored in an unnatural location to make WordPress allow it to be read by JavaScript, and the simple fact that the file's extension was .json was something WordPress felt was "too dangerous" or "too complicated and low-level" for a normal programmer to ever want to deal with.

Line breaks were inserted into the HTML, without user feedback to the developer, even when the HTML was written directly by using the code editor.  And I know there's a setting in the WordPress configuration to change this, but aside from having to run back to the system administrator to get read/write access to the installation files to change it, their documentation gives you two function calls to insert into a certain file without telling you where in that file to insert them.  Put them in the wrong place (the file is thousands of lines long), and WordPress won't work.  - This breaks JavaScript containing blank lines for formatting.

And before it was over with, there got to be maybe 20 or so different completely unnatural roadblocks I had to get around to implement a very basic contact form.

So now the positive side:

Months later I attended a WordCamp with an open mind, hoping to find out why so many people would prefer this over "ordinary" web development.  The basic answer I got out of that is more-or-less the following:

You're not always going to work with other programmers.  Especially if you have a somewhat popular site, then artists, journalists, bloggers, musicians, and other kinds of talented people will either become a part of the team or work alongside it.  Oftentimes your non-programmer clientele will need to make frequent changes to the website (sometimes altering the way data is presented, not just the data itself), and having a nice, big GUI that acts like a server with multiple users that manages this - and helps automatically integrate content into code - can really save time, trouble, and stress.

Alright...So what if you don't have non-programmer artists, journalists, bloggers, etc. consistently involved?  And in particular, what if you're the only one who's really making very many modifications to the site?

Yes, you can separate content from presentation through a CMS, but if you code like you're supposed to, it'll already be quite separate in your files and site structure.

And yes, people keep saying there are all sorts of plugins, but is that any better to a programmer than there being all sorts of SDKs in more code-style development platforms?  What's more is that, at least in the case of WordPress, many of these plugins are there for no other reason than to get past serious roadblocks imposed specifically by the fact that you're using the CMS (such as points 1 and 2).

Personal Opinion

I'm not sold very much on the idea of a CMS at all, even when coordinating with more artist-like people.  It's too much trouble for what appears to be too little gain.  As a general rule, every layer of abstraction costs you the ability to do and to control certain things you may want to utilize, and a good programmer will mostly separate content from code anyway.

This is enough to allow clients to just copy and paste files with the content over an FTP or something without assistance from the developer.

I know my experience has only been with WP, but supposedly, 20% of web developers these days use it.  I honestly saw very little reason to use a CMS, at least until they really improve...BUT I am trying to keep an open mind and listen for things I may have missed.

The Question

So something I have been wanting to ask on here for a while, because nobody has explained this very well:

The idea of a CMS is fairly popular right now.  Many people almost automatically flock to one, even if they are experienced web developers accustomed to using text editors.  Why would you want to do this, thereby introducing certain kinds of obstacles, in situations where you're not dealing with a bunch of people who are not programmers?


问:
Is there a common reason a more technical/traditional web developer should use a CMS for his/her own purposes?
Note

When this question was originally posted months ago, I worded it to sound relatively neutral.  Whereas it has been answered in a way that seems probably valid and that I would be tempted to accept, I think I just really need to update the question to bring my basic concern front-and-center at the beginning, leaving all the earlier, more neutral contents in place:

As far as I have seen, CMSs get in the programmer's way a lot for what seems to be little to no benefit for a developer.  Maybe a journalist needs this kind of hand-holding to build a website, but when I tried a CMS out myself (it was WordPress), there was zero perceivable benefit, even in terms of content management!  Do a programmer, an artist, and a journalist all need to work together in a way that the artist and journalist can change their content without involving the developer?  Fine - that's why you put content in its own separate files and code accordingly.  Do you need to load the same, updated contents in multiple places? Use scripting languages and such to accomplish this. You do not need a CMS that disables and hinders the programmer in many ways in order to do this.

It was not my intention to put something like this at the top, but I think part of the problem I'm having understanding this is not being communicated well below, so I've put this at the top for clarity.  If someone can answer this in a way I can understand, I'll pretty much accept their answer.

The Concept of a CMS

The basic idea behind a CMS is to combine web development, artistry, journalism, and so on into a single, user-friendly* aggregate, by which an organization can not only develop a website, but also better coordinate such an effort and potentially more easily automate certain parts of the process.

.

.

.

*...Well..."user-friendly" seems to be somewhat conditional on there being a team of people working together on a project, particularly if they are not all programmers.

Background behind the Question

I remember being tested by an organization some time ago to see if I could write something in particular and get it up and working on a cloned WordPress instance, and part of this had to do with the fact that I had not previously been exposed to WordPress.  In fact, this was my first time using a CMS, and I developed a little bit of a bad taste for the concept.  What should have been a relatively trivial programming assignment with HTML, CSS, JavaScript, and PHP turned out to be a minefield just trying to circumnavigate all sorts of seemingly unreasonable restrictions, assumptions, and so on built in to the CMS.

I'm going to come back to the positive side of a CMS in just a second, but first some example negatives in the case of WordPress:

PHP was not supported natively.  If memory serves me correctly, it took a plugin to enable it, not a configuration change.

It was unnecessarily difficult to read, let's say, a list of countries out of a json file.   The file had to be stored in an unnatural location to make WordPress allow it to be read by JavaScript, and the simple fact that the file's extension was .json was something WordPress felt was "too dangerous" or "too complicated and low-level" for a normal programmer to ever want to deal with.

Line breaks were inserted into the HTML, without user feedback to the developer, even when the HTML was written directly by using the code editor.  And I know there's a setting in the WordPress configuration to change this, but aside from having to run back to the system administrator to get read/write access to the installation files to change it, their documentation gives you two function calls to insert into a certain file without telling you where in that file to insert them.  Put them in the wrong place (the file is thousands of lines long), and WordPress won't work.  - This breaks JavaScript containing blank lines for formatting.

And before it was over with, there got to be maybe 20 or so different completely unnatural roadblocks I had to get around to implement a very basic contact form.

So now the positive side:

Months later I attended a WordCamp with an open mind, hoping to find out why so many people would prefer this over "ordinary" web development.  The basic answer I got out of that is more-or-less the following:

You're not always going to work with other programmers.  Especially if you have a somewhat popular site, then artists, journalists, bloggers, musicians, and other kinds of talented people will either become a part of the team or work alongside it.  Oftentimes your non-programmer clientele will need to make frequent changes to the website (sometimes altering the way data is presented, not just the data itself), and having a nice, big GUI that acts like a server with multiple users that manages this - and helps automatically integrate content into code - can really save time, trouble, and stress.

Alright...So what if you don't have non-programmer artists, journalists, bloggers, etc. consistently involved?  And in particular, what if you're the only one who's really making very many modifications to the site?

Yes, you can separate content from presentation through a CMS, but if you code like you're supposed to, it'll already be quite separate in your files and site structure.

And yes, people keep saying there are all sorts of plugins, but is that any better to a programmer than there being all sorts of SDKs in more code-style development platforms?  What's more is that, at least in the case of WordPress, many of these plugins are there for no other reason than to get past serious roadblocks imposed specifically by the fact that you're using the CMS (such as points 1 and 2).

Personal Opinion

I'm not sold very much on the idea of a CMS at all, even when coordinating with more artist-like people.  It's too much trouble for what appears to be too little gain.  As a general rule, every layer of abstraction costs you the ability to do and to control certain things you may want to utilize, and a good programmer will mostly separate content from code anyway.

This is enough to allow clients to just copy and paste files with the content over an FTP or something without assistance from the developer.

I know my experience has only been with WP, but supposedly, 20% of web developers these days use it.  I honestly saw very little reason to use a CMS, at least until they really improve...BUT I am trying to keep an open mind and listen for things I may have missed.

The Question

So something I have been wanting to ask on here for a while, because nobody has explained this very well:

The idea of a CMS is fairly popular right now.  Many people almost automatically flock to one, even if they are experienced web developers accustomed to using text editors.  Why would you want to do this, thereby introducing certain kinds of obstacles, in situations where you're not dealing with a bunch of people who are not programmers?

答:
A good CMS is a force multiplier for a web developer.  It gets a basic website up & running very quickly enabling you to concentrate on developing modules (in PHP if you pick the right one) that add the customer specific functionality.  Basically you do more for your customer in less time but (hopefully) get paid the same - because you're being paid for results, right, not billed hours?

To pick Drupal as a good example, it is not actually a CMS.  It is better to think of it as a web development framework that happens to ship out of the box with a reference implementation of a CMS.

What you were doing with Wordpress was the wrong idea and it gave you a bad impression.  You should have written a Wordpress plugin in PHP rather than trying to embed PHP in pages which is what you seem to have done based on your description

ContentLicense: CC BY-SA 3.0


问:
Why does CI stipulate that we should be able to rollback to any version of a software?
I was reading the book "Continuous delivery, reliable software deployments through build, tests and deployment automation ". And the author mentions that one should be able to rollback to any version of a software with one click.

I am wondering if this is really useful, and especially in the following scenarios :

You are working on web projects. Sounds to me that in this case, you don't really need the ability to rollback to any previous version. Being able to rollback the current release should be enough. Once it's deployed and working, why would you ever want to go back to a previous version ?

And actually this argument holds true if you are working on desktop applications.

Perhaps I misunderstood what he means by "being able to rollback to any version".

Does he mean the production environment or the development environment ? If it's the later that would make more sense - even if I still find it kind of unecessary for the web, source control branching should do the trick for desktop applications.

And still if it's the later, do you think that using tools like Entity Framework Code First Migration that allow you to recreate the database from the source code is enough to say that we have reach this standard ? Because then, with source control, we'd even have the referential data that need to be seeded for this particular version after the database is created.

答: Never mind the current deployment, if you (or your customers) run a previous version you may need to get a snapshot of that version going to reproduce an issue for an incident or compare current undesirable behaviour to a previous build. That includes not just the application, but test data, and test details as well.</p>


答:
Apart from the reasons already mentioned, my main reason for choosing, or writing, a CMS is so that the web site can be frequently updated without having to call on me. I am a programmer not a copy writer, you would not ask me to write your advertising copy for a magazine after all. The single biggest problem that I have faced over the years was to actualy get the content from the client in the first place. So providing them with the ability to enter and edit the content once the site was finished, finished from my point of view that is, is immensely attractive.

Relevent, accurate and frequently updated content is the best way to improve one's natural ranking on search engines. A CMS is the best way to acheive this, unless you enjoy copy/paste from word/email to html yourself that is. Personally it would drive me crazy: I am a programmer not a copy typist.


问:
Why are objects instantiated this way?
Some times I see an object instantiated this way.

```<code>ICustomer oCustomer = new Customer
</code>```

Obvious but the Customer class is implementing ICustomer interface in this example. Are there any advantages of instantiating an object that way? From my understanding, if a class in implementing an interface it is already following the contract. What is the name of that practice and is there a disadvantage of instantiating an object "normal"(what I usually do) way? I know there are already some existing questions out there, but they don't really highlight the advantages and disadvatages

Interface instantiation vs class instantiation

```<code>Customer oCustomer = new Customer
</code>```

答:
As long as your code looks as simple like this

```<code>void ExampleFunc()
{
   ICustomer oCustomer = new Customer();
   oCustomer.Method1OfICustomer();
   oCustomer.Method2OfICustomer();
   // ...
}
</code>```

there is no semantic difference - you can exchange "ICustomer" by "Customer", and the behaviour will stay identical. In this example, however, it could fulfill already some documentary purposes. The first line may express the design decision of the programmer to avoid adding calls like

```<code>   oCustomer.MethodNotPartOfICustomer();
</code>```

in the future, but in fact, when this kind of call is needed later on, one could also change the "new" line, or add the missing method to the ICustomerlater.

In fact, the use of interfaces, as the term implies, will start to make more sense when there is some real "interfacing" involved - interfacing between functions, classes, components. For example, the function

```<code>void ExampleFunc(ICustomer oCustomer)
{
   oCustomer.Method1OfICustomer();
   oCustomer.Method2OfICustomer();
   // ...
}
</code>```

is probably more generic than

```<code>void ExampleFunc(Customer oCustomer)
{
   oCustomer.Method1OfICustomer();
   oCustomer.Method2OfICustomer();
   // ...
}
</code>```

since it will work with any class implementing the ICustomer interface, not just Customer. For example, for testing purposes one could think of passing a "CustomerMock" into the function, something you cannot do with the second variant.

Title: Why are objects instantiated this way?

Body:
As long as your code looks as simple like this

void ExampleFunc()
{
   ICustomer oCustomer = new Customer();
   oCustomer.Method1OfICustomer();
   oCustomer.Method2OfICustomer();
   // ...
}

there is no semantic difference - you can exchange "ICustomer" by "Customer", and the behaviour will stay identical. In this example, however, it could fulfill already some documentary purposes. The first line may express the design decision of the programmer to avoid adding calls like

   oCustomer.MethodNotPartOfICustomer();

in the future, but in fact, when this kind of call is needed later on, one could also change the "new" line, or add the missing method to the ICustomerlater.

In fact, the use of interfaces, as the term implies, will start to make more sense when there is some real "interfacing" involved - interfacing between functions, classes, components. For example, the function

void ExampleFunc(ICustomer oCustomer)
{
   oCustomer.Method1OfICustomer();
   oCustomer.Method2OfICustomer();
   // ...
}

is probably more generic than

void ExampleFunc(Customer oCustomer)
{
   oCustomer.Method1OfICustomer();
   oCustomer.Method2OfICustomer();
   // ...
}

since it will work with any class implementing the ICustomer interface, not just Customer. For example, for testing purposes one could think of passing a "CustomerMock" into the function, something you cannot do with the second variant.


答:
This question goes to the very heart of what Object-Orientation means. Simply put, in a language like Java, C# or Visual Basic.NET, classes (and structs) define Abstract Data Types and interfaces define Objects. As soon as you have a class or struct as a type (i.e. the type of a local variable, field, property or a method parameter, a method return type, a type argument to a generic class or interface, the target of a cast operator or the argument of an instanceof operator), you are not doing object-oriented programming.

The only thing you can use for a type, is an interface, you can not use classes or structs (and certainly not primitives in a language like Java which has them). The only place where a class or struct is allowed, is right next to the new operator: classes and structs are merely factories for objects.

This is explained much better than I could ever hope to achieve in On Understanding Data Abstraction, Revisited by William R. Cook. It uses Java for the examples, but it applies just as well to C# or any other language.

So, the simple answer is: if you weren't instantiating an object this way, it wouldn't be an object, but an instance of an abstract data type.

Title: Why are objects instantiated this way?

Body:
Some times I see an object instantiated this way.

```<code>ICustomer oCustomer = new Customer
</code>```

Obvious but the Customer class is implementing ICustomer interface in this example. Are there any advantages of instantiating an object that way? From my understanding, if a class in implementing an interface it is already following the contract. What is the name of that practice and is there a disadvantage of instantiating an object "normal"(what I usually do) way? I know there are already some existing questions out there, but they don't really highlight the advantages and disadvatages

Interface instantiation vs class instantiation

```<code>Customer oCustomer = new Customer
</code>```


问:
Executing scripts in parallel based on dependency tree
We have an app that is using a fairly simple stack (Linux, PHP, Oracle, Shell Scripts, etc).

We have a series of scripts that need to be executed:

/scr/app1/start.sh

/scr/app2/start.php

/scr/app3/kickoff.py

/scr/app4/test.sh

The dependency rules are as follows:

app1 must be run first

app2 then must be run next

app3 and app4 can be run in parallel

That being said, I am looking to capture the following from ALL scripts:

exit codes (used to determine success of failure / breakage of chain)

standard out and/or standard error

The solution does not necessarily have to be written in PHP, it just has to work. Node.js / io.js is part of our build stack so we are comfortable building there.

Basically the parallelism is the real challenge that I see. What is the best approach to this problem while satisfying all of the requirements?

答:
I'd use node.js to initiate each of the tasks that need to be done, and I would manage your parallel sequencing of things with a promise library like Q.

With Q, you can basically say:

1) Do all these things at the same time and let me know when you are done with all of them

2) Then, now that you've finished all those things, do something else either by itself or at the same time as some other things (my choice)

You can keep chaining like this, and each "chain-link's stuff" gets done roughly in parallel, but nothing gets started until all prerequisite tasks have completed.

Scroll down this page for examples:
https://github.com/kriskowal/q


问:
Optimizing XML based protocol
We have recently replaced binary based communication protocol with XML one (between browser based client and server). The implementation is almost complete, however I am looking for ways to improve its performance both for faster transmission and parsing. Any ideas ? Please post link along with the answer.</p>

答:
I presume this is a web service and using C++ as a mod extenstions to a web server rather than writing your own.

To speed up transfer you could be able to enable gzip compression on the web server, this is relatively straight forward in all modern web servers.

Parsing could be sped up by:

Reducing node count - can the data being set be reduced, can some be inferred from others?

If you are using a DTD/XSD, have a local copy and resolve to this rather than necessarily always pulling it from the public location. I have seen an XML library pull it from the public location each time which slowed down parsing considerably.

ContentLicense: CC BY-SA 2.5

Title: Optimizing XML based protocol


问:
Using static classes to define methods for handling POCO class objects
I am pretty new to the OOP paradigm and for this current project of mine, I need to design and develop a web application backend in .NET MVC using C#.

A friend of mine told me that the class objects we use mostly for passing information from one layer/function to other should be as small as possible, which is a sound argument and hence I also presumed that we better not have methods in this class and store only properties. This requires me to define another class that would have some methods defined solely to do operations on this class's objects.

I was wondering if making this whole method-only class a static class is good option or not? Or may be make these methods a part of the property-only class but make them static.

Am I thinking on the right track? Are there any cons of using static which I should be aware of? Any costs associated with it?

答: A method on a class in c# doesnt actually take any memory on an actual instance of the class. So every object you create of this class will still be the same size whether or not you added some extra methods to the class. You definitely should not create a new class to do these operations that are closely bound to your 'data-passing-class'.</p>


问:
Design question concerning proper and practical encapsulation
I have been working on refactoring old code and found a lot of instances of the following type of situation: There is a master object which we call "Application" and there is only one of these. The Application will create other objects called "Features" inside it depending on user input etc. The Feature object may have some methods that take void parameters but actually operate on or use some variables in the scope of Application. This is because the functions defined in class Feature are defined in the same project and include the header from Application (this is C++). Here is a rudimentary attempt to show a simple example pseudocode:

```<code>int main()
{
    Application theApp = new Application()

    the.App.someSetting = foo;
    the.App.someVariable = bar;

    the.App.RunSomeFeature();
}
// RunSomeFeature function def in class Application
void Application::RunSomeFeature()
{
    // create object of type feature
     Feature feature = new Feature();

    feature.SomeFunction(void)
}
// SomeFunction def in class Feature
void Feature::SomeFunction(void)
{
    // global variable from Application "creeping in"
    someLocalVariable = theApp.someSetting;
    otherLocalVariable = theApp.someVariable;
}
</code>```

I hope this illustrates somewhat what I mean. My goal is essentially to move the class "Feature" to some location outside the namespace of "Application" (to a dll for example) and I can not include Application header (since that would defeat the purpose of the separation). But since there are these types of globals everywhere in the old code this task is rather complicated. This may be a C++ thing for all I know that it is easy (or posible) to make this coding mistake but I am not sure.

This made me think of a few questions regarding OOP design. Well designed OOP code would only have completely autonomous classes and functions with all outside variables explicitly passed in? Even if one object will be created inside another? I can see that way the entire code would be much easier to internally "reshuffle". But sometimes there may be a lot of parameters to be passed and since "Feature" is created by "Application" anyway I see why my situation might arise. But code written as in the example implicitly joins class Application and Feature to the same overall "block" or scope and it takes line by line work sometime to separate them.

However the other extreme would be that each class is essentially almost an autonomous application in its own right (and this may go somewhat against the idea of inheritance). When I read about OOP design principles, I usually don't find this particular nuance talked about much or I just get the idea that everything should be basically autonomous but I find that in practice this is rarely truly so.

I see that this may be a bit open ended but any rules of thumb about at what level would we "completely encapsulate" in order to have pieces of code we can reshuffle easily? Or any design philosophy anyone would share about this type of situation?

答:
I can not include Application header (since that would defeat the purpose of the separation). But since there are these types of globals everywhere in the old code this task is rather complicated.

You just need to split the task into the correct steps, and then it is simple (though it may not be easy :) )

But sometimes there may be a lot of parameters to be passed and since "Feature" is created by "Application" anyway I see why my situation might arise.

Rule: things that are processed together should be grouped together.

Here's an example, for your feature code:

Original code

```<code>// RunSomeFeature function def in class Application
void Application::RunSomeFeature()
{
    // create object of type feature
     Feature feature = new Feature(this); // added this as a parameter
                                          // assuming Feature reads lots of data
                                          // from Application, to construct itself

    feature.SomeFunction(void)
}
</code>```

Step 1

Create a constructor that receives already constructed values for it's data members. If Feature is constructed using Application::arg1, Application::arg2, ..., Application::arg_n_, then you will need a Feature constructor that receives n arguments.

Step 2

Extract Feature into a separate class, and switch client code from calling Feature::Feature(const Application&) to calling Feature::Feature(arg1, arg2, ..., argn).

note: Because things that are processed together should be grouped together, consider writing feature like this:

```<code>struct FeatureData // or class
{
    // feature args are passed together, so we group them together, here:

    Arg1 arg1;
    Arg2 arg2;
    ...
    Argn argn;
};

class Feature
{
    Feature(FeatureData&& data); // call std::move on data.arg1, ... data.argn to populate feature

};
</code>```

(instead of having a Feature that receives n arguments).

Step 3

Update Application to either be a FeatureData specialization or construct a FeatureData instance when needed.

Step 4

Move Feature and FeatureData to a separate library.

I see that this may be a bit open ended but any rules of thumb about at what level would we "completely encapsulate" in order to have pieces of code we can reshuffle easily? Or any design philosophy anyone would share about this type of situation?

SOLID principles: In this case, the "I" stands for Interface Segregation (that is, do not use all of Application's public interface to pass arguments to constructors; separate the interface - into FeatureData and rest of Application, so you can use them separately).

Demeter's Law: a class should not know/have-access-to more than it needs to complete it's job (in this case, a Feature needs to know "a set of n values", not an Application object and "a set of n values").

Body:
I can not include Application header (since that would defeat the purpose of the separation). But since there are these types of globals everywhere in the old code this task is rather complicated.

You just need to split the task into the correct steps, and then it is simple (though it may not be easy :) )

But sometimes there may be a lot of parameters to be passed and since "Feature" is created by "Application" anyway I see why my situation might arise.

Rule: things that are processed together should be grouped together.

Here's an example, for your feature code:

Original code

// RunSomeFeature function def in class Application
void Application::RunSomeFeature()
{
    // create object of type feature
     Feature feature = new Feature(this); // added this as a parameter
                                          // assuming Feature reads lots of data
                                          // from Application, to construct itself

    feature.SomeFunction(void)
}

Step 1

Create a constructor that receives already constructed values for it's data members. If Feature is constructed using Application::arg1, Application::arg2, ..., Application::arg_n_, then you will need a Feature constructor that receives n arguments.

Step 2

Extract Feature into a separate class, and switch client code from calling Feature::Feature(const Application&) to calling Feature::Feature(arg1, arg2, ..., argn).

note: Because things that are processed together should be grouped together, consider writing feature like this:

struct FeatureData // or class
{
    // feature args are passed together, so we group them together, here:

    Arg1 arg1;
    Arg2 arg2;
    ...
    Argn argn;
};

class Feature
{
    Feature(FeatureData&& data); // call std::move on data.arg1, ... data.argn to populate feature

};

(instead of having a Feature that receives n arguments).

Step 3

Update Application to either be a FeatureData specialization or construct a FeatureData instance when needed.

Step 4

Move Feature and FeatureData to a separate library.

I see that this may be a bit open ended but any rules of thumb about at what level would we "completely encapsulate" in order to have pieces of code we can reshuffle easily? Or any design philosophy anyone would share about this type of situation?

SOLID principles: In this case, the "I" stands for Interface Segregation (that is, do not use all of Application's public interface to pass arguments to constructors; separate the interface - into FeatureData and rest of Application, so you can use them separately).

Demeter's Law: a class should not know/have-access-to more than it needs to complete it's job (in this case, a Feature needs to know "a set of n values", not an Application object and "a set of n values").


问:
Does path coverage guarantee finding all bugs?
If every path through a program is tested, does that guarantee finding all bugs?

If not, why not? How could you go through every possible combination of program flow and not find the problem if one exists?

I hesitate to suggest that "all bugs" can be found, but maybe that is because path coverage isn't practical (as it is combinatorial) so it isn't ever experienced?

Note: this article gives a quick summary of coverage types as I think about them.

答:
Well... yes actually, if every path “through” the program is tested. But that means, every possible path through the entire space of all possible states the program can have, including all variables. Even for a very simple statically compiled program – say, an old Fortran number cruncher – that's not feasible, though it can at least be imaginable: if you have just two integer variables, you're basically dealing with all possible ways to connect points on a two-dimensional grid; it actually looks a lot like Travelling Salesman. For n such variables, you're dealing with an n-dimensional space, so for any real program, the task is completely untractable.

Worse: for serious stuff, you have not just a fixed number of primitive variables, but create variables on the fly in function calls, or have variable-size variables... or anything like that, as possible in a Turing-complete language. That makes the state space infinite-dimensional, shattering all hopes of full coverage, even given absurdly powerful testing equipment.

That said... actually things aren't quite so bleak. It is possible to proove entire programs to be correct, but you'll have to give up a few ideas.

First: it's highly advisable to switch to a declarative languange. Imperative languages, for some reason, have always been by far the most popular, but the way they mix together algorithms with real-world interactions makes it extremely difficult to even say what you mean by “correct”.

Much easier in purely functional programming languages: these have a clear distinction between the real interesting properties of mathematical functions, and the fuzzy real-world interactions you can't really say anything about. For the functions, it is very easy to specify “correct behavior”: if for all possible inputs (from the argument types) the corresponding desired result comes out, then the function behaves correctly.

Now, you say that's still intractable... after all, the space of all possible arguments is in general also infinite-dimensional. True – though for a single function, even naïve coverage testing leads you way further than you could ever hope for in an imperative program! However, there is an incredible powerful tool that changes the game: universal quantification / parametric polymorphism. Basically, this allows you to write functions on very general kinds of data, with the guarantee that if it works for a simple example of the data, it will work for any possible input at all.

At least theoretically. It's not easy to find the right types that are really so general that you can completely proove this – usually, you need a dependently-typed language, and these tend to be rather difficult to use. But writing in a functional style with parametric polymorphism alone already boosts your “security level” enourmously – you won't necessarily find all bugs, but you'll have to hide them quite well so the compiler doesn't spot them!


答:
There are several substantial benefits of using a CMS for content management in a team of developers.

Knowledge required to publish content. Let's imagine I want to write an article. With any CMS, that's easy. I walk through the menus, and a few minutes later have a grasp of the system.

What happens if I have to discover the internal workings of a home-grown project that I need to modify to publish content? I have to know naming conventions. I have to know how to compile the project. What about regression testing? In most projects, deployment is a nightmare, and the number of errors and blocking points you can get when doing a minor change are often overwhelming.

Some developers in your team may not necessarily want to explore the internal workings of your home-grown project. Some may not even know the programming language used by the project, and not willing to learn it.

Writing an article shouldn't be more difficult than a few clicks, and a CMS is a perfect tool for that.

Other technical knowledge.

I have a blog based on a home-made blog engine. I love the engine, but it has a huge drawback: I have to write articles in a simple textarea and use extended Markdown syntax. There are no pretty buttons for bold and italic text, and nothing much to help me when I forget the syntax.

And forgetting the syntax happens to me very often. For instance, I have no idea how to create a footnote, or a dialog, or a table. I remember that I did that in previous articles, but I have to find them and copy the syntax.

With developer-oriented solutions, this happens all the time. How do you create footnotes in code? When you need to add a picture, where do you put the image file? With an enterprise-scale CMS, all those features are easily accessible; you don't have to think about them, and so you can focus on important things, that is the content.

Iteration duration.

How long does it takes to, say, correct a typo or add a comment in a CMS? A few seconds to a few minutes, depending on the steps such as authentication.

Do you think it will be practical to edit source code to add a short comment, or to make a delivery just to correct a small typo? If the answer is no, this means that you are losing opportunities because of technical constraints you can easily avoid by having a CMS.

Extensibility.

Take SquareSpace (although not a CMS, the following feature probably exists in a few CMS as well). They have a feature which resizes site images for different screen sizes. You can upload a 8 MB photo from your DSLR, knowing that the user accessing your website from a mobile device won't have to download the 8 MB file, but the rescaled image which takes a few kilobytes.

How do you do that when your team is directly modifying the source code of the site? You create a tool which does that. The problem is that now, every member of the team has to know how to use this tool. Or you make it possible to do automatically by hrefing images to a specific service, but now the members of the team need to remember that they need to use the service. Half of them will not, leading to inconsistencies.

Maintenance.

Your home-grown solution will grow constantly. Team members will need different features, leading to more code. The site is a standalone project which should be managed as an actual project, which has technical debt to be paid, which can have regressions.

The time you spend working on this project is the time you won't spend on other projects. This is unfortunate, since with a CMS, all you have to do is to update the engine regularly.

Access from everywhere.

Most CMS provide OAuth or similar authentication mechanisms allowing you to connect from anywhere. The fact that they require only a browser makes it possible to change content from practically any device: you can be writing an article on a tablet in a train or posting comments with your smartphone in a subway during your morning commit.

Making is necessary to modify the source code in order to change the content, on the other hand, creates additional barriers. While basically the only two things you need is a text editor and a version control system client, this may not be that easy to have. Do you have vi on your smartphone or a git client on your tablet?


问:
What is proven as a good maximum length of a function?
Does function length affect the productivity of a programmer? If so, what is a good maximum number of lines to avoid productivity loss?

Since this is a highly opinionated topic please back up the claim with some data.

答:
In my opinion, every function should be as small as possible. Each function should do only one thing and do it well. That doesn't really answer the maximum length question, but it is more my feelings on the length of functions.

To use the words of Uncle Bob, "Extract till you just can’t extract any more. Extract till you drop."

ContentLicense: CC BY-SA 4.0


答:
The source of the confusion here may be the fact that you are viewing the application object as being one and the same thing as the domain model of your application.  They are not.  The application contains the domain model, and instantiates the features that operate on it.

So, my recommendation would be to take all these global variables out of the application object and move them into a domain model object which gets instantiated by and contained within the application object. Then, pass a reference to this domain model object as a constructor parameter to each and every feature that needs to operate on it.

In order for this to work well, the domain model object should offer change notification events, so that when one feature changes it, other features can take notice of this change if they need to.

It is perfectly fine if a feature needs to make use of only a small subset of the domain model; there is no need to break the domain model down into smaller chunks to feed them to individual features. Such a reduction of the available information would be too artificial, too much hassle to maintain, too fragile, and it would not yield any considerable benefits.  On the other hand, if an entire group of features only need a small common subset of the domain model, then you may wish to consider having a subdomain model for use by that group of features only.

Title: Design question concerning proper and practical encapsulation

Body:
I have been working on refactoring old code and found a lot of instances of the following type of situation: There is a master object which we call "Application" and there is only one of these. The Application will create other objects called "Features" inside it depending on user input etc. The Feature object may have some methods that take void parameters but actually operate on or use some variables in the scope of Application. This is because the functions defined in class Feature are defined in the same project and include the header from Application (this is C++). Here is a rudimentary attempt to show a simple example pseudocode:

```<code>int main()
{
    Application theApp = new Application()

    the.App.someSetting = foo;
    the.App.someVariable = bar;

    the.App.RunSomeFeature();
}
// RunSomeFeature function def in class Application
void Application::RunSomeFeature()
{
    // create object of type feature
     Feature feature = new Feature();

    feature.SomeFunction(void)
}
// SomeFunction def in class Feature
void Feature::SomeFunction(void)
{
    // global variable from Application "creeping in"
    someLocalVariable = theApp.someSetting;
    otherLocalVariable = theApp.someVariable;
}
</code>```

I hope this illustrates somewhat what I mean. My goal is essentially to move the class "Feature" to some location outside the namespace of "Application" (to a dll for example) and I can not include Application header (since that would defeat the purpose of the separation). But since there are these types of globals everywhere in the old code this task is rather complicated. This may be a C++ thing for all I know that it is easy (or posible) to make this coding mistake but I am not sure.

This made me think of a few questions regarding OOP design. Well designed OOP code would only have completely autonomous classes and functions with all outside variables explicitly passed in? Even if one object will be created inside another? I can see that way the entire code would be much easier to internally "reshuffle". But sometimes there may be a lot of parameters to be passed and since "Feature" is created by "Application" anyway I see why my situation might arise. But code written as in the example implicitly joins class Application and Feature to the same overall "block" or scope and it takes line by line work sometime to separate them.

However the other extreme would be that each class is essentially almost an autonomous application in its own right (and this may go somewhat against the idea of inheritance). When I read about OOP design principles, I usually don't find this particular nuance talked about much or I just get the idea that everything should be basically autonomous but I find that in practice this is rarely truly so.

I see that this may be a bit open ended but any rules of thumb about at what level would we "completely encapsulate" in order to have pieces of code we can reshuffle easily? Or any design philosophy anyone would share about this type of situation?


问:
Is it a bad practice to separate the unit tests for a class?
My Classes normally have about 5-20 methods maximum, that implies that the class that has the unit tests has about the double of methods (counting dataProviders, setUp, ...)

I have thought to separate the tests in 2-3 classes, because even if I try to follow the single responsibility principle, I prefer 2 tests classes with 10 methods each, than one with 20.

Is it a bad practice?? Is good to have all the tests for a class in only one, although the test class grows in vertical?

答:
It is almost of no importance how your unit tests are organized compared to having them in the first place.

A module or class of business code is something you have to understand as a unit and develop further. That's the main reason we strive to make it coherent, easy to grasp as a whole, etc. A test suite is only a collection of cases that must all pass; the don't have any particular relationship to each other. Ideally, you'll never have to deal with it again; if you do it's usually to add more tests that again have no particular relationship to any other test, and they're never called by client code except the unit test framework.

Therefore, the question of how to organize the classes containing unit tests is much less critical than how to organize the classes that make up your application itself. You're not supposed to deal with them as a well-architected macrostructure anyway.


答:
If we say that definition of bad practice in software development is anything that doesn't help you cope with and encapsulate change then I would say not keeping your classes and tests in one to one relationship is bad practice. It is a code smell that might arise because of the things mentioned below.

Obviously there are exceptions just like with anything but just keep that in mind as you are writing your tests.

My Classes normally have about 5-20 methods maximum.

If any of your classes have 20 (or a little less) methods that kind of shows me that the class is doing too much in the first place. This is where unit testing should hint you that you might need to break down your class a little more and distribute the responsibility before going about testing.

As for keeping them in the same class or not I would suggest trying to keep them in one class if possible because it is better understandable - one to one connection is easy to grasp after a lot of time has passed. Just from experience.

If you see that the unit tests are huge even when you have 5 methods or less then that tells me that your setup code is doing too much or your objects are abnormally big.

If you haven't tried already check out the builder pattern for building your objects - this could cut down code drastically on how you are building your objects before testing them. Therefore making the unit test class shorter and less need for you to cut it down into more classes.

Title: Is it a bad practice to separate the unit tests for a class?

Body:
My Classes normally have about 5-20 methods maximum, that implies that the class that has the unit tests has about the double of methods (counting dataProviders, setUp, ...)

I have thought to separate the tests in 2-3 classes, because even if I try to follow the single responsibility principle, I prefer 2 tests classes with 10 methods each, than one with 20.

Is it a bad practice?? Is good to have all the tests for a class in only one, although the test class grows in vertical?


答:
Put the tests in one file.  Typically for every class file I would have a test file.  Usually append "Tests" to the file name.

For example, if there is a class called "Foo" there would be a corresponding "FooTests" file.  This way for every code file there is a 1 to 1 relationship between code file and the test file.

This provides consistency and makes it easier for developers to locate the tests and keep them up to date.  Tests are usually excluded from code analysis/metrics so if the file is big, it doesn't hurt the overall code health metric, so I don't consider it bad form to have a test file with lots of unit test code.


问:
License terms when porting free software to another language
I'm exploring in the idea of porting an existing software package to another language. It's released under the Apache License 2.0, and is distributed for free; but there's a big different between using a library versus creating a copy of it. I would of course give full credit and be honest about where it came from, and I certainly don't plan to make any money from the port, just use it in other projects.

I've read the license of course, which says:

Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.

[...]

Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:

a. You must give any other recipients of the Work or Derivative Works a copy of this License; and

b.You must cause any modified files to carry prominent notices stating that You changed the files; and

c. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and

d. If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file [...]

You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.

Which sounds very much like a port (as a "Derivative Work") is entirely permitted with or without the author's permission provided I diligently retain copies of the license, existing copyright notices, attribution etc.

But that doesn't mean I understand all the implications of it. For example, would the port necessarily have to share the same license as the original?

I haven't started any of the work, nor have I contacted the authors of the package yet (though I will). I want to establish whether there's any risk of a lot of work being wasted. I also need to know whether I'd need to make a clean room implementation based only on the API, or whether I could base my work on the existing source code (which I haven't looked at yet).

答: A copyright applies to the original source code only. I cannot provide legal advice (legally :) ) in my country, but when you use a different language, it is a different body of source code. Ethical considerations are a different matter. I would attempt to use a license that is agreeable to the original authors, to preserve the spirit of the original open source contribution to the community. Additionally, the original authors should be credited.</p>


答:
To answer the specific question, it's absolutely possible that grouping tests into multiple classes is a good decision, event when the class under test is well designed.

Unit test code is like any other code: it should follow good design principles (DRY, GRASP, KISS, SOLID, YAGNI, etc). Because the logic that makes up test code is often simpler than domain logic, a lot of the specific points won't come up as much, but keep them in mind while writing your tests all the same.

There are a couple of principles that come to mind that can easily apply when thinking about your question:

Readability

Ideally, once a test is written, you never have to look at it again; but the same can be said for any code. The reality is that requirements change, so we find ourselves reading code much more than writing it. Even when doing your best, you may find that the test you wrote didn't quite verify what you thought it did, at which point you'll have to go back in and figure out what was wrong. Finding that test method in a class of 40-50 test methods is going to be tough, not to mention the complication of naming those methods so they can be differentiated easily.

High Cohesion

Each test class (like any other class) should have a clear focus. If you have a lot of different test cases for a given method of the class under test, as when a given test verifies a single thing, put those test methods in a separate class and name it to reflect its focus.


问:
Should curly braces appear on their own line?
Should curly braces be on their own line or not? What do you think about it?

```<code>if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}
</code>```

or should it be

```<code>if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}
</code>```

or even

```<code>if (you.hasAnswer())
    you.postAnswer();
else
    you.doSomething();
</code>```

Please be constructive! Explain why, share experiences, back it up with facts and references.

答:
You could write it:

```<code>you.hasAnswer() ? you.postAnswer() : you.doSomething();
</code>```

To answer the question; I used to prefer curly braces on their own line, but, to avoid having to think about bugs from automatic semicolon insertion in browsers i started using Egyptian style for javascript. And when coding java in eclipse I had no interest in fighting (or configuring) the default brace style, so I went with Egyptian in that case too. Now I'm fine with both.

Body:
You could write it:

you.hasAnswer() ? you.postAnswer() : you.doSomething();

To answer the question; I used to prefer curly braces on their own line, but, to avoid having to think about bugs from automatic semicolon insertion in browsers i started using Egyptian style for javascript. And when coding java in eclipse I had no interest in fighting (or configuring) the default brace style, so I went with Egyptian in that case too. Now I'm fine with both.


答:
Translations (both to a different natural language and to a different programming language) are considered to be Derived Works.

When creating a derived work that is so radically different from the original as a translation to a different (not closely related) programming language results in, it is actually quite hard to understand how the requirements from the Apache license should be applied. I would very strongly advise you to discuss with the maintainers of the original package how they would like to see the copyrights handled and you might want to discuss it with a lawyer as well.

The troublesome part is clause 4c:

c. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and

The problem here is that with such a radical change, it is next to impossible to tell which (copyright and attribution) notices from the original work legally also pertain to the translated version and thus which notices must be kept and which must be removed.

Title: License terms when porting free software to another language

Body:
I'm exploring in the idea of porting an existing software package to another language. It's released under the Apache License 2.0, and is distributed for free; but there's a big different between using a library versus creating a copy of it. I would of course give full credit and be honest about where it came from, and I certainly don't plan to make any money from the port, just use it in other projects.

I've read the license of course, which says:

Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.

[...]

Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:

a. You must give any other recipients of the Work or Derivative Works a copy of this License; and

b.You must cause any modified files to carry prominent notices stating that You changed the files; and

c. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and

d. If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file [...]

You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.

Which sounds very much like a port (as a "Derivative Work") is entirely permitted with or without the author's permission provided I diligently retain copies of the license, existing copyright notices, attribution etc.

But that doesn't mean I understand all the implications of it. For example, would the port necessarily have to share the same license as the original?

I haven't started any of the work, nor have I contacted the authors of the package yet (though I will). I want to establish whether there's any risk of a lot of work being wasted. I also need to know whether I'd need to make a clean room implementation based only on the API, or whether I could base my work on the existing source code (which I haven't looked at yet).


答:
"Static" is sometimes a naughty word in the C# world, because it makes it difficult to create Unit Tests around the class in question, unless the class is doing nothing but logic-processing and has no database, file I/O operations, or any such behavior. If you're passing data or commands from layer to layer, then I would suggest that your class NOT be static.

Did your friend specify WHY your data classes should be small? I suspect its not because of memory size, but rather because its best to break those data classes down to be as small and specific as you need, and not any larger. When you first get into OOP, there's a tendency to create "God" classes that have dozens of methods and fields. This feels "right" at first ("Oh look, I've got everything I need in one class/spot, great!") but it quickly bogs down into an unmaintainable mess.

A common pattern that I like to use is having my data transfer object (or POCOS, they have diff names) be very small and very dumb. Just structures really (but not the "struct" keyword, that's a whole 'nother ball of wax), with no methods or behavior of any sort. Having properties that do very basic null checking, string building, and/or aggregation on other fields of the same class is fine, but any bigger behavior goes elsewhere. The class that actually does work (database, file stuff) is a separate class with a bunch of methods that take these data transfer objects as params, or return them as results. This "data access provider" class won't have very many properties itself, and usually implements an interface (keyword: "interface" in C#) that I define that requires those methods.

The point of the interface is so my web apps or whatever can just call that class through the interface, and I can hot-swap in a different class that satisfies the interface that might just drop in dummy data, for testing purposes. You can't do that type of thing if the data access class is static.

Summary: If you truly want your data access class to ONLY behave in one way (actually trigger sql calls or file i/o and not be "mockable") then your data access class can be static, but I'd recommend against it. You'll be boxing yourself into a corner later, if you get into Unit/Integration Testing. (However, it wouldn't be terribly difficult to refactor at that point honestly)

Title: Using static classes to define methods for handling POCO class objects

Body:
I am pretty new to the OOP paradigm and for this current project of mine, I need to design and develop a web application backend in .NET MVC using C#.

A friend of mine told me that the class objects we use mostly for passing information from one layer/function to other should be as small as possible, which is a sound argument and hence I also presumed that we better not have methods in this class and store only properties. This requires me to define another class that would have some methods defined solely to do operations on this class's objects.

I was wondering if making this whole method-only class a static class is good option or not? Or may be make these methods a part of the property-only class but make them static.

Am I thinking on the right track? Are there any cons of using static which I should be aware of? Any costs associated with it?


问:
Big O notation for a sub linear algorithm
I have a function for which the complexity raise by the square ten of the exponent of the number.

Ex:

```<code>+-----+----------+
|Input|Complexity|
+-----+----------+
|0    |     1    |
|10   |     2    |
|100  |     3    |
|123  |     3    |
|1001 |     4    |
|9999 |     4    |
|10000|     5    |
|99999|     5    |
+-----+----------+
</code>```

How to express its complexity in big O notation ?

答: The mathematical function that is like that is log n.  So the big O notation would be O(log n).


问:
What are the real benefits of static code analysis?
Tools like pc-lint or QAC can be used to perform static code analysis on a code base.

In my experience the static analysis often yields a huge amount of noise, i.e. warnings on things that are not real bugs but somehow violate one of the rules in a given rule set. Turning off certain rules (either for good in the rule set or via special comments in the code) can be a real cumbersome process.

What are the real benefits of static code analysis?

答:
From a consultant's perspective, every static analysis tool will have some noise but not all static analyzers are created equal. Static analysis tools like Coverity, Klocwork, Grammatech have good analysis techniques that should produce more accurate results.  If you tune and tweak some more you get better results typically (after all, static analyzers have to be able to run on all different types of code from a tiny medical device to a network operating system).  Defining "noise" is also dependent upon your criteria for what constitutes a fix-worthy report.  On one end of the spectrum, some developers mark all reports they don't fix as "false" (even poorly written code that they don't have the time to fix) and on the other end, we worked with several mil-aero and med devices companies that made sure even false positives were "fixed" because if the code was confusing the tool, then it probably should be written more clearly so it would be more maintainable.

Some of these tools are more central analysis focused and others are more desktop focused - although all three have features that support both.  As @Bob mentioned, they cost money.

OwnerDisplayName: Andy


问:
Fixing class Hierarchy design mistakes due to incorrect inheritance
I have a code like this. My derived class man, may not properly have a member function declared pure virtual higher up the hierarchy. eg. WagTail here

```<code>class mammal{
public:
    virtual void WagTail() = 0;
    virtual void BreastFeed() { };
    ~mammal();
};

class Terrestrials : public mammal{
public:
    virtual void sunbathe() = 0;
};

class cat : public Terrestrials {
    void sunbathe() override final  {
        cout << "My owner made me stand in the sun";
    }
    void WagTail() override final   {
        cout << "Wagging Tail";
    }
};

class Man : public Terrestrials {
    void sunbathe() override final  {
        cout << "Life is good!";
    }
    void WagTail() override final   {
        // Wait, Wha??? ERROR!!!!
    }
};
</code>```

What is the best way to fix a mistake like this without rewriting the entire hierarchy?

答:
This is a case of a Liskov Substitution Principle violation.

Your mammal class appears to be misnamed, not all mammals have tails as you may have noticed.

You may be able to solve it with multiple-inheritence.

```<code>class Waggable
    + WagTail

class Terrestrial
    + SunBathe

class Cat : Terrestrial, Waggable

class Man : Terrestrial
</code>```

Though I'm not sure what you mean by not rewriting the hierarchy.  The hierarchy is the problem so I don't know how you can 'fix' it without changing it.

Body:
This is a case of a Liskov Substitution Principle violation.

Your mammal class appears to be misnamed, not all mammals have tails as you may have noticed.

You may be able to solve it with multiple-inheritence.

class Waggable
    + WagTail

class Terrestrial
    + SunBathe

class Cat : Terrestrial, Waggable

class Man : Terrestrial

Though I'm not sure what you mean by not rewriting the hierarchy.  The hierarchy is the problem so I don't know how you can 'fix' it without changing it.


答:
The fundamental problem is that a pure virtual function was added very high in a class hierarchy which not all conceivable subclasses can plausibly support. This is why one should be very careful defining deep class hierarchies. I see a couple approaches.

One approach is to simply provide an empty implementation of WagTail for the Man class. Hopefully this won't break anything. And after all, primates generally have tails, only for people they have withered away to an internal coccyx (tailbone) because they provided no benefit. And some people are in fact born with "tails".

Another is to move tail-ness into a separate class, really just an interface, and have most Terrestrials inherit from that. This way other classes, like Reptiles and Fish, can also have tails and a WagTail method. In general, multiple inheritance of interfaces is preferable to deep class hierarchies.

Historical Note: Back in the 1980s and early 1990s, before there was Java and C++ compilers did not widely support multiple inheritance, deep class hierarchies were quite common. Microsoft's MFC was quite deep, as was Apple's MacApp.

Title: Fixing class Hierarchy design mistakes due to incorrect inheritance

Body:
I have a code like this. My derived class man, may not properly have a member function declared pure virtual higher up the hierarchy. eg. WagTail here

```<code>class mammal{
public:
    virtual void WagTail() = 0;
    virtual void BreastFeed() { };
    ~mammal();
};

class Terrestrials : public mammal{
public:
    virtual void sunbathe() = 0;
};

class cat : public Terrestrials {
    void sunbathe() override final  {
        cout << "My owner made me stand in the sun";
    }
    void WagTail() override final   {
        cout << "Wagging Tail";
    }
};

class Man : public Terrestrials {
    void sunbathe() override final  {
        cout << "Life is good!";
    }
    void WagTail() override final   {
        // Wait, Wha??? ERROR!!!!
    }
};
</code>```

What is the best way to fix a mistake like this without rewriting the entire hierarchy?


答:
Actually, Randall Cook gave a very good answer here, but I would like to add something. Assumed you are going to implement "WagTail" for "man", the correct way of implementing it depends on the expectations of the code calling that method on mammals. If the caller expects some kind of error behaviour or exception to be thrown, then you could actually implement that. If the caller does not expect it, you may implement it empty.

That's why for any interface or pure virtual base class, there should be a contract somewhere, a formal or informal definition of the expected behaviour. Without a contract, you can only guess whats necessary not to violate the Liskov Substitution Principle.


答:
In this case, tail-wagging is just the expression of something more fundamental (excitement?). Rename WagTail at the high level to something more "simple" (ExpressExcitement?), update the invoking code, and just invoke the relevant subclass's WagTail methods/code from their ExpressExcitement methods.

That could be a lot of work (it could also be a really quick search/replace); but it's probably worthwhile to make your common denominator more meaningful / less implementation specific.

... I guess this may fail your "without rewriting the entire hierarchy" requirement. But, I'd posit that the requirement is wrong.


答: A method that works for me is: Can I have a part of a longer function give a name that makes sense. I think length of a method is not that important like good naming. The method should do what the name says, no more and no less. And you should be able to give a good name. If you cannot name your method good, the code is probably not good put together.</p>

Title: What is proven as a good maximum length of a function?

Body:
Does function length affect the productivity of a programmer? If so, what is a good maximum number of lines to avoid productivity loss?

Since this is a highly opinionated topic please back up the claim with some data.


问:
Use of FindWindow and window handles within a Windows service
I've got a third-party vendor who is installing a series of Windows services to a (Windows 2008 R2) server in my control.  Whilst attempting to run each service under its own least-privilege account, we have hit upon obligatory permissions issues.  These only seem to be resolvable by running the service as Local System -- even membership of the local Administrators group is insufficient.

The issue appears to stem from some IPC-related code, which is built around a single .NET class, referenced by the individual services.

As far as I can tell from the IL disassembly (via Telerik JustDecompile), the IPC class derives from System.Windows.Forms.NativeWindow and sets up a WndProc override to handle a custom message.

Each service instantiates the IPC class with a given name parameter, which it passes as the NativeWindow's title and, when it needs to send to the other service, uses the Win32 API FindWindow method (called as Win32.FindWindow(null, targetName)) to determine the handle of the hidden NativeWindow of the target service, and calls PostMessage on that handle, to trigger the remote action.

The issue appears to be that, unless run as Local System, the call to FindWindow only returns a zero-handle, which the sending service perceives as the target service not being found.  As mentioned, even when run as a member of Administrators, it still appears to return the zero value.

I thought this might be an issue with Session #0 isolation but, since this is all service-to-service IPC, rather than service-to-desktop, all executables are running in Session #0, anyway.

There's not much I'm going to be able to do about this -- business needs must, after all -- but, from a theoretical perspective:

Am I right in thinking a global, named EventWaitHandle, with a while (true) { _h.WaitOne(); /* handle event */ }-style message loop, on its own thread, is the more-appropriate option for this kind of work?

Is this a case of permissions to the window handle (do such things exist?) and, if so, could these be changed (e.g. with DuplicateHandle); or does a Windows privilege exist (e.g. in Local Security Policy / User Rights Assignment) that permits/overrides access to the handle?  (I considered SeDebugPrivilege, but local Administrators already has that.)

Is there anything that documents the inappropriateness of FindWindow/PostMessage for this kind of work (specifically for service-to-service IPC)?  i.e. is this a known limitation for FindWindow, with which I might beat the third-party over the head?

答:
This is a normal restriction in the Windows security model since NT3.x services that only the local service account is allowed access to the desktop when run as a service and it has other restrictions when you select that option.

On Windows Server since about 2003, there is also a service interaction policy you may have to adjust. You may have to reboot the machine to pick up this setting.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows
NoInteractiveServices = default is 1 until win2k3, change this to 0. On win2k8+ its default is 0

This technote below also suggests a method using named pipes to connect a service to a windows app or background task that can run in the logged in session and send materials to the service over the pipe.

Here is a technote from Microsoft on the topic along with some cautions:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms683502(v=vs.85).aspx

There is a registry hack if you want to use a specific account but not sure it will be able to reach into any user's session unless it has admin permissions, I've never tested this use case.

HK Local Machine : SYSTEM\CurrentControlSet\Services\your service
Key= "Type"
Position 100h (If you logical 'or' with decimal 256 to set the bit)

Credit for this registry detail:
http://www.codeproject.com/Articles/4891/Interact-With-Desktop-when-Installing-Windows-Serv


问:
How to test network connectivity API using TDD?
I'm currently trying to add TDD on my workflow. I fail to create tests where I can easily test a library that requires remote connections.

More precise, my program uses snmp4j library. Currently I'm working with 1 release behind due to I don't know what's the impact of the new API release on my code. So I read that implementing a battery of tests based on what I use from the library I can have a better overview of the impact if I upgrade to the new version. So I have the following question

I need to get an snmp response based on a request. Ideally would be that I have control over the machine and I know what to ask and what to expect ... but what if that remote machine is down, has network connectivity problems or doesn't exist? Should I create a SNMP agent listening on localhost and have control over which OID I ask and which responses I give? I rely heavy on the type of responses from the OIDs (being Integer32, Gauge32 etc) not the values I receive.

The response doesn't have to be so concrete, actually I would like to read more about this kind of scenarios where you need to test network connectivity through an API.

答:
In their book Growing Object-Oriented Software, Guided by Tests, Steve Freeman and Nat Pryce tackle this very issue. I do recommend that as a worthy read, since it's full of interesting examples and I'll probably just misquote, anyway.

Rephrasing, they argue that instead of mocking the external API you have no control over, you should create a layer of adapter objects. That way you can translate the data to your application's terms and distance the third party code from yours.

I rely heavy on the type of responses from the OIDs (being Integer32, Gauge32 etc) not the values I receive.

Based on what you said, that could be a helpful pattern to adapt to.

However, the authors also state that this pattern may not be applicable if your application relies on value types. So in the end it boils down to: it depends. Abstracting value types may not make sense in this particular case, but if it does, here's an option worth considering.


问:
Styleguide when coding in a static language
I am currently a junior engineer and keen on learning best practices and expanding my experience. My question concerns any static programming language such as Java, C#, C++ etc.

When I am writing code, I like making it easy to read. In my opinion, reading code should be like reading a book. It should be fluent and elegant. Then, even if I do not need to use them, I like prepending this, super–base keywords whenever I can. Ditto for current class name when I want to use constants or static variables/methods.

Consequently, another developer can quickly have a long shot. He knows this method or var is in the current class or in mother class without needed to move to declaration. You may say to me it is really easy to do that with recent IDE. However, I know a bunch of guys who are still working with Vim, Emacs or other editors without these fancy features.

When explaining it, I like comparing my practices to a drama book. We have all read at least one of them, such as Macbeth from Shakespeare. Who has never felt frustrated to go back at the beginning of the book to know who is that character and what part he has in the plot? You did that so many times, right?

My question can be associated to literate programming practices. However, I assumed Donald Knuth's recommandations are more about commenting and adding macros to your code.

So I would like to know your opinions and feedbacks about these practices. Am I doing too much? Should I keep it simpler? Am I breaking OOP rules?

Here is a code sample:

```<code>class Bar {
    protected int _motherVar;

    public aBarMethod() { }
}

class Foo extends Bar {
    private static List<String> _strings;

    private int _myPrivateVar;

    public void aMethod() {
        super.aBarMethod();

        this._myPrivateVar++;
        super._motherVar -= 2;
    }

    public static String anotherMethod() {
        String outcome = "";

        for (String s : Foo._strings) {
            outcome += s;
        }

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

答:
I'd advise against using this. in this fashion, not because it is in itself a bad idea.  (Python, for example, forces you to do this with self. and python has a well-deserved reputation for readability.)   But rather because the language doesn't enforce it.  Because the language doesn't enforce it, it is easy to forget it on an individual line, which will then may confuse a future reader of the code.  Same goes for super..  The compiler doesn't make you do it, so you may forget, and when you forget, the missing super. becomes misleading to someone who assumes it will always be there.

Using a prefix like _ or my or m_ is better because the compiler will force all instances to match.  You can't forget that, so any reference to that attribute will be obvious as a member of the attribute.

That said, @kent-anderson's point in the comments is well taken.  Ideally, you want to keep the classes and methods small enough that this sort of thing isn't needed.  If, for example, you don't reference globals, avoid using superclass attributes directly and keep method names to 10-20 lines, it is pretty easy to see what are locals (as they are declared right there) and what are attributes on that object (everything else.)


问:
Is there an alternative to instanceof when filtering a Java stream by class?
I have an unexpected situation in a project in which all types extending one class are packed into a Java collection; but only a specific extension of that class contains an additional method. Let's call it "also()"; and let me be clear that no other extension has it. Right before performing one task on every item in that collection, I need to call also() on every item that implements it.

The easiest way forward is this:

```<code>stuff.stream().filter(item -> item instanceof SpecificItem)
            .forEach(item -> ((SpecificItem)item).also()));
stuff.stream().forEach(item -> item.method());
</code>```

It works fine, but I'm not comfortable with the "instanceof" in there. That's generally a marker of bad code smell. It is very possible that I will refactor this class just to get rid of it. Before I do something that dramatic, though, I thought I would check with the community and see if someone with more experience with either Streams or Collections had a simpler solution.

As an example (certainly nonexclusive), is it possible to get a view of a collection that filters entries by class?

答:
Here is my approach:

```<code>stuff.stream().filter(item -> SpecificItem.class.isInstance(item)).map(item  -> SpecificItem.class.cast(item)).forEach(item -> item.also());
stuff.stream().forEach(item -> item.method());
</code>```

No instanceof, no explicit casts (actually it is an explicit cast, but masked by a method call). I think this is as good as it can get.

Body:
Here is my approach:

stuff.stream().filter(item -> SpecificItem.class.isInstance(item)).map(item  -> SpecificItem.class.cast(item)).forEach(item -> item.also());
stuff.stream().forEach(item -> item.method());

No instanceof, no explicit casts (actually it is an explicit cast, but masked by a method call). I think this is as good as it can get.


答:
I think all three (this., super., and private member prefixes) are superfluous:

this. is superfluous if you have relatively small methods, which you should (rule of thumb: does one thing; code fits in a single screen). In a small method you can easily tell apart method-local and instance/class variables.

super. is superfluous because classes should be relatively small (due to single responsibility principle), so you should easily see if a member you access is or isn't in a current class.

Prefixing private members with underscore (or any other special prefix) is superfluous because you shouldn't care if something is private or not when using it in a method (you should only care if it is accessible), and if you have to care, this is probably a code smell of some sort, e.g. you're joggling a state of some public variable. (@StevenBurnap's point is valid, but you can forget to prefix (especially after refactoring) a member name with underscore just as easy as you can forget to prefix it with this. when accessing, so I think it doesn't help as well.)

Of course, if you have 1000+ lines of crap in a single class, all those things start to matter, but it is not a solution, but rather a prosthetic. I've seen people do that a lot, and it never helped my reading a bad code.

Title: Styleguide when coding in a static language

Body:
I am currently a junior engineer and keen on learning best practices and expanding my experience. My question concerns any static programming language such as Java, C#, C++ etc.

When I am writing code, I like making it easy to read. In my opinion, reading code should be like reading a book. It should be fluent and elegant. Then, even if I do not need to use them, I like prepending this, super–base keywords whenever I can. Ditto for current class name when I want to use constants or static variables/methods.

Consequently, another developer can quickly have a long shot. He knows this method or var is in the current class or in mother class without needed to move to declaration. You may say to me it is really easy to do that with recent IDE. However, I know a bunch of guys who are still working with Vim, Emacs or other editors without these fancy features.

When explaining it, I like comparing my practices to a drama book. We have all read at least one of them, such as Macbeth from Shakespeare. Who has never felt frustrated to go back at the beginning of the book to know who is that character and what part he has in the plot? You did that so many times, right?

My question can be associated to literate programming practices. However, I assumed Donald Knuth's recommandations are more about commenting and adding macros to your code.

So I would like to know your opinions and feedbacks about these practices. Am I doing too much? Should I keep it simpler? Am I breaking OOP rules?

Here is a code sample:

```<code>class Bar {
    protected int _motherVar;

    public aBarMethod() { }
}

class Foo extends Bar {
    private static List<String> _strings;

    private int _myPrivateVar;

    public void aMethod() {
        super.aBarMethod();

        this._myPrivateVar++;
        super._motherVar -= 2;
    }

    public static String anotherMethod() {
        String outcome = "";

        for (String s : Foo._strings) {
            outcome += s;
        }

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


问:
Structuring project (refactoring)
I'm working on a project that requires from me to make modular and extendible code structure. This code should be able to support multiple clients. The good news is that code should not do anything spectacular. I will explain this in more details later in the question.

So now I have around 30 branches for about 60 clients. Some clients needed their own branch because at the time it was easier to just separate their code from everyone else’s so that over time grow to 30 separated codes, that are very very similar.

So now architecture could not be more simpler. Request comes from client in XML form and then I process I return XML. Process part is mostly CRUD. Nothing fancy. I have two front controllers one for actions (INSERT, UPDATE, DELETE) and one for requests(SELECT). Then that front controller just includes script that client requested. Every request and every action has their own dedicated script. There are not a single class in the project. Everything is written in procedural way.

So in the new App structure the goal is to have one main branch that will all clients use and it will be managed from conf file.

I'm telling you all this because I'm not sure how to structure everything. I don't have much experience with OOP I know the concepts and theory but its harder when it comes to actual coding in that style.

My idea now is. I'm leaving two front controller for action and request because that doesn't require any change from client-side of application and that is important for now. They will now serve as only get request and echo it back. They will also call ActionController and RequestController. They will be a little smarter. They will know how to recognize which request/action client sent and then they will make new object of that class.

Every action/request has some steps that it needs to do. So i'm thinking that every class need some public method 'execute' that will just call method of that class by the order that it needs to, but I'm afraid that, that is also procedural way of thinking just it wont be in global score but in Class.

```<code>$client_request = new $fullClassPath(new $mapperClassPath);
$response = $client_request->execute($request);
</code>```

Also How to handle Database, I probably should make actions on database as abstract as possible.

Configuration file will be very important, so I don't know if it's the solution to make class for every feature and include classes if that feature field is set to true in config file?

Every action has its own response to client and it can be pretty heavy xml. What is the solution there. Should I have a Response class that will handle that. Im afraid that the class will be pretty heavy because there are around 20 actions and 5 requests and everyone have different xml response.

So every help is appreciated with someone who had experience with similar projects, some links on good articles also wouldn’t hurt.

I should mention that language I’m working with is vanilla(plain) PHP.

答:
It sounds like essentially the problem is that you have 30 processes which are similar but vary in inconsistent ways and you want to avoid duplicating code as much as possible while still being able to change any aspect if required.

In that case then the template method pattern can be very useful.

The basic idea is that you'd implement a base/abstract class which more or less functions in the most common way, then for each customer you create a child class which only overrides the methods which need to be changed.

For example:

```<code>abstract class BaseCustomer {

    protected $someValue = 5;

    protected function someProcess() {
        return $this->someValue * 2;
    }

    public function execute() {
        return $this->someProcess();
    }

}

class FirstCustomer extends BaseCustomer {
    protected $someValue = 10;
}

class SecondCustomer extends BaseCustomer {
    protected function someProcess() {
        return $this->someValue + 2;
    }
}
</code>```

Calling ->execute() will return 20 for FirstCustomer and 7 for SecondCustomer.

A further step you can take is to use composition in combination with a template pattern to separate different components of your modules.

For example let's say you have processes which send a CSV file in 5 different formats via either email, FTP or HTTP depending on the customer. You can have two sets of modules: one for the file format and one for the transport method.

Then go something like:

```<code>$format = new CustomerOneCSVFormat($data);
$transport = new FTPModule();
$transport->send($format);
</code>```

In that example you could support 15 different combinations from only 8 classes (plus the base/abstract class).

When designing your base class it's important to keep in the internal functions short and divided along the lines of what you're likely to change on a customer-by-customer basis, that will avoid having to copy large chunks of code to child classes just to change a few lines.

Title: Structuring project (refactoring)

Body:
It sounds like essentially the problem is that you have 30 processes which are similar but vary in inconsistent ways and you want to avoid duplicating code as much as possible while still being able to change any aspect if required.

In that case then the template method pattern can be very useful.

The basic idea is that you'd implement a base/abstract class which more or less functions in the most common way, then for each customer you create a child class which only overrides the methods which need to be changed.

For example:

abstract class BaseCustomer {

    protected $someValue = 5;

    protected function someProcess() {
        return $this->someValue * 2;
    }

    public function execute() {
        return $this->someProcess();
    }

}

class FirstCustomer extends BaseCustomer {
    protected $someValue = 10;
}

class SecondCustomer extends BaseCustomer {
    protected function someProcess() {
        return $this->someValue + 2;
    }
}

Calling ->execute() will return 20 for FirstCustomer and 7 for SecondCustomer.

A further step you can take is to use composition in combination with a template pattern to separate different components of your modules.

For example let's say you have processes which send a CSV file in 5 different formats via either email, FTP or HTTP depending on the customer. You can have two sets of modules: one for the file format and one for the transport method.

Then go something like:

$format = new CustomerOneCSVFormat($data);
$transport = new FTPModule();
$transport->send($format);

In that example you could support 15 different combinations from only 8 classes (plus the base/abstract class).

When designing your base class it's important to keep in the internal functions short and divided along the lines of what you're likely to change on a customer-by-customer basis, that will avoid having to copy large chunks of code to child classes just to change a few lines.