答:
Don't confuse OO classes and ontological classifications. You might naively want to classify a mermaid as both human and fish, but the description of the problem suggests that its swimming behaviour results in the composition of its two parts. OO classes are a means of combining state variables and behaviours which operate on those variables, they package up what something does not describe what something is.

I'd create a Swimmer class, which has two SwimmingBehaviour components - superior ( upper body in humans and merfolk, head end of fish) and inferior ( legs in human, tail in fish and merfolk ). There would be subtypes of swimming behaviours representing human upper body, human legs, fish body, fish tail, and the three types of swimmer would be creating them with different compositions.

Title: Mermaid problem (OOP)

Body:
A Mermaid is half fish and half human. It has upper human body and lower fish body. When under water its upper part swims like a human while its lower part swims like a fish. Please explain how can it swim like a human and a fish at the same time? Create C++ program using class(es) and OOP paradigm to solve this problem.

Note: I don't want the actual code but instead I wanna know the OOP Concepts that can be be used to solve this problem (like multiple inheritance, Composition & Aggregation, Overriding etc...) and why?

The question is how can we make a class "Mermaid" that depicts both human and fish functionality on upper and lower parts of its body (like Inheriting the properties of human and fish on the upper & lower parts of the body respectively). I don't need to know how the functionality would be performed.... Instead the concepts required to satisfy those properties (like swimming like humans and fish at the same time). So forget about the physics part. And as far as the content goes I just copy pasted the question from the OOP paper.

An example "It might be the answer actually" Just an example try:

```<code>Class Human{
/*some data members go here */
public:
 void swim()
{ /*functionality */ }
 };

Class Fish{
/*some data members go here */
public:
 void swim()
{ /*functionality */ }
 };

Class Mermaid:public Human, public Fish{
/*some data members go here */
public:
 void someFunction()
{ /*functionality */ }
 }; –
</code>```


问:
Partitioning REST API resources into areas based on business domains
In a major application REST API that covers several related domains, does it make more sense to split resources into 'areas' based on the business domain they belong to or is it better to to maintain a single model?

For example, there are 'Sales' and 'Inventory' sub-domains. Users of the system typically only care about one domain at a time, but exceptions are possible.
There is an 'Item' concept that exists in both domains so we could implement the 'item' resource in two different ways.

have different resources to represent the concept in each domain, each resource holding only the relevant data:

/sales/items/:id

/inventory/items/:id

have a single resource with all the data to be used in all contexts:

/items/:id

There are also plenty of resources that only belong to one of the domains.

pros of 'areas'

easier to understand the API for users who only care about a single domain

easier to implement resources (less stuff to read/update at a time)

resources can be more specialized/optimized for each particular domain

ability to control access to resources at more granular level

pros of a single unified model

no duplicated resources for concepts that belong to more than one domain

if a user needs to work with multiple domains, he will only have to use a single API that covers all his needs

Is API partitioning as described above a valid way to reduce complexity of both API contract and implementation? I haven't seen it mentioned much anywhere.

Are there any more things that need to be considered to make a decision in favor of either approach?

答:
I think that this is the perfect fit for Bounded Context pattern from Domain Driven Design.

Large models don't scale well, it's better to split them into smaller models (bounded contexts) and explicitly declare their relationships (common entities, interactions between bounded contexts etc.)

In this case you would have two bounded contexts (sales and inventory) with one shared resource (item). Interpretation of item in sales context may be a bit different than in inventory context and that's completely fine.

To use this pattern, you should:

identify the boundaries of different contexts (which you partly did by creating subroots /sales/ and /inventory/)

identify shared resources (item) and explicitly describe what is resource's interpretation in different bounded contexts

identify interactions between bounded contexts (which is probably out of scope of this question)

Note on

pros of a single unified model:
  no duplicated resources for concepts that belong to more than one
  domain

From REST point of view, resource is not duplicated. One resource can be identified by multiple URIs, each can have different representations (fitting for given bounded context).

ContentLicense: CC BY-SA 3.0


问:
Test and deployment environment design for small team
Question is about organizing dev environment for the web development.

There is 2 things to deploy: web site and database schema

We use SVN to keep track of source code

We use RedGate tools to generate migration SQL and to version-control database schema.

It is important to have fresh copy of data in our dev environment.

At first, we just worked each in personal databases. Now our team getting bigger so we have dev server with shared database.

For customer, we created "test" website that we run on our server. And it points to our dev database.

For data - we bring fresh copy of database weekly, so it's just another PITA because we do it by backup/restore and obviously schema different when we bring it back.

Where we have problem now is when we release something for customer to test. They check, it may take some time. By the time they check we might already have some other new features added to TEST site. Now, let's say production missing A, B, and C features. Customer tested A, but B and C need to be tested or changed. A need to go to release.

In big companies were I worked there was DEV, TEST and PROD environments. Pretty much DEV->TEST didn't go unless TEST->PROD happened. This caused just wasted time (realistically). Now we can't afford just sitting, so how do we work fast-paced like this with minimum hickups.

Now because we still waiting from a customer on feedback on "A" - we already "forgot" what else we added. With many people it just get's more complex.

So, I guess question is: How to manage DB/Code version control and separate features publishing in such environment? With minimal bureaucracy.

答:
This is a difficult problem.

You can try to solve this by using feature branching - each new feature is developed in its own branch independently from the other features. You can then have "test" branch where all of these feature branches are merged so that customer can test all features at the same time . When feature A is ready, but B and C are not, you can then create a build only from ready features, in this case A because it is independent from the other features.

So this is theory, but in practice it doesn't work so well. Smaller problem is that you use SVN which supports branching, but working with them in SVN is kind of a PITA. Some distributed VCS would be better (Git, Mercurial, ...). Bigger problem is that features are often not independent from each other (there may be some dependencies between them, several features touch the same code etc.) and it's just not possible to deploy just feature A, especially without specific testing for this build - even though A worked on branch with all feature branches merged, it (A) doesn't necessarily have to work if deployed in isolation ...

Other possibility is non-technical - have some development/release cycle - e.g. SCRUM mandates that after each sprint you have potentially deliverable product. Also working closely with customer (product owner) for testing, making sure she understands how you work so she can align herself to your development process for greater gain ...


问:
Excel worksheet population and fomatting is slow
I have written a VSTO plugin in C# which populates several worksheets.

During the population process cell values or formula are added one at a time according to user-definable criteria taken from a hidden configuration worksheet.

Typically there are 200 rows with around 50 columns, containing SUMPRODUCT formula, VLOOKUPs, etc.

The cells are also formatted and some have conditional formatting.

You're going to say "that sounds slow" - right? You are correct.

Even with the display and auto calculation switched off during population, this still takes forever on my client's standard workstation (i5 processor, 4GB ram).

For example, adding 10 rows usually takes around 15 minutes on those workstations, but on my dev PC (i7 processor, 16gb ram) I can do 200 rows in 2 minutes.

I appreciate that the speed issue is most probably related to the many RPC calls which take place while each cell is modified.

Consequently I have been searching for a way to this more efficiently and have found a way to populate an object array with values, then copy these en-mass to a worksheet.

Unfortunately there is no such option when the worksheet contains mostly formula, and it doesn't address the formatting issues.

What I'm wondering is, are there any alternatives here?
Is there a way to deactivate the RPC calls while the worksheet is built?
Is there an object I can inherit from that I can use in an array to build an off-line copy of the worksheet and then copy en-mass to the worksheet?

I'm pretty sure that any suggestion you can supply will add to my reservoir of ideas, so grateful to all who can chip-in with valuable info!

答:
After several changes performance is perfectly acceptable now.

There are a few things to always bear-in-mind for best performance when making a large number of changes to a worksheet:

set calculations to manual (reset after)

turn off screen updates (and back on after)

if deleting data from a large number of rows, delete entire rows if you can - much faster than deleting a few columns and shifting those below up

if inserting a large number of rows, consider whether you can just update the rows below rather than insert new ones. If preserving formats is an issue, copy existing formats to the new rows with FillDown.


问:
How/when to "build" a Singleton that stores configuration data
I am a junior developer (think "intern-level" experience) working at a small shop more or less alone on a project that consumes data from a database, processes it, and inserts the results into another database. The solution is a Windows service written in C#.

A previous version of the solution used App.config for things like connection strings, time intervals for checking the db for new data, etc. The project manager wants for this information to be stored in a table in the db, and then have a singleton keep that data rather than needing to access the config file. The configuration data needs to be loaded at startup.

My current implementation has the singleton's constructor make a single call to getConfig(), a method that encapsulates the work of getting all the data from the db. We are now in the process of writing code that will check the db at startup to make sure those configuration tables are there and will build them if they aren't.

I have several uncertainties about the design:

1) Is building the config in the constructor the best place so the work is implicit:

```<code>protected override void OnStart(string[] args)
{
    // The first call for an instance, so the object is created & data is loaded
    ConfigSingleton MyConfig = ConfigSingleton.GetInstance;

    // Create object that checks db for data to process; relies on config
    Poller = new Poller();
    Poller.Start();
}
</code>```

or should I make an explicit public call to getConfig() during startup for the sake of clarity:

```<code>protected override void OnStart(string[] args)
{
    ConfigSingleton MyConfig = ConfigSingleton.GetInstance;
    MyConfig.getConfig(); // Explicit call to get config from db

    // Create object that checks db for data to process; relies on config
    Poller = new Poller();
    Poller.Start();
}
</code>```

2) Should the work to check for the config tables be done by a separate, presumably static, class:

```<code>protected override void OnStart(string[] args)
{
    if (!DBChecker.isTableReady())
    {
        DBChecker.BuildTables();
    }

    ConfigSingleton MyConfig = ConfigSingleton.GetInstance;
    MyConfig.getConfig();

    // Create object that checks db for data to process; relies on config
    Poller = new Poller();
    Poller.Start();
}
</code>```

or should it be handled internally by the configuration singleton, so the code would look like one of the variations above?

A somewhat unrelated example that helps clarify the spirit of my question comes from a previous version of the solution (which I've paraphrased):

```<code>// Inside this function, a call is made to BusinessLayer.GetList1()
MyController = new Controller(FirstParam);
MyController.Start();

// Yet here, a similar version is called first and then the result is passed as a parameter
List<Objects> MyList2 = BusinessLayer.GetList2();
MySender = new Sender(SecondParam, MyList2);
MySender.Start();
</code>```

Are there basic rules of thumb that govern when work should be done inside some other work, or outside, passed as parameter, etc, other than the obvious fact that it should at least be consistent?

答:
1) For the sake of clarity, I decided to go with the public call to getConfig().

2) The config object's responsibility is to get and store data from the db. Therefore, it would be better to have a separate class do the work of bootstrapping the config tables. My code now looks something like:

```<code>protected override void OnStart(string[] args)
{
    ConfigBootstrapper.GetConfigTablesReady();
    ConfigSingleton.GetInstance.getConfig();

    Poller = new Poller();
    Poller.Start();

    Logger.Warn("service started.");
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
1) For the sake of clarity, I decided to go with the public call to getConfig().

2) The config object's responsibility is to get and store data from the db. Therefore, it would be better to have a separate class do the work of bootstrapping the config tables. My code now looks something like:

protected override void OnStart(string[] args)
{
    ConfigBootstrapper.GetConfigTablesReady();
    ConfigSingleton.GetInstance.getConfig();

    Poller = new Poller();
    Poller.Start();

    Logger.Warn("service started.");
}


问:
Ways for beginner programmer to practice with C++
So i just finished my first semester of college. In my intro to programming class we made a bunch of super interesting (sarcasm) console applications. Any suggestions on ways other than just messing around with console applications for a beginner C++ student to improve?

答: Find an open source project you find interesting, and contribute.  We love new contributors, and more experienced coders will be reviewing your patches and providing feedback. :)</p>

ContentLicense: CC BY-SA 2.5


问:
What does "Stateful" means in Stateful ViewModel in MVVM
I was reading about some XAML patterns, and there was the Stateful ViewModel, according to what I read it has nothing different than what we as just the "ViewModel".

Here's a description for example :

Stateful View Model:

To create isolation between business logic and presentation, data
  should be removed from the view. The stateful view model pattern moves
  data into the view model using XAML data binding. This allows the view
  model to be tested without constructing a view, and it allows the view
  to change with minimal impact on the business logic.

What is so special about it to be called Stateful ViewModel ? why isn't just called ViewModel

Link : http://www.xamlpatterns.com/stateful-view-model

答: See the Stateless view model, which is the opposite, for more explanation. Basically, in the stateful pattern data is kept on the model whereas in stateless it is not.</p>


问:
Referencing external javascript vs. hosting my own copy
Say I have a web app that uses jQuery.  Is it better practice to host the necessary javascript files on my own servers along with my website files, or to reference them on jQuery's CDN (example: http://code.jquery.com/jquery-1.7.1.min.js)?

I can see pros for both sides:

If it's on my servers, that's one less external dependency; if jQuery went down or changed their hosting structure or something like that, then my app breaks.  But I feel like that won't happen often; there must be lots of small-time sites doing this, and the jQuery team will want to avoid breaking them.

If it's on my servers, that's one less external reference that someone could call a security issue

If it's referenced externally, then I don't have to worry about the bandwidth to serve the files (though I know it's not that much).

If it's referenced externally and I'm deploying this web site to lots of servers that need to have their own copies of all the files, then it's one less file I have to remember to copy/update.

答:
I could be wrong, but implementing document.write overwrites anything that the DOM has. Since it's good practice to put JavaScript files at the end of the body,

I propose the following method based on previous answers:

```<code><script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">

if(!window.jQuery)
{
    //Creates the script element
    var script = document.createElement('script');
    //Adds the type attribute with "text/javascript" value
        script.setAttribute('type', 'text/javascript');
    //Adds the source attribute and populates it
        script.setAttribute('src', 'Put_The_Relative_Path_To_Your_JavaScript_File_Here');
    //Adds it to the end of the body, as it is good practice, to prevent render-blocking.
    document.body.appendChild(script);

}

//Note that there's no need for you to verify with an onload function, since all scripts
//must be loaded before going to the next one!

</script>
</code>```

Body:
I could be wrong, but implementing document.write overwrites anything that the DOM has. Since it's good practice to put JavaScript files at the end of the body,

I propose the following method based on previous answers:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">

if(!window.jQuery)
{
    //Creates the script element
    var script = document.createElement('script');
    //Adds the type attribute with "text/javascript" value
        script.setAttribute('type', 'text/javascript');
    //Adds the source attribute and populates it
        script.setAttribute('src', 'Put_The_Relative_Path_To_Your_JavaScript_File_Here');
    //Adds it to the end of the body, as it is good practice, to prevent render-blocking.
    document.body.appendChild(script);

}

//Note that there's no need for you to verify with an onload function, since all scripts
//must be loaded before going to the next one!

</script>


问:
Automatic builders/chain setters for Java?
Consider that code:

```<code>FancyClass c = new FancyClass();
s.setParameter(value);
s.setParameter2(value2);
//a lot of parameters
</code>```

It is really naive, so we can use a builder pattern:

```<code>FancyClass c = new FancyClassBuilder().setParameter(value).setParameter2(value2).build()
</code>```

It is okay, but what if we have to use a lot of setters during a program?

```<code>s.setParameter(value)
s.setParameter1(value)
s.setParameter2(value)
s.setParameter3(value)
//more and more...
</code>```

It will be more efficient and less boilerplated:

```<code>s.setParameter(value).setParameter1(value).setParameter2(value)
 .setParameter3(value)
</code>```

Looks more okay and it allows programmer not do this action: (i hate it):

```<code>s.setParamter()
// a lot of doing smth
s.setParameter2()
</code>```

even there is no neccessary to put this setters away (because it is a some legacy issue, somebody just tap the enter twice and someone type in a other code...

What if...

```<code>@SetterChain
class MyFancyClass {
  public void setParameter(Parameter p) {}
  public Parameter getParameter(Parameter p) {}
  public void setParameter2(Parameter p) {}
  public Parameter getParameter2(Parameter p) {}
}

//somewhere else...

MyFancyClass s = new MyFancyClass()

//a long time ago

s.set().parameter(value).parameter2(value); //and more and more...
</code>```

Cool stuff or no? Is this solution would significally increase a code quality or not and its a wreck and why?

答:
While not exactly the same as what you suggested, something along these lines already exists. If you want to provide this feature to your Java projects, you may consider using Lombok. It has a @Builder annotation, which allows you to create a builder with pretty much a single line of code and at the same time avoid exposing or even writing setters.

Here's how it can be used:

```<code>import lombok.Builder;

@Builder
public class Person {

    private String name;

    private int age;

    public String getName() { return name; }

    public int getAge() { return age; }
}
</code>```

To set the fields on an instance of this class, you would now call:

```<code>Person instance = Person.builder().name("Tom").age(25).build();
</code>```

In fact, if you decide to use Lombok, you can have it generate the getters for you and make the code even shorter:

```<code>import lombok.Builder;
import lombok.Getter;

@Builder
public class Person {

    @Getter
    private String name;

    @Getter
    private int age;
}
</code>```

The downsides include the necessity to set up Lombok for your project and include a dependency on it. I've worked with it on a couple of project and I can say it's relatively painless when environment setup is concerned.

I think the worst drawback is that of limited debugging capabilities (as your original sources will not contain the lines that are actually run).

Anyway, it's out there for you to try and realize the pros and cons of such a solution.

Another option to have this kind of syntactic sugar would be to switch to Groovy, which has quite a gentle learning curve for Java developers and very nice support for builders as well thanks to its AST transformations.

Body:
While not exactly the same as what you suggested, something along these lines already exists. If you want to provide this feature to your Java projects, you may consider using Lombok. It has a @Builder annotation, which allows you to create a builder with pretty much a single line of code and at the same time avoid exposing or even writing setters.

Here's how it can be used:

import lombok.Builder;

@Builder
public class Person {

    private String name;

    private int age;

    public String getName() { return name; }

    public int getAge() { return age; }
}

To set the fields on an instance of this class, you would now call:

Person instance = Person.builder().name("Tom").age(25).build();

In fact, if you decide to use Lombok, you can have it generate the getters for you and make the code even shorter:

import lombok.Builder;
import lombok.Getter;

@Builder
public class Person {

    @Getter
    private String name;

    @Getter
    private int age;
}

The downsides include the necessity to set up Lombok for your project and include a dependency on it. I've worked with it on a couple of project and I can say it's relatively painless when environment setup is concerned.

I think the worst drawback is that of limited debugging capabilities (as your original sources will not contain the lines that are actually run).

Anyway, it's out there for you to try and realize the pros and cons of such a solution.

Another option to have this kind of syntactic sugar would be to switch to Groovy, which has quite a gentle learning curve for Java developers and very nice support for builders as well thanks to its AST transformations.


问:
If Scala runs on the JVM, how can Scala do things that Java seemingly cannot?
I just learned about Scala yesterday, and I'd like to learn more about it. One thing that came to mind, however, from reading the Scala website is that if Scala runs on the JVM, then how is it possible for bytecode compiled from Scala source to be able to achieve things that Java can't readily do, such as (but not limited to) reified generics?

I understand that the compiler is what generates the bytecode; so as long as the compiler can massage source code into valid bytecode supported by the JVM, then both should be equivalent. But I was under the impression that Java couldn't even reify its own generics, so how could another compiler be able to pull this off?

答:
Reified generics do not require JVM support. Yes, they would be easier and most performant with JVM support, but JVM support is not necessary. For instance, a Scala compiler could, for every class featuring a type variable, add a field that stores the corresponding object:

```<code>class List<T> {

}

void test() {
    List<?> list = new List<String>();
    List<Integer> intList = (List<Integer>) list;
}
</code>```

would be compiled to

```<code>class List<T> {
    final Class<T> tClass;
    public List(Class<T> tClass) {
        this.tClass = tClass;
    }

    public <O> List<O> castTo(Class<O> oClass) {
        if (tClass == oClass) {
            return (List<O>) this;
        } else {
            throw new ClassCastException("Incompatible type parameter: " + tClass);
        }
    }
}

void test() {
    List<?> list = new List<String>(String.class);
    List<Integer> intList = list.castTo(Integer.class);
}
</code>```

There are of course more elaborate translation strategies that more seamlessly integrate with the host type system, for instance by actually having separate classes for different type arguments to the same generic type:

```<code>class List<T> {

}

class List#Integer extends List<Integer> { }

class List#String extends List<String> { }

void test() {
    List<?> list = new List#String();
    List<Integer> intList = (List#Integer) list;
}
</code>```

(There would of course be some challenges not apparent in this trivial example, for instance recursive type arguments, proper isolation of different class loaders, ...)

The reason Java does not have reified generics is not that reification would be impossible on the JVM, but that reified generics would have broken backwards compatibility (in particular binary compatibility) with existing Java programs - something Scala did not have to worry about.

Body:
Reified generics do not require JVM support. Yes, they would be easier and most performant with JVM support, but JVM support is not necessary. For instance, a Scala compiler could, for every class featuring a type variable, add a field that stores the corresponding object:

class List<T> {

}

void test() {
    List<?> list = new List<String>();
    List<Integer> intList = (List<Integer>) list;
}

would be compiled to

class List<T> {
    final Class<T> tClass;
    public List(Class<T> tClass) {
        this.tClass = tClass;
    }

    public <O> List<O> castTo(Class<O> oClass) {
        if (tClass == oClass) {
            return (List<O>) this;
        } else {
            throw new ClassCastException("Incompatible type parameter: " + tClass);
        }
    }
}

void test() {
    List<?> list = new List<String>(String.class);
    List<Integer> intList = list.castTo(Integer.class);
}

There are of course more elaborate translation strategies that more seamlessly integrate with the host type system, for instance by actually having separate classes for different type arguments to the same generic type:

class List<T> {

}

class List#Integer extends List<Integer> { }

class List#String extends List<String> { }

void test() {
    List<?> list = new List#String();
    List<Integer> intList = (List#Integer) list;
}

(There would of course be some challenges not apparent in this trivial example, for instance recursive type arguments, proper isolation of different class loaders, ...)

The reason Java does not have reified generics is not that reification would be impossible on the JVM, but that reified generics would have broken backwards compatibility (in particular binary compatibility) with existing Java programs - something Scala did not have to worry about.


问:
Are there real world examples demonstrating reasonable performance improvement by using move semantics?
(I've asked a similar question on SO but unfortunately it might not be proper, so I also put here; please kindly point out if you think it's a duplicate.)

I've heard many words about the move semantics (essentially rvalue) introduced in C++11. In theory, it should bring much performance improvement due to the fact it avoids unnecessary copies.

However, there have already been some optimizations for legacy code during compilation to deal with the inefficient temporary copies, such as:

(named) return value optimizations

constructor copy elision

And additionally for frequently used data structures, some C++ standard libraries use special optimizations (e.g., small string optimization for std::string).

More importantly, although some pieces of legacy code are really inefficient they don't result in much latency since they are

not frequently invoked

modern computers have enough physical memories for them

So I'm asking: are there real-world examples that greatly accelerate the performance when using modern C++ (C++11/14/17) syntax, or improve the performance by a reasonable percentage (e.g., >10%) overall?

I expect that the answer can be any of the 3 categories:

```<code>#include <vector>
using std::vector;
using std::size_t;

size_t const MAX = NNN;  // NNN is specified by -DNNN=xxx option
size_t const NUM = NNN/100;

vector<int> factory(size_t size) {
  vector<int> v;
  for (size_t i = 0u; i < size; ++i) {
    v.push_back(i);
  }
  return v;
}

// Version 1
/// void doubles(vector<int> & v) {
// Version 2
void doubles(vector<int> && v) {
  for (size_t i = 0u; i < v.size(); ++i) {
    v[i] = v[i] * 2;
  }
}

int main() {
// Version 1
/// vector<int> v = factory(MAX);
/// doubles(v);
// Version 2
  doubles(factory(MAX));
}
</code>```

Some performance bugs/bottlenecks existing in real world repositories that can be handled modern C++ well.

Some profiling for a piece of code that show the improvement.

Starting by modifying some of the above trivial code to help me get an example that can bring the performance benefit.

And the improvement can still be viewed with default (e.g., -O0) compilation options (so -fno-elide-constructors is not allowed during compilation) by gcc or clang or MSVC.

I ask this question because I was doing a survey on the move semantics impact on performance for real world programs but after I tried some (trivial) code and did some basic profiling myself, I found that I simply cannot find the significant differences. So please forgive me if you feel it stupid/pedantic.

答:
If you need an overview of the benefits and best-practices on move semantics, please watch some of the conference recordings on the isocpp website.
(At the bottom there's a link to older recordings.)

Bjarne Stroustrup provide a prime motivating example on his website.

http://www.stroustrup.com/C++11FAQ.html#rval

Just consider the typical implementation of std::swap, assuming that this method does not have special access to the type.

The sample code and comments below are copied verbatim from the link above.

```<code>template<class T> swap(T& a, T& b)      // "old style swap"
{
    T tmp(a);   // now we have two copies of a
    a = b;      // now we have two copies of b
    b = tmp;    // now we have two copies of tmp (aka a)
}
</code>```

When new objects are created, it incurs the cost of copying that object. Most of the time, this implies deep copying - share nothing, because each object must be prepared to be independently modifiable, because there's nothing to imply otherwise.

But in this example, it is clear that tmp is a temporary. What can we do to avoid the cost of deep copying in this case?

As @DocBrown points out in comment, the benefits of move semantics is dependent on:

The coding style

The implementation of data structures used most heavily in the code

In object oriented programming, there is a contentious issue: copying or sharing? (Another contentious issue is the mutable or immutable.)

Most software programs will spend time copying stuff. The questions are:

Does the situation require copying?

Is there a cheaper way of copying?

If two or more instances of code need access to the same object, and if all of these instances promise they will never modify the object (i.e. cause its states to change), then perhaps sharing the object reference (by pointer or other means) may be sufficient.

If one instance of code needs to make a copy so that the object can be modified, it will not benefit from most "make copy cheap" scheme.

Sometimes it is a middle ground. An object has multiple properties, and the code wants to make a copy so that one or several properties can be modified. In this case, "make copy cheap" would require one to allow sharing of unchanged properties between the old and new object. (Note: move semantics does not enable this. I mention this because move semantics have to face a number of competing other kinds of semantics.)

C++ code that is written to a C style, with its heavy use of pointers, may not see any benefit, because such code already freely share any data structure by  sharing pointers, and do so without much syntactic safeguards.

C++ code that already implements reference counting (such as OpenCV's Mat class), Microsoft COM pointers (com_ptr_t), etc., allow multiple instances of code to share the same piece of data.

The kind of C++ code that may benefit from move semantics are those that

Mainly rely on STL data structures (most importantly std::vector),

Uses "value semantics" heavily (makes objects immutable, makes copies of objects heavily, prefers copying values to sharing references), and

In order for its performance improvements to be measurable,

It should be doing some heavy-lifting (i.e. the amount of data and computation should be reasonably big to be measurable)

It should not be dominated by other types of bottlenecks (such as disk, IO, database, etc.).

One may say that each of those factors are questionable, and rightly so.

There are C++ programs that implement their own reference counting, reference-sharing schemes, lazy (on-demand) evaluation, asynchronous operations or promise-futures, etc., long before C++11 was conceived. These C++ programming environments chose a trajectory that make them largely independent of the evolutions of C++. From a historical perspective, they might be right, because the evolutions of C++ had apparently been stagnant for a decade or so, where most of the innovations are thought to be doable with library code (such as the Boost Libraries) without requiring changes to the language standard.

Body:
If you need an overview of the benefits and best-practices on move semantics, please watch some of the conference recordings on the isocpp website.
(At the bottom there's a link to older recordings.)

Bjarne Stroustrup provide a prime motivating example on his website.

http://www.stroustrup.com/C++11FAQ.html#rval

Just consider the typical implementation of std::swap, assuming that this method does not have special access to the type.

The sample code and comments below are copied verbatim from the link above.

template<class T> swap(T& a, T& b)      // "old style swap"
{
    T tmp(a);   // now we have two copies of a
    a = b;      // now we have two copies of b
    b = tmp;    // now we have two copies of tmp (aka a)
}

When new objects are created, it incurs the cost of copying that object. Most of the time, this implies deep copying - share nothing, because each object must be prepared to be independently modifiable, because there's nothing to imply otherwise.

But in this example, it is clear that tmp is a temporary. What can we do to avoid the cost of deep copying in this case?

As @DocBrown points out in comment, the benefits of move semantics is dependent on:

The coding style

The implementation of data structures used most heavily in the code

In object oriented programming, there is a contentious issue: copying or sharing? (Another contentious issue is the mutable or immutable.)

Most software programs will spend time copying stuff. The questions are:

Does the situation require copying?

Is there a cheaper way of copying?

If two or more instances of code need access to the same object, and if all of these instances promise they will never modify the object (i.e. cause its states to change), then perhaps sharing the object reference (by pointer or other means) may be sufficient.

If one instance of code needs to make a copy so that the object can be modified, it will not benefit from most "make copy cheap" scheme.

Sometimes it is a middle ground. An object has multiple properties, and the code wants to make a copy so that one or several properties can be modified. In this case, "make copy cheap" would require one to allow sharing of unchanged properties between the old and new object. (Note: move semantics does not enable this. I mention this because move semantics have to face a number of competing other kinds of semantics.)

C++ code that is written to a C style, with its heavy use of pointers, may not see any benefit, because such code already freely share any data structure by  sharing pointers, and do so without much syntactic safeguards.

C++ code that already implements reference counting (such as OpenCV's Mat class), Microsoft COM pointers (com_ptr_t), etc., allow multiple instances of code to share the same piece of data.

The kind of C++ code that may benefit from move semantics are those that

Mainly rely on STL data structures (most importantly std::vector),

Uses "value semantics" heavily (makes objects immutable, makes copies of objects heavily, prefers copying values to sharing references), and

In order for its performance improvements to be measurable,

It should be doing some heavy-lifting (i.e. the amount of data and computation should be reasonably big to be measurable)

It should not be dominated by other types of bottlenecks (such as disk, IO, database, etc.).

One may say that each of those factors are questionable, and rightly so.

There are C++ programs that implement their own reference counting, reference-sharing schemes, lazy (on-demand) evaluation, asynchronous operations or promise-futures, etc., long before C++11 was conceived. These C++ programming environments chose a trajectory that make them largely independent of the evolutions of C++. From a historical perspective, they might be right, because the evolutions of C++ had apparently been stagnant for a decade or so, where most of the innovations are thought to be doable with library code (such as the Boost Libraries) without requiring changes to the language standard.


答:
In a nutshell, Scala can do it because the Scala compiler is a master in code transformation/generation. Which means Java could do it too (maybe it does already). The trick is not made at the bytecode level but at the source level.

Could you guess the output of this code:

```<code>def test[T](f : => Any) : T = {
  try { val x = f.asInstanceOf[T]
    println("f.asInstanceOf did not raise an error")
      x
  }
  catch { case e : Throwable =>
    println("f.asInstanceOf did raise an error")
    throw e
  }
}

val x = test[Int]("x")
</code>```

(Not so) Suprisingly it outputs

```<code>f.asInstanceOf did not raise an error
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer at scala.runtime.BoxesRunTime.unboxToInt(BoxesRunTime.java:105)
</code>```

... 33 elided

Because of type erasure, f.asInstanceOf[T] can not fail but obviouly a String is not an Int so it has to fail somewhere. Fortantely Scala brings solutions to this problem:

```<code>import shapeless.Typeable
import shapeless.syntax.typeable._

def test[T : Typeable](f : => Any) : T = {

    f.cast[T] match {
        case Some(x) => {
            println("f.cast[T] succeed")
            x
        }
        case None    => {
            println("f.cast[T] failed")
            throw new RuntimeException("cast failed!")
        }
    }
}

val x = test[Int]("x")
</code>```

The main difference here is we declare T as Typeable. Scala have several ways to provide runtime representations of types.

Title: If Scala runs on the JVM, how can Scala do things that Java seemingly cannot?

Body:
I just learned about Scala yesterday, and I'd like to learn more about it. One thing that came to mind, however, from reading the Scala website is that if Scala runs on the JVM, then how is it possible for bytecode compiled from Scala source to be able to achieve things that Java can't readily do, such as (but not limited to) reified generics?

I understand that the compiler is what generates the bytecode; so as long as the compiler can massage source code into valid bytecode supported by the JVM, then both should be equivalent. But I was under the impression that Java couldn't even reify its own generics, so how could another compiler be able to pull this off?

Body:
In a nutshell, Scala can do it because the Scala compiler is a master in code transformation/generation. Which means Java could do it too (maybe it does already). The trick is not made at the bytecode level but at the source level.

Could you guess the output of this code:

def test[T](f : => Any) : T = {
  try { val x = f.asInstanceOf[T]
    println("f.asInstanceOf did not raise an error")
      x
  }
  catch { case e : Throwable =>
    println("f.asInstanceOf did raise an error")
    throw e
  }
}

val x = test[Int]("x")

(Not so) Suprisingly it outputs

f.asInstanceOf did not raise an error
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer at scala.runtime.BoxesRunTime.unboxToInt(BoxesRunTime.java:105)

... 33 elided

Because of type erasure, f.asInstanceOf[T] can not fail but obviouly a String is not an Int so it has to fail somewhere. Fortantely Scala brings solutions to this problem:

import shapeless.Typeable
import shapeless.syntax.typeable._

def test[T : Typeable](f : => Any) : T = {

    f.cast[T] match {
        case Some(x) => {
            println("f.cast[T] succeed")
            x
        }
        case None    => {
            println("f.cast[T] failed")
            throw new RuntimeException("cast failed!")
        }
    }
}

val x = test[Int]("x")

The main difference here is we declare T as Typeable. Scala have several ways to provide runtime representations of types.


问:
Deploying Qt-based app on Mac OS X
I wrote a cross platform application and I distributed it successfully for Windows and Linux (and tested them on "clean" virtual systems, with no other additional software and/or libraries installed).

I have already compiled my application on my Mac computer, but I don't know if my application will work on other Mac computers.

I don't have two Macs, also, (as far as I know) it's difficult to install Mac OS X on a virtual machine with "legal" discs or without having to perform a process similar to building a Hackintosh, this means that I cannot test my app on a virtual machine (in VirtualBox).

So may question would be: Is there any way of making sure that my application will actually run on other Mac systems (without the need of using another computer)?

As an additional note, I wrote my application by using the Qt framework.

答:
I came up with this problem last week and I got my information from this source:

You can check what other libraries your application links to using the otool:

```<code>otool -L plugandpaint.app/Contents/MacOs/plugandpaint
</code>```

Here is what the output looks like for a Qt application example:

```<code>plugandpaint.app/Contents/MacOS/plugandpaint:
/System/Library/Frameworks/Carbon.framework/Versions/A/Carbon
        (compatibility version 2.0.0, current version 128.0.0)
/System/Library/Frameworks/QuickTime.framework/Versions/A/QuickTime
        (compatibility version 1.0.0, current version 10.0.0)
/usr/lib/libz.1.dylib
        (compatibility version 1.0.0, current version 1.2.3)
/System/Library/Frameworks/ApplicationServices.framework/Versions/A/ApplicationServices
        (compatibility version 1.0.0, current version 22.0.0)
/usr/lib/libstdc++.6.dylib
        (compatibility version 7.0.0, current version 7.3.0)
/usr/lib/libgcc_s.1.dylib
        (compatibility version 1.0.0, current version 1.0.0)
/usr/lib/libmx.A.dylib
        (compatibility version 1.0.0, current version 92.0.0)
/usr/lib/libSystem.B.dylib
        (compatibility version 1.0.0, current version 88.0.0)
</code>```

If you see Qt libraries in the output, it probably means that you have both dynamic and static Qt libraries installed on your machine.

I don't take credit for this answer, I'm just a pointer to the source of information.

I use macdeployqt for my applications.

Title: Deploying Qt-based app on Mac OS X

Body:
I came up with this problem last week and I got my information from this source:

You can check what other libraries your application links to using the otool:

otool -L plugandpaint.app/Contents/MacOs/plugandpaint

Here is what the output looks like for a Qt application example:

plugandpaint.app/Contents/MacOS/plugandpaint:
/System/Library/Frameworks/Carbon.framework/Versions/A/Carbon
        (compatibility version 2.0.0, current version 128.0.0)
/System/Library/Frameworks/QuickTime.framework/Versions/A/QuickTime
        (compatibility version 1.0.0, current version 10.0.0)
/usr/lib/libz.1.dylib
        (compatibility version 1.0.0, current version 1.2.3)
/System/Library/Frameworks/ApplicationServices.framework/Versions/A/ApplicationServices
        (compatibility version 1.0.0, current version 22.0.0)
/usr/lib/libstdc++.6.dylib
        (compatibility version 7.0.0, current version 7.3.0)
/usr/lib/libgcc_s.1.dylib
        (compatibility version 1.0.0, current version 1.0.0)
/usr/lib/libmx.A.dylib
        (compatibility version 1.0.0, current version 92.0.0)
/usr/lib/libSystem.B.dylib
        (compatibility version 1.0.0, current version 88.0.0)

If you see Qt libraries in the output, it probably means that you have both dynamic and static Qt libraries installed on your machine.

I don't take credit for this answer, I'm just a pointer to the source of information.

I use macdeployqt for my applications.


问:
Is template "metaprogramming" in Java a good idea?
There is a source file in a rather large project with several functions that are extremely performance-sensitive (called millions of times per second). In fact, the previous maintainer decided to write 12 copies of a function each differing very slightly, in order to save the time that would be spent checking the conditionals in a single function.

Unfortunately, this means the code is a PITA to maintain. I would like to remove all the duplicate code and write just one template. However, the language, Java, does not support templates, and I'm not sure that generics are suitable for this.

My current plan is to write instead a file that generates the 12 copies of the function (a one-use-only template expander, practically). I would of course provide copious explanation for why the file must be generated programmatically.

My concern is that this would lead to future maintainers' confusion, and perhaps introduce nasty bugs if they forget to regenerate the file after modifying it, or (even worse) if they modify instead the programmatically-generated file. Unfortunately, short of rewriting the whole thing in C++, I see no way to fix this.

Do the benefits of this approach outweigh the disadvantages? Should I instead:

Take the performance hit and use a single, maintainable function.

Add explanations for why the function must be duplicated 12 times, and graciously take the maintenance burden.

Attempt to use generics as templates (they probably don't work that way).

Yell at the old maintainer for making code so performance-dependent on a single function.

Other method to maintain performance and maintainability?

P.S. Due to the poor design of the project, profiling the function is rather tricky... however, the former maintainer has convinced me that the performance hit is unacceptable. I assume by this he means more than 5%, though that is a complete guess on my part.

Perhaps I should elaborate a bit. The 12 copies do a very similar task, but have minute differences. The differences are in various places throughout the function, so unfortunately there are many, many, conditional statements. There are effectively 6 "modes" of operation, and 2 "paradigms" of operation (words made up by myself). To use the function, one specifies the "mode" and "paradigm" of operation. This is never dynamic; each piece of code uses exactly one mode and paradigm. All 12 mode-paradigm pairs are used somewhere in the application. The functions are aptly named func1 to func12, with even numbers representing the second paradigm and odd numbers representing the first paradigm.

I'm aware that this is just about the worst design ever if maintainability is the goal. But it seems to be "fast enough", and this code hasn't needed any changes for a while... It's also worth noting that the original function has not been deleted (although it is dead code as far as I can tell), so refactoring would be simple.

答:
You can solve the problem of specialized methods by using Scala language.

Scala can inline methods, this (in combination with easy higher order function usage) makes it possible to avoid code duplication for free — this looks like the main problem mentioned in your answer.

But also, Scala has syntactic macros, which makes it possible to do a lot of things with code at compile time in a type-safe manner.

And the common problem of boxing primitive types when used in generics is possible to solve in Scala, too: it can do generic specialization for primitives to avoid boxing automatically by using @specialized annotation — this thing is built into language itself. So, basically, you'll write one generic method in Scala, and it will run with the speed of specialized methods. And if you need fast generic arithmetics too, it's easily doable by using Typeclass "pattern" for injecting the operations and values for different numeric types.

Also, Scala is awesome in many other ways. And you don't have to rewrite all code to Scala, because Scala <-> Java interoperability is excellent. Just make sure to use SBT (scala build tool) for building the project.


问:
Implementation of Asynchronous function call in C
I took it upon myself recently to work towards making a general-purpose Translator to automatically translate js programs into C, but I got stuck when thinking of asynchronous behaviour. Using ANSI / POSIX C, and only allowing yourself to use a library for a threadpool implementation, how would you go about implementing asynchronous function calls in C. The methodology must be thread-safe. When I came up with my approach, I was inspired by this source's use of what they call the Asynchronous Dispatcher pattern: https://doanduyhai.wordpress.com/2012/08/04/design-pattern-the-asynchronous-dispatcher/

答:
Are you aiming at making a general-purpose Javascript to C automatic translator (that is, a compiler from Javascript to C)?

This is quite challenging and will take you several years of work, in particular if you want to make an efficient Javascript to C compiler (something which won't be much slower than most current Javascript implementations)

Notice that semantically Javascript has a lot of common features with Scheme (dynamic typing, garbage collection, closures, and perhaps run-time evaluation), even if the syntax is very different. Its prototype object model is indeed not in Scheme, but you could find some implementations of prototype object models in Scheme quite similar to the Javascript model. So I definitely recommend studing Scheme and its formal semantics, and looking inside several Scheme to C translators (Bigloo, Chicken, Stalin, ...). In contrast to Scheme, Javascript was initially ill-defined (its first implementation was a few weeks hack!) and has some unpleasant peculiarities (result of [] + {}, etc...) that are painful to handle in a Javascript to C translator.

Then I strongly recommend reading C.Queinnec Lisp In Small Pieces book. Read also Scott's programming language pragmatics book.

The asynchronous aspect of Javascript is similar to coroutines and to continuation passing style (a.k.a. CPS). Look into Continuation Passing C, it is translating a program in CPC (an extended dialect of C, with yield, spawn, wait, ... primitives usable for asynchronous computations) into plain C using continuation passing style techniques.

If your goal is not a general-purpose translator of Javascript to C, but simply to manually rewrite a specific Javascript program into C, coroutines, callbacks, closures, and CPS are still useful concepts to assess.
And you could even generate or write code for CPC then use the CPC compiler to get ordinary C.

You might also implement your asynchronous computations using the deprecated setcontext(3) routine, but I don't recommend using that since it is deprecated, very low level (basically it is setting all the machine registers), somehow machine specific, and difficult to debug.

Of course you could also consider multi-threading, e.g. POSIX pthreads or C11 threads.


答:
Know the feeling. I was frustrated at the same thing. Console applications aren't very interesting what with all that string reversing and linked lists, but at the same time there is no way I can argue with the other responses given.

To answer your question, pick a topic your interested in. Seeing as I learned C/C++ I headed in the direction of learning GTK+ and SDL. GTK+ should give you a good start on GUI and SDL on 2D graphics (this could lead onto opengl later on). I also recommend you going over beej's guide to networking (its a free online ebook), this should give you a start on networking.

Title: Ways for beginner programmer to practice with C++

Body: So i just finished my first semester of college. In my intro to programming class we made a bunch of super interesting (sarcasm) console applications. Any suggestions on ways other than just messing around with console applications for a beginner C++ student to improve?


问:
Static console object or dependency injection?
For a current project I have created a Console class which wraps up C++'s usual cout, writes output to a file or uses Console::WriteLine depending on the environment. Currently I've setup my code base to inject a console object into each class that I use, making all of them extend a base class: Debuggable. This seemed like a great plan at first but now that I have to pass the console to every object and ensure that it is created before all of them I'm having second thoughts.

Usually consoles seem to be handled with static objects, so I'm considering changing my implementation to use a static instance of the console that all the objects can use but I feel that this removes an element of control, I can't have more than one potential console with different formats and targets.

I understand that there's a lot of discussion about dependency injection, I'm interested specifically in the case of utilities such as a console.

答:
Usually when there is an object, which needs to be used everywhere (like your logger class), then using the singleton makes sense. And that is one of rare cases where the singleton is not an anti pattern.

You can implement it in such case that it is possible to create a mock (if you going to unit tests).

So, something like this :

```<code>class Logger
{
public:

    typedef Debugable* (Fnc)();

    static Debugable& Instance()
    {
        static Debugable* p = f();
        return *p;
    }

    void SetCreator( Fnc newf ){ f = newf; }

private:
    static Debugable* DefaultCreator(){ return 0; }
    static Fnc f = DefaultCreator();
};
</code>```

First you need to set the creator function somewhere (do this only once) :

```<code>Debugable* CreateLogger()
{
   return new StdOutputLogger;
};

//...
// somewhere
Logger::SetCreator( CreateLogger );
</code>```

then use it as a singleton :
    Logger::Instance() << "log this message";

In unit tests, you need to create a mock object :

struct MockLogger : public Debugable
{
  // methods
};

Set it in the setUp() function :

```<code>MockLogger mock;
Debugable* CreateMock()
{
   return new StdOutputLogger;
};

void setUp()
{
  Logger::SetCreator( CreateMock );
}
</code>```

then check the accesses to the mock.

Body:
Usually when there is an object, which needs to be used everywhere (like your logger class), then using the singleton makes sense. And that is one of rare cases where the singleton is not an anti pattern.

You can implement it in such case that it is possible to create a mock (if you going to unit tests).

So, something like this :

class Logger
{
public:

    typedef Debugable* (Fnc)();

    static Debugable& Instance()
    {
        static Debugable* p = f();
        return *p;
    }

    void SetCreator( Fnc newf ){ f = newf; }

private:
    static Debugable* DefaultCreator(){ return 0; }
    static Fnc f = DefaultCreator();
};

First you need to set the creator function somewhere (do this only once) :

Debugable* CreateLogger()
{
   return new StdOutputLogger;
};

//...
// somewhere
Logger::SetCreator( CreateLogger );

then use it as a singleton :
    Logger::Instance() << "log this message";

In unit tests, you need to create a mock object :

struct MockLogger : public Debugable
{
  // methods
};

Set it in the setUp() function :

MockLogger mock;
Debugable* CreateMock()
{
   return new StdOutputLogger;
};

void setUp()
{
  Logger::SetCreator( CreateMock );
}

then check the accesses to the mock.


问:
How do I design an arbitrary system in an interview?
A common question in Tech Interview is to design a particular system, usually an existing product of the company. For example, "Design Google Docs".

What is the expected answer for such a question? I mean, such systems surely have a complex design which is beyond the scope of any interview. What are the interviewers expecting in such a short time?

答:
The point behind asking this kind of a question is to gain an insight into your mind. A common question I use is to ask programmers to design a system that can simulate PacMan.

And yes, I look for use cases first, it shows me that the person is thinking.
Then, for multithreading, consideration of data structures first (ones that could be used for the problem, then more appropriate or specific ones with the whys of the decision).

This is a considered must for senior development positions.  It is both silly and pointless for people to sit and answer questions on sort implementations at this level of developer experience. System design is what I would expect at this level.


问:
In C++, should I ever declare a local variable in the corresponding header?
So for example, I create a class with two functions:

foo.h

```<code>class foo
{
public:
    foo();
    void bar();
    void ey();
    bool m_memberBool;
    bool localBool; // ??? Should I put this here?
};
</code>```

foo.cpp

```<code>#include "foo.h"

foo::foo() {
    bool m_memberBool = true;
}
void foo::bar() {
    bool localBool = true;
    if (localBool && m_memberBool) {
        ey();
    }
}
void foo::ey() {
    m_memberBool = false;
}
</code>```

Should I ever include that local variable, or any local variable ever in a header? If not, should I ever document it in the header?

答:
Member variablesare the value types that is associated with the class and thus will be part of Object of that class.

Local variables are the value holders that are local to scope. Scope here could be functions, if conditions or swith case, typically everything where you use {}.

Now if you have to decide where to put which then use these rules of thumb:

Member variable is an attribute of class. which means it might be used by methods and/or manipulators of the class objects.

Local variable is required locally for manipulations or as temporary value holder, which means it is useful for current scope only.

I hope that helped. Please comment queries if any.


答:
Note: Initially I answered this question without realizing that it is about the use of singletons for debugging purposes. So, the first part of my answer is for using singletons in general, not for debugging.  The second part of my answer addresses the issue of debugging.  (I have added to it a couple of points I made in comments.)

Part 1 - singletons in general (without respect to debugging)

My recommendation would be to not go with a singleton. My experience is that "the singleton" is not a pattern, but an anti-pattern by its very nature.  (But let's not turn this into yet one more episode of the singleton war, shall we?)

You say that you are "interested specifically in the case of utilities such as a console." I am afraid that a console is not a utility. It is a stream to which you send output.

Text sent to it gets buffered, so it has state.

Concurrently calling it from multiple threads might not crash it, but it will result in misplaced linefeeds and garbled lines, so it cannot really be thought of as amenable to multi-threading.

Even if it is convenient for some to think of it as a singleton, conceptually it is not, as evidenced by the fact that you can redirect it to other devices like files, printers, etc.

So, either you can treat it as what it really is, (an output stream, passed to whoever needs to output stuff,) or treat it like some special public global one-of-a-kind thing, the nature of which everyone has intimate knowledge of, and then rely on the sorcery provided by the library and the OS beneath the scenes to undo your assumptions and make it work like the output stream that it really is, as far as the rest of the system is concerned.

True, you may end up making it a singleton due to pragmatic concerns of convenience vs. correctness, but I suppose that if convenience was your primary concern then you would not be asking the question in the first place.  So, this answer is to say that there do in fact exist other engineers besides you, like me, who will tenaciously pursue the "do it right, avoid singletons" approach.

Part 2 - singletons for debugging

I seem to have missed the point about debugging in the original question. When it comes to debugging, I do not have objections with the use of singletons. I would use a singleton as a debugging helper, I would not use a singleton for anything else.  But then again, we do not test debugging helpers.  If it requires testing, then it is not just a debugging helper.

In the past I have tried passing debugging facilities as dependencies to objects in the same way that I pass formal dependencies (dependencies that that are part of the design) and I have come to the conclusion that a) it is a big pain, b) it adds more complexity than the design calls for. When debugging dependencies are treated with the same dignity that design dependencies are treated, they start to appear as if they are part of the design, while they are not.

For example, say you have a collection which is sortable and you want to pass it a comparator. Is it really worth the hassle to make the comparator an object so that you can inject the debugging dependency in it? And isn't it kind of odd now that the comparator has become an entity of its own, as if it is part of the design, while in fact the only reason it is an entity is so as to have a reference to the debugging facility?

So, if it is only for debugging, (which, incidentally, means that it will not require testing,) then go ahead and use a singleton, it is fine.

Title: Static console object or dependency injection?

Body:
For a current project I have created a Console class which wraps up C++'s usual cout, writes output to a file or uses Console::WriteLine depending on the environment. Currently I've setup my code base to inject a console object into each class that I use, making all of them extend a base class: Debuggable. This seemed like a great plan at first but now that I have to pass the console to every object and ensure that it is created before all of them I'm having second thoughts.

Usually consoles seem to be handled with static objects, so I'm considering changing my implementation to use a static instance of the console that all the objects can use but I feel that this removes an element of control, I can't have more than one potential console with different formats and targets.

I understand that there's a lot of discussion about dependency injection, I'm interested specifically in the case of utilities such as a console.


问:
Formal justification for use of third-party libraries
My team and I develop and application which uses a number of third-party libraries to fulfill certain common functions. (It's a Java application and uses a number of Apache Commons libs, Log4j, etc.)

I have been asked to justify the use of third-party libs as opposed to coding everything in-house. I have explained that it is standard practice in software development, that it reduces the need to write and test our own code, and that the libs' long history and "many eyeballs" mean that library code is likely to be more reliable than our own.

My explanation is all well and good (IMHO!) but is there a more formal explanation of why using third-party libs is generally good practice — in a book, or a web page by a respected developer, for example?

(Edit: Unlike the question marked as duplicate, I'm not after a bunch of opinions. I'm specifically after a well-respected source I can cite to back up the prevailing opinion. However, I've just been pointed at the FAQ which explains that asking for off-site resources isn't allowed, so apologies for posting this question.)

答:
This is a very broad question which can only receive a broad answer about software reusability.

It all started back in 1968, with Douglas McIlroy's (personal website, and wikipedia) address at a NATO conference on software engineering, the content of which can be found today in a book called "Software Engineering, Report on a conference sponsored by the NATO Science Committee, Garmisch, Germany, 7th to 11th October 1968", Scientific Affairs Division, NATO, Brussels, 1969.

The text of interest has been scanned and can be found on the professor's site, under the title "Mass Produced Software Components".

Of course, a lot more has been written on the subject since then, for example a quick search yields documents on software reusability by Microsoft Research and other notable sources, but all these documents reference McIlroy's first paper, so you can search for its title to find documents that reference it.


问:
API key - in content or header
Working on an API at the moment and just wanted to gather opinions on where the best place to transmit the API key should be. I know that is shouldn't go in the URL, this leaves the request header or the message body.

If I put it in the header I can come up with a generic method for pulling it out that can be used across all services, however the spec I've been handed wants it in the body (ie in a JSON string included as part of the serialized object in the POST body).

答:
In HTTP, there is a Authorization header for that.

While it is usually used to provide users' credentials, in a case of an API, it can contain the ID of the client and the corresponding API key.

There are several benefits:

Support from different frameworks. Many frameworks will expect Authorization header in order to do authentication. Not using it will force to write additional code to feed those frameworks with custom values.

Support from different tools. For instance CURL.

Less “WTF where do I find/put this API key?!” from new developers joining the team (or developers designing new clients for your API).

You can then use HTTP status code definitions such as 401 Unauthorized, for which:

The response MUST include a WWW-Authenticate header field [...] The client MAY repeat the request with a suitable Authorization header field.

Moving it to the body of the request can become quickly painful. Most frameworks and tools don't make it very straightforward to add a body to a request, which may make your API more difficult than it needs to be.

Title: API key - in content or header


答: I would like to add that hosting a local copy is a best practice because none of above state anything related to a secure posture whereby Geo Location and strict White Listing are imperative.  Not hosting that file locally presumes to push a reduced security posture onto your clients.</p>

Title: Referencing external javascript vs. hosting my own copy

Body:
Say I have a web app that uses jQuery.  Is it better practice to host the necessary javascript files on my own servers along with my website files, or to reference them on jQuery's CDN (example: http://code.jquery.com/jquery-1.7.1.min.js)?

I can see pros for both sides:

If it's on my servers, that's one less external dependency; if jQuery went down or changed their hosting structure or something like that, then my app breaks.  But I feel like that won't happen often; there must be lots of small-time sites doing this, and the jQuery team will want to avoid breaking them.

If it's on my servers, that's one less external reference that someone could call a security issue

If it's referenced externally, then I don't have to worry about the bandwidth to serve the files (though I know it's not that much).

If it's referenced externally and I'm deploying this web site to lots of servers that need to have their own copies of all the files, then it's one less file I have to remember to copy/update.


问:
How to determine what should get its own respective controller?
I'm using the MVC pattern in my web application built with PHP.

I'm always struggling to determine whether I need a new dedicated controller for a set of actions or if I should place them inside an already existing controller.

Are there any good rules of thumb to follow when creating controllers?

For example I can have:

AuthenticationController with actions:

index() to display login form.

submit() to handle form submission.

logout(), self-explanatory.

OR

LoginController with actions:

index() to display login form.

submit() to handle form submission.

LogoutController with action:

index() to handle logging out.

OR

AccountController with actions:

loginGet() to display login form.

loginPost() to handle login form submission.

logoutGet() to handle logging out.

registerGet() to display registration form.

registerPost() to handle form submission.

And any other actions that are are involved with an account.

答:
Here are a few rules of thumb:

Organise by subject or topic, with the controller name being the topic's name.

Remember that the controller's name will appear in the URL, visible to your users, so preferably it should make sense to them.

In the situation you mention (authentication) the MVC team has already written the controller for you. Open Visual Studio 2013 and then click

```<code>File / New / Project...
Search installed templates for "ASP.NET MVC4 Web Application"
Choose "Internet Application" / OK.
</code>```

AccountController.cs contains all methods for managing user accounts:

```<code>Login()
Logoff()
Register()
Disassociate()
Manage()
ExternalLogin()
</code>```

So they have organised by topic "User accounts and authentication", with visible topic name "Account".

Body:
Here are a few rules of thumb:

Organise by subject or topic, with the controller name being the topic's name.

Remember that the controller's name will appear in the URL, visible to your users, so preferably it should make sense to them.

In the situation you mention (authentication) the MVC team has already written the controller for you. Open Visual Studio 2013 and then click

File / New / Project...
Search installed templates for "ASP.NET MVC4 Web Application"
Choose "Internet Application" / OK.

AccountController.cs contains all methods for managing user accounts:

Login()
Logoff()
Register()
Disassociate()
Manage()
ExternalLogin()

So they have organised by topic "User accounts and authentication", with visible topic name "Account".


问:
Calculate Big-O for nested for loops
I found this nested loop to calculate the Big-O notation.

for(i=0;i<n;i++)
  for(j=0;j<i*i;j++)
    for(k=0;k<j;k++)
```

<p>I got the time complexity for the algorithm with this polynomial equation. Suppose C1, C2 and C3 are time constants for each loop. Please note inner loop goes to i*i.</p>

```T(n) = C1(n) + C2(n/2)(n+1) + C3(n)(n^2)(n^2+1)/2
```

According to this, it has the time complexity of O(n^5) Am I right on the equation?

答:
In this specific case, you can replace the variables with their minimum and maximum values to find the number of steps for each loop.

The first loop goes from 0 to n, the second loop goes from 0 to n*n and the inner loop goes from 0 to n*n. So there are n2 iterations of the innermost loop, times n2 iterations of the second loop, times n iterations of the outer loop. Thus your running time is O(n * n2 * n2) = O(n5).

Note that it might not always be so simple to calculate the running time. Functions that are called within the loops, recursion, loops ending early, etc. will all add to the complexity of the calculation.

Title: Calculate Big-O for nested for loops


问:
How much refactoring is acceptable?
I am currently in a project where one of my developer colleagues constantly refactors stuff on every ticket he's doing. We are using agile methodologies. I know that refactoring is a good thing to do while solving some issues, keeps the codebase nice and clean, but my question is, what's the limit, how many files should one be touching at max? Can too much refactoring bite us on the long term?

Sometimes it feels like he could be introducing bugs (although the system is heavily tested) and that it makes the review process quite cumbersome; reviewing changes in 60-70 files when the original change should have affected only about 10-20.

On the project the tickets we are getting are quite small, usually no more than 10-20 files need to be touched, and this developer is averaging 50 or so. It feels wrong, and I haven't found a way to convince him that it's not. He says everything is tested, so all changes only improve the codebase. Finally, I am assuming that this refactoring could also be slowing him down, cause he just changes so many damn stuff all the time ! :D

Any thoughts ?

My personal view is that refactoring should be done, but it should usually be limited to the classes that are changing for the ticket anyway, and should a need for a bigger refactoring occur, it should be a ticket itself. In some cases, I find myself not even changing small stuff, cause "I've refactored enough for this ticket as it is.", it feels like when I reach the refactoring limit I've got set in my mind, I just stop making any non-necessary changes to the codebase and only focus on wrapping up the ticket..

Edit: I've come to realize from reading the responses and similar questions on programmers stackexchange (that I just discovered, what a lovely place !) that my main problem is that what I described is a single commit. I need to tell everyone that that are free to introduce refactoring but make sure they keep it in separate commits to ease the reviewing process.

Edit: Another aspect that I have found to be problematic is merge conflicts. These refactorings end up costing time to other members working on same pieces of code every now and then. Nothing substantial, but if everyone on the team made so much refactoring we would surely have many more merge conflicts. Not saying that this is the end of the world, just putting it on the table.

答:
how many files should one be touching at max?

Theoretically speaking you can go on refactoring indefinitely because there is no perfect codebase.

One way to get around this that has worked out for me and my team is to identify these areas that need cleaning, make tickets out of them (call it technical debt tickets or anything else along those lines) then during your sprint planning attach these tech debt tickets to your main ticket.

This way you are scoping your work and not doing any additional refactoring that might cause trouble to other developers (since you are not stepping on their toes).

In the above approach it is obvious that you will not be capturing every single, little area of code for refactoring as tech debt, so for those little changes you can all include them under the ticket that you are working on. That should be fine.

However, small changes shouldn't add 20+ files over what you have expected, and if you do see that happening then that means 2 things:

1) The person is doing WAY too many random things unrelated to the ticket.

2) The person is doing a big refactor which was not captured previously.

Either way you can definitely bring these two scenarios up for discussion.

For the first case you can say the following:

Making quite a few amount of changes unrelated to the ticket is more distracting than helpful in terms of leaving your codebase cleaner than you have found it.

This mantra is about the code you are working with currently so if you are working with class A and it is related to class B which is a bit messy, then refactoring it would make sense.

But if you are working with class A and you are refactoring class Z which is totally unrelated then not only are you creating more need for testing, but you are also distracting and slowing down the overall development process (slowing down dev testing, unnecessary context switching, more testing resources, introducing more entropy to the workflow).

For the second case you can say the following:

Working on a large amount of tech debt which was not captured previously is a betrayal of the process and of the team since it was not agreed upon by all and wasn't prioritized by the business analysts as something to spend time/resources on.

For the next time when one finds a large chunk of technical debt one should capture it and add it to the backlog for later prioritization instead of tackling it with no planning and direction in mind.

OwnerDisplayName: sakis kaliakoudas

Title: How much refactoring is acceptable?


答:
To me this sounds like you and your team mate aren't on the same page when it comes to the level of quality required of the project.

I recently had the same problem with a team. What worked for me was determining the ideal design we all agreed on for every part of the project. The repository would use CQS, the MVC controllers would be very thin and primarily use the services layer etc.

Once every team member agrees on the design of the project, formalize it by, for example, some UML diagrams. Print them so you have them available in the team room during code reviews. When the design is clear, it's easier agree on when good is good enough and more refactoring isn't required.

Also, I would recommend only refactoring parts of the code relevant to the feature/story you are currently working on. That way, the refactoring time is small compared to the entire feature and you can 'sell' the refactoring time more easily to project management.

Title: How much refactoring is acceptable?

Body:
I am currently in a project where one of my developer colleagues constantly refactors stuff on every ticket he's doing. We are using agile methodologies. I know that refactoring is a good thing to do while solving some issues, keeps the codebase nice and clean, but my question is, what's the limit, how many files should one be touching at max? Can too much refactoring bite us on the long term?

Sometimes it feels like he could be introducing bugs (although the system is heavily tested) and that it makes the review process quite cumbersome; reviewing changes in 60-70 files when the original change should have affected only about 10-20.

On the project the tickets we are getting are quite small, usually no more than 10-20 files need to be touched, and this developer is averaging 50 or so. It feels wrong, and I haven't found a way to convince him that it's not. He says everything is tested, so all changes only improve the codebase. Finally, I am assuming that this refactoring could also be slowing him down, cause he just changes so many damn stuff all the time ! :D

Any thoughts ?

My personal view is that refactoring should be done, but it should usually be limited to the classes that are changing for the ticket anyway, and should a need for a bigger refactoring occur, it should be a ticket itself. In some cases, I find myself not even changing small stuff, cause "I've refactored enough for this ticket as it is.", it feels like when I reach the refactoring limit I've got set in my mind, I just stop making any non-necessary changes to the codebase and only focus on wrapping up the ticket..

Edit: I've come to realize from reading the responses and similar questions on programmers stackexchange (that I just discovered, what a lovely place !) that my main problem is that what I described is a single commit. I need to tell everyone that that are free to introduce refactoring but make sure they keep it in separate commits to ease the reviewing process.

Edit: Another aspect that I have found to be problematic is merge conflicts. These refactorings end up costing time to other members working on same pieces of code every now and then. Nothing substantial, but if everyone on the team made so much refactoring we would surely have many more merge conflicts. Not saying that this is the end of the world, just putting it on the table.


答:
Agree up front how much refactoring is to occur on each ticket.  This is done as a team.  If that developer wants to do extra stuff, bring it up and decide whether it is OK.  Keep things scoped properly.  There's nothing worse trying to explain to a boss why the team broke something that wasn't in scope.

Also, verify refactoring is actually improving the code base.  Your team should have done some code metrics on your system identifying the hotspots.  Some developers just like to re-write everything, make sure the efforts are actually improving code base.  Sometimes its just not worth the effort or the work being done isn't actually improving anything.  Again, measuring before and after will help.

Praise the members of the team doing the extra work.  It's good that they take pride in improvements.  Try to show them that we want to capture all the good work they are doing and not create any surprises.  They may resist on defining scope, but one definately doesn't want a bunch of loose cannons in the code base because at some point it may come back to bite you.

Title: How much refactoring is acceptable?


答:
Answer is not that obvious

Please let me clarify a few things before i will make any answering statements. First of all:

What is the controller?

Controller is a part of system that controls request - after dispatching. Thus, we can define it as some set of actions related to... what?

What is the scope of controller?

And thats more or less part when we will have any answer. What do you think? Is it a controller of things (for example an Account) or controller of actions? Of course its a controller of some model or some more abstract thing that provides actions on it.

The answer is...

AuthenticationController with actions:

index() to display login form.

submit() to handle form submission.

logout(), self-explanatory.

Nah, authentication is a process. Don't go that way.

LoginController with actions:

index() to display login form.

submit() to handle form submission.

Same here. Login - action. Better don't create action controller (you don't have correlated model to it).

AccountController with actions:

loginGet() to display login form.

loginPost() to handle login form submission.

logoutGet() to handle logging out.

registerGet() to display registration form.

registerPost() to handle form submission.

Quite good, but i am not convinced that building that low-level controller (controller is abstraction itself) is worth bringing. Anyway, creating methods with *Get or *Post are unclear.

Any suggestion?

Yes, consider it:

AccountController:

login(AccountModel)

logout(AccountModel)

register(AccountModel)

index()

And related model to it, ofc Account class. It will give you an opportunity to move your model-controller pair somewhere else (if it will be neccessary) and make a clear code (it's obvious what the login() method mean). Stincking to model is really famous especially with CRUD applications and maybe it is a way for you.

Title: How to determine what should get its own respective controller?

Body:
I'm using the MVC pattern in my web application built with PHP.

I'm always struggling to determine whether I need a new dedicated controller for a set of actions or if I should place them inside an already existing controller.

Are there any good rules of thumb to follow when creating controllers?

For example I can have:

AuthenticationController with actions:

index() to display login form.

submit() to handle form submission.

logout(), self-explanatory.

OR

LoginController with actions:

index() to display login form.

submit() to handle form submission.

LogoutController with action:

index() to handle logging out.

OR

AccountController with actions:

loginGet() to display login form.

loginPost() to handle login form submission.

logoutGet() to handle logging out.

registerGet() to display registration form.

registerPost() to handle form submission.

And any other actions that are are involved with an account.


答:
I wouldn't focus on the quantity, but rather on substance. The number of affected files during a group of refactoring operations is as irrelevant as the LOC you write per day. An extreme example is the renaming of methods to follow a convention. It may affect thousands of files, but is barely more important than a refactoring focused on two files which radically change their design.

By focusing on what are the group of refactoring operations improving rather than how much files or LOC are affected, you also reduce the complexity of the problem you are currently encountering. During the code review, look at the overall impact of those operations. Do they improve the code base? How much?

Consider refactoring operations individually. This will help your team determining precisely what is considered useful, and what should be avoided. For instance, imagine that during a code review, you notice that your colleague made the following refactoring operations:

Split methods which were doing too much,

Introduced abstract factory pattern,

Replaced a few ifs by inheritance, simplifying the logic,

Replaced a few inheritance occurrences by ifs, reducing the number of classes and LOC and making the code easier to read,

Rewrote the method findSparse to be more readable,

Renamed a few methods to show that those are actually getters and setters,

Replaced a singleton and introduced Dependency Injection: the code is now much easier to test.

Rather than telling that six changes affected 28 files and should be ignored, since they are above the threshold of 25 files, your team may rather consider that:

Refactoring operations 1 and 7 are totally worth it.

Operations 2, 3 and 4 are interesting, but cost much time. They shouldn't be done if the project is under time pressure, but should be otherwise.

Operation 6 is cosmetic and has a risk of introducing bugs on the part of the project which uses Reflection (explaining the risks which outweigh the benefits is essential). This operation should be postponed until all the team is ready to undertake the change.

Operation 5 is not improving anything: the author of the refactoring just rewrote the code to match his own style. Most team members agree that this doesn't make code more readable, and some claim that they actually find the original version easier to understand. Similar operations should be avoided in the future.

By focusing on individual operations, you make it very easy for your coworker to understand the team's point of view, what is welcome, and what is not. By focusing on quantity, you make it more “I don't like your way of working” nonconstructive criticism.

Note that:

If commits are granular enough (and they should be; for the refactoring listed above, I will expect at least seven commits, and the eighth one implementing the feature itself; ideally, point 3 and point 4 should also be subject to multiple commits, leading to more than ten commits overall), rolling back a commit shouldn't cause too much trouble.

If commits are sparse and monolithic (that is, one or two commits for the refactoring operations listed above), there might be a more serious problem in your team. Try to explain them that one commit should correspond to one change, as small as it could be while remaining independent of other changes.

Title: How much refactoring is acceptable?


问:
What to test for in a simple form where the value of one input field dictates other fields?
Note:- I have added android and iOS tags to this question but it is not necessarily restricted to those platforms.

Consider a simple registration form where the the value of one field dictates what other fields are shown and how they are shown. For example, imagine the following

You start off by selecting your country from a drop-down/list

If the native language of that country is not English, you display a text field to enter the language.

Question: What strategy would one adopt to test such a form?

To elaborate a bit, of late there has been a push from both the Android and iOS developer communities to move away from MVC (well, on Android that has never existed really) towards other architectures like MVVM or MVP. One major reason cited for this is that sticking to traditional architectures conflates responsibilities of what ought to be several distinct layers. Separating them into derivatives of MVC makes testing easier.

Secondly, both MVVM and MVP have the advantage of isolating the View layer to such an extent that everything right up to view logic can be tested without ever having to touch a real view object. On Android, this means being able to run pure JVM Junit tests to test the view logic.

I suppose my example above falls under the category of view logic. However, it is not clear to me how I can test this without actually instantiating a real View object. Conceptually, I want to verify that if user chooses a country that speaks English natively, then the text field to enter a language is not shown. Otherwise, the text field is shown. How does this translate to non-UI tests?

答:
What strategy would one adopt to test such a form?

You have to separate the GUI from the decision logic by adding a decision function that only depends on business attributes and not on GUI elements:

```<code>bool isNativeLanguageInputVisible(RegistrationData currentRegistrationData)
</code>```

Your GUI would use this decision function to control visibility and your test goes against decision function and not against the GUI.

Body:
What strategy would one adopt to test such a form?

You have to separate the GUI from the decision logic by adding a decision function that only depends on business attributes and not on GUI elements:

bool isNativeLanguageInputVisible(RegistrationData currentRegistrationData)

Your GUI would use this decision function to control visibility and your test goes against decision function and not against the GUI.


答:
Terminology

I believe it is a big misconception to call a class containing some HTTP-related methods a "controller".

Controller is a method that handles request, but not a class containing such methods. So, index(), submit(), logout() are controllers.

Class containing that kind of methods is named "controller" just because it constitutes a group of controllers, and is playing a role of "bottom-level" namespace. In FP language (like Haskell) it would be just a module. It is good practice to keep those "controller" classes as stateless as possible in OOP languages, except references to services and other program-wide stuff.

The answer

With terminology sorted out, the question is "how should we separate controllers into namespaces/modules?" I think the answer is: controllers inside a single namespace/module should deal with the same kind of data. For example, UserController deals primarily with instances of User class, but occasionally touches other related things, if required.

Since login, logout and other such actions are mostly dealing with the session, it probably best to put them inside SessionController, and index controller, which just prints a form, should be placed into LoginPageController, since it obviously deals with login page. It makes a little sense to put HTML rendering and session management into a single class, and that would violate SRP and probably a bunch of other good practices.

General principle

When you're having trouble deciding where to put a piece of code, start with data (and types) you deal with.


问:
Why is it common to put an underscore before a method in JavaScript?
For example, I noticed that in the jQuery UI widget factory, methods like _init, _start, _on, ect.

答: The most common use for a leading underscore in my experience is to identify an object member (field/function) that is not supposed to be used by regular users. This means the member is regarded as "private". Because JavaScript doesn't enforce visibility modifiers (everything's considered "public"), it's common to use coding conventions like this to indicate visibility. As a commenter stated, members with a leading underscore are considered more specifically to have "internal" scope. They can be freely accessed within the library, or by those writing extensions to it, but should not be accessed by users of the library.</p>


问:
Is it always a good idea to divide large classes into smaller ones?
I've heard time and time again that in object-oriented programming, you should try to split objects that 'do too much' into multiple classes, to avoid the "God Object" problem.

This seems like fine advice for a project that has plenty of room to expand, but in our project, our packages are already loaded down with too many objects - some that are very bare-bones - while we also have the problem of very large objects that do too much.

Is it a better idea, for code sanitation, to split our larger objects that do too much work into smaller objects?  Or is there a limit to the amount of good it can do?

答:
I assume you're on a legacy project where you weren't the one who developed the code. I am in a similar situation.

In my opinion, don't touch the code unless:

You have been tasked with the refactor by a superior.

You are in fact a senior guy who knows the code inside and out.

Otherwise I would have to say I would apply the "if it isn't broke, don't fix it" law. While it is quite possible that you may achieve better modulation and encapsulation by breaking up huge classes, it could also introduce tons of problems that are not there currently.


答:
It seems to me that the fundamental principle to apply here would be the Single Responsibility Principle.  Does each class have a single, clearly articulated, well-bounded responsibility?

Note that I don't mean "does each class do one thing."  For example, a repository "Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects."  But it still might have several methods that accomplish parts of this overall responsibility.

If you find that a clearly-articulated, well-bounded responsibility that should be contained in a single class with multiple methods is instead being split over many smaller classes, then your classes are getting too small.

Title: Is it always a good idea to divide large classes into smaller ones?

Body:
I've heard time and time again that in object-oriented programming, you should try to split objects that 'do too much' into multiple classes, to avoid the "God Object" problem.

This seems like fine advice for a project that has plenty of room to expand, but in our project, our packages are already loaded down with too many objects - some that are very bare-bones - while we also have the problem of very large objects that do too much.

Is it a better idea, for code sanitation, to split our larger objects that do too much work into smaller objects?  Or is there a limit to the amount of good it can do?


答:
Is it a better idea, for code sanitation, to split our larger objects that do too much work into smaller objects?

It is not about the length of the class but about the responsibility.

You could potentially have a class that is a bit too long but is taking care of only one responsibility. So, definitely don't go by length.

Instead, try to understand the problem it is trying to solve.

If it is solving a single problem then it is following the single responsibility principle and you could either leave it the way it is or DI some of its private methods as helpers classes.

If you notice that it is taking care of more than one responsibility then no matter how long the class I would suggest to break it down into two or however many responsibilities it takes to have them all take care of singular concerns.


问:
JSON Web Token - why is the payload public?
I can't understand the reasoning for making the claims/payload of a JWT publicly visible after base64 decoding it.

Why?

It seems like it'd be much more useful to have it encrypted with the secret.

Can someone explain why, or in what situation, keeping this data public is useful?

答:
You choose not to encrypt the payload for the same reasons that you choose not to encrypt anything else: the cost (however small it is) exceeds the benefit, and a lot of data simply doesn't need to be secured that way.

What you mostly need protection against is people tampering with the data so that the wrong record gets updated, or someone's checking account gets money in it that it's not supposed to have.  The JSON Web Token's signature accomplishes that, because changing any part of the header/payload/signature combination invalidates the packet.

Note that you can still secure the packets at the Transport Layer by using SSL.