问:
Is big-O really that relevant when working in industry?
In every interview I have been in, I have been quizzed on mathematical analysis of complexity, including big-O notation.

How relevant is big-O analysis to development in industry? How often do you really use it, and how necessary is it to have a honed mindset for the problem?

答:
The reason for this is because it indicates scalability.

A process that is O(n^2) will scale worse than one that is O(n log n), but better than one in O(n^3) or even O(n!).

If you do not know the differences and when they apply, you are less suited for choosing the right implementations of functionality, as well as extrapolating test performance into production performance.

EDIT:  A comparison of 48n with n^3 from http://www.codinghorror.com/blog/2007/09/everything-is-fast-for-small-n.html (which in turn is from Programming Pearls)


问:
Clean, Modular Code vs MV* Frameworks
I've been hearing a lot about the "new" MV* frameworks. I've tinkered with KnockoutJS (I created an invoicing application), but I much prefer to write clean, modular code in raw JavaScript - leveraging utility APIs and other libraries when necessary.

Given a methodical/structured/SOLID approach to writing a JavaScript application, where OOP, SOC, SRP and other design principles are adhered to, wouldn't the usage of MV* frameworks be superfluous?

Are there any articles that express/address these concerns?

I've found one in the past

note - I've migrated this question from SO to this site, as its more appropriate for this audience.

答:
The thing is - if you write clean and modular code in a complex applications (I mean application with lots of UI functionality, since the question was particulary about JS and MV* frameworks), you will realize, eventually, that you are doing an application in MV* style. It could have another implementation and code look, but it will be MV*-application. I couldn't bet here, but I am 95% sure it will be that.

MV*-architecture is not a kind of fashion, or killer-feature, or something that could be thrown out. It is a pragmatical way to organize rich UI-applications to tackle complexity of the modern programs.

ContentLicense: CC BY-SA 3.0

Title: Clean, Modular Code vs MV* Frameworks


问:
Big switching from one platform to another
As an example I want to switch from C#/.NET to Scala/Jvm. I'm working as a self-employed and I'm free to choose my favorite language/platform. Having more than 8 years of experience in C#/.NET leads me to have lots of reusable codes, libraries and framework. I can work on my projects and ideas without thinking about language so I'm focused on what I'm doing.

Why should I do such migration? Because;

Scala is open-source and innovative

Scala runs on JVM which is cross-platform that decreases costs and some risks

Scala has all C# feature (with something more)

Benefit of Java comminuty

More open-source libraries in Java platform

Doing open-source in .NET is a little harder and doesn't get attention as it does in Java or other plaforms.

Is it OK to manage such a big risk and learn a new language/platform (in this case, Scala, Play framework, etc.) and use it in at least a small commercial project to find out if it's suitable?

答:
I wouldn't use an environment that's totally new to me in a commercial situation, as you don't know the pitfalls of the language and frameworks. This will cause your estimates to be grossly incorrect, as you need more time to find solutions to problems that are new to you.

If your customer is fine with that, go ahead. Otherwise I'd try to convert an existing .NET application to Scala in my own time.


答:
Not many customers will be happy for you to be learning at their expense. They may have given you free reign to pick, but be assuming that whatever you pick, you are an expert in.

I am self employed as well, and frankly, the only consideration for me is whether I will be able to find new contracts using my skillset.

Dropping my bread and butter stack to learn a new one makes sense if the old one is becoming obsolete and there is less and less work available doing it. And even then, I may have to pitch myself at a lower level to get work in the new stack.

That being said, older stacks are more niche and come with higher rewards, but you need to find the balance between there suddenly being no work, and your skills being out of date.

Title: Big switching from one platform to another

Body:
As an example I want to switch from C#/.NET to Scala/Jvm. I'm working as a self-employed and I'm free to choose my favorite language/platform. Having more than 8 years of experience in C#/.NET leads me to have lots of reusable codes, libraries and framework. I can work on my projects and ideas without thinking about language so I'm focused on what I'm doing.

Why should I do such migration? Because;

Scala is open-source and innovative

Scala runs on JVM which is cross-platform that decreases costs and some risks

Scala has all C# feature (with something more)

Benefit of Java comminuty

More open-source libraries in Java platform

Doing open-source in .NET is a little harder and doesn't get attention as it does in Java or other plaforms.

Is it OK to manage such a big risk and learn a new language/platform (in this case, Scala, Play framework, etc.) and use it in at least a small commercial project to find out if it's suitable?


答:
My question is, how relevant is this test to development in industry?

A solid understanding of computational complexity theory (e.g. big O notation) is essential to design scalable algorithms, applications and systems.  Since scalability is highly relevant to computing in industry, big O notation is too.

How often do you reeeally use it, and how necessary is it to have a honed mindset for the problem?

Depends what you mean by "reeeally use it".  On the one hand, I never do formal proofs of computational complexity for the software I write.  On the other hand, most days I have to deal with applications where scalability is a potential concern, and design decisions include selection of (for example) appropriate collection types based on their complexity characteristics.

(I don't know whether it is possible to consistently implement scalable systems without a solid understanding of complexity theory.  I would be inclined to think that it is not.)

Title: Is big-O really that relevant when working in industry?

Body:
In every interview I have been in, I have been quizzed on mathematical analysis of complexity, including big-O notation.

How relevant is big-O analysis to development in industry? How often do you really use it, and how necessary is it to have a honed mindset for the problem?

ContentLicense: CC BY-SA 2.5


问:
Why not a standard rendering engine to solve cross browser problems
Why do browsers use different rendering engines, this causes the problem I hate the most "make your HTML/CSS compatible with all major web browsers".

Why don't they use one rendering engine  as a standard and this will save a lot of time and effort for all developpers. In fact this is what I hate about IT industry "Concurrence at the expense of the user". We can say the same about Operating systems.

Why not only one ?

答:
It's exactly like if you were asking why are there multiple browsers: wouldn't it be easier to have just one, globally adopted browser?

Different companies build different browsers because they believe their browser is either the best one or provides features other browsers don't have.

Different browsers sometimes need different rendering engines in order to:

Provide additional features other rendering engines don't have, or:

Avoid features the browser don't need. This is the reason why Blink, the new rendering engine for Chrome, was created.

Moreover, an unique, globally adopted rendering engine used by every browser, anywhere, means that the engine cannot be updated: once you update the engine, it will mean that some people will use the updated browser with the new engine, while others will not update anything, and so will keep using the old one.


答:
At the risk of teaching grandma to suck eggs, you'll of course have to learn this in your own time. Unless you have some very understanding customers, they're unlikely to give you the time (or money) to develop new skills at your own pace for your own professional gain.

As a former contractor/freelancer myself, there is a definite benefit of coding in a language where expertise is freely available. My freelancing price structure was $X for development and doubled if they wanted the source.

I was brought in on one C# freelance project specifically because the previous incumbent was writing their software in an arcane language (knowing that expertise wasn't readily available) and fleecing the client for the simplest updates.


答:
In layman's words:

Standards already exist. WC3 specifications are standard enough.

Standards don't mean there would be only one implementation.

Each implementation can have different bugs and particularities, and each one is more or less successful in implementing the standard.

You cannot have a single implementation that runs in all operating systems.

How would you prevent anyone from writing his/her own rendering engine, but by force ?

Browsers strive for getting faster with every version, that's good for the user.

Many browsers share the same rendering engine, for example Webkit is used by Chrome and Safari.

A world dictatorship prohibiting anyone from creating its own rendering engine would stifle innovation.

Regarding your comment on why not have just one operating system: that would be a bleak world.

Title: Why not a standard rendering engine to solve cross browser problems

Body:
Why do browsers use different rendering engines, this causes the problem I hate the most "make your HTML/CSS compatible with all major web browsers".

Why don't they use one rendering engine  as a standard and this will save a lot of time and effort for all developpers. In fact this is what I hate about IT industry "Concurrence at the expense of the user". We can say the same about Operating systems.

Why not only one ?


问:
Will high reputation in Stack Overflow help to get a good job?
In a post, Joel Spolsky mentioned that 5 digit Stack Overflow reputation can help you to earn a job paying $100k+. How much of that is real?

Would anyone like to share their success in getting a high paid job by virtue of their reputations on Stack Exchange sites?

I read somewhere that, a person got an interview offer from Google because a recruiter found his Stack Overflow reputation to be impressive. Anyone else with similar stories?

答:
This reminds me of Drake's equation in astronomy. It is an equation that is suppose to give a statistical hint of the number of civilizations in the universe. It is a waste of time actually because it assumes that involved parameters are independent while they are clearly not.

I have four children and a good job. Maybe that is the key to the good job?


问:
How do I handle 3rd party search result data (via cache)
I have a search function on my site and it is taking data from 6 different 3rd party resources. The problem is, it takes too long requesting the data over and over again on the results page.

I've read for questions like this on SO about session not being a good choice but for me 'memcache' is not an option, because the server doesn't have memcached installed and I have no way to install it now.

Is there any other approach to do this? Storing in the database seem inappropriate because the data depends on the search terms requested.

What I've been thinking is writing a file on the server that would act as a cache for this file but I don't know how I would know when to delete it after.

答:
There are two methods that could be used in caching here (assuming using the file system only, as you've mentioned Memcache is not available):

Method 1: Cache life is known

If you know how long the cache file should last for, then you could probably just wrap the fetching of cache information in a call to filemtime before fetching. Example:

$filepath = './cache/' . md5($params); // path to cache file
$cachelength = 3600; // 1 hour
if (is_file($filepath) && time() - filemtime($filepath) < $cachelength) {
    $response = unserialize(file_get_contents($filepath));
} else {
    $response = fetch_data();
    file_put_content($filepath, serialize($response));
}
```

<p><strong>Method 2: Cache life not known</strong></p>

<p>If you don't know how long the cache should last for, then your other alternative would be to have a cronjob (or scheduled task on Windows) which removes all the cache files every few minutes, so that your cache is continually being cleaned. Example:</p>

```*/5 * * * * /bin/rm -f /path/to/cache/*
```

In addition to the caching, there is another way that you could possibly speed up the initial requests (assuming all requests being made can be asynchronous):

Bonus tip: "Speed up" initial requests using curl_multiexec()

Something you might want to look at using is the curl_multiexec_* functions in order to process all the initial requests in parallel. I have a wrapper for this functionality on github

Body:
There are two methods that could be used in caching here (assuming using the file system only, as you've mentioned Memcache is not available):

Method 1: Cache life is known

If you know how long the cache file should last for, then you could probably just wrap the fetching of cache information in a call to filemtime before fetching. Example:

$filepath = './cache/' . md5($params); // path to cache file
$cachelength = 3600; // 1 hour
if (is_file($filepath) && time() - filemtime($filepath) < $cachelength) {
    $response = unserialize(file_get_contents($filepath));
} else {
    $response = fetch_data();
    file_put_content($filepath, serialize($response));
}

Method 2: Cache life not known

If you don't know how long the cache should last for, then your other alternative would be to have a cronjob (or scheduled task on Windows) which removes all the cache files every few minutes, so that your cache is continually being cleaned. Example:

*/5 * * * * /bin/rm -f /path/to/cache/*

In addition to the caching, there is another way that you could possibly speed up the initial requests (assuming all requests being made can be asynchronous):

Bonus tip: "Speed up" initial requests using curl_multiexec()

Something you might want to look at using is the curl_multiexec_* functions in order to process all the initial requests in parallel. I have a wrapper for this functionality on github


问:
What do you call parentheses operators?
In most programming languages documentation where they talk about operators +-*/=<> they also include ()[] as operators.

There are unary operators, multiplicative operators, additive operators, bit shifting operators, etc. etc.

I can find no terminology that separates parentheses operators from the rest of them. Calling them just parentheses operators doesn't seem right, because they can be used in very different contexts.

Specify casts, or type conversions.

```<code> a = (int)x;
</code>```

Invoke methods.

```<code> fooMethod();
</code>```

Define order or operations.

```<code> x = (2+4)*8;
</code>```

In the above examples. What is the correct terminology for each type of parentheses. I require this for documentation purposes.

答:
Not all notations are operators.

Parentheses ("(" and ")") are operators when used in an expression like a*(b+c), in which case they're often referred to as grouping operators.  When used to set off the type in an expression like (int) x, they're a part of the cast notation ("(" + typename + ")"), not operators.  Similarly, when used in an expression like function(), they're part of the function call notation, not operators.

Brackets ("[" and "]") are typically used as part of the indexing notation, as in a[1].  In some older languages, parentheses are used instead of brackets, owing to the lack of brackets in the character sets the languages were originally defined with.

Title: What do you call parentheses operators?


答:
In short: They are typically called Operators and Punctuators in C family languages.

The definition of operation is defined as:

An operation is an action performed on one or more values either to modify the value held by one or both of the variables, or to produce a new value by combining existing values. Therefore, an operation is performed using at least one symbol and at least one value. The symbol used in an operation is called an operator. A value involved in an operation is called an operand.

Thus, there are 3 operators and one punctuator in most C family languages:

Unary operators

Binary operators

Ternary operators

Punctuators

Operators and Operands in C#

More about the examples and detailed explanation is posted here - Operators and Punctuators.

Title: What do you call parentheses operators?

Body:
In most programming languages documentation where they talk about operators +-*/=<> they also include ()[] as operators.

There are unary operators, multiplicative operators, additive operators, bit shifting operators, etc. etc.

I can find no terminology that separates parentheses operators from the rest of them. Calling them just parentheses operators doesn't seem right, because they can be used in very different contexts.

Specify casts, or type conversions.

```<code> a = (int)x;
</code>```

Invoke methods.

```<code> fooMethod();
</code>```

Define order or operations.

```<code> x = (2+4)*8;
</code>```

In the above examples. What is the correct terminology for each type of parentheses. I require this for documentation purposes.


问:
How to figure out design pattern for this particular solution?
While working on a project I've come up with some design solution. I am having a hard time relating it to any general design pattern or analyzing this situation in details. This is also prohibiting me to find any better design for this.

This is a simple analogy of my solution -
Both Kangaroo and Tiger can walk but only Kangaroo can jump and only Tiger can run.

```<code>Animal<TLeg> where TLegs: ILegs
{
    TLegs Legs;
    void Walk(){ Legs.Walk(); }
}

Kangaroo: Animal<IJumpingLegs>
{
    void Jump() { Legs.Jump(); }
}

Tiger: Animal<IRunningLegs>
{
    void Run() { Legs.Run(); }
}

ILegs
{
   void Walk();
}

IRunningLegs : ILegs
{
   void Run();
}

IJumpingLegs : Ilegs
{
   void Jump();
}
</code>```

[Edit]

Problem Description:

Here, Kangaroo and Tiger share common functions and a property Legs. Therefore, I have a base class for common functions. Base class needs to have access to this property Legs.

Functions in subclasses too rely on Legs and based on type of Legs, subclass will need to call different functions of this property.

Basically, two concrete animals need some common methods and their uncommon methods(Jump and Run) require different TYPE of a common property.

For this problem, I have come up with the solution described above. Hoping that I am able to describe my problem, I would like to know if there could be any alternate solution.

Does this problem/solution sound familiar? Is there anything that can be improved?

答:
This described problem reminds me the Adapter and Facade Patterns: Being Adaptive.

While reading your question, i also have remembered a famous funny old saying:

If it walks like a duck and quacks like a duck, then it must be a turkey wrapped with a duck adapter...

You may get detailed explanation from the following book - Head First Design Patterns

In addition, there are SOLID principles and Liskov Substitution Principle is one of them. It also addresses this issue with a different flavor.

If it looks like a duck, quacks like a duck, but needs batteries – you probably have the wrong abstraction


答:
As long as the customers are happy with solution, it does not matter which platform you are using or planning to switch to.

It is very important to choose tools and appropriate development platforms that will deliver the solution. One of the most important phase of the system requirement analysis is to choose the right/available and familiar tooling to tackle the project.

However, be aware that totally new development platform and tooling does require upfront time investment.


答:
I never actually applied formally the rule in my working life.

However you have to be familiar with that concept, and apply it in an intuitive way every time you design an algorithm.

The rule is:

You should be enough familiar with the
  O notation to being able to determine, for a given task,
  if it is required to formally calculate it,
  or it is just enough to evaluate it intuitively,
  or if you can just skip it entirely. Just like
  many other basic mathematical
  concepts.


答:
To me, it seems like case of bad abstraction. Base classes are for abstracting behavior that is same for all expected children. Which is wrong in your example. In your case you either want Move virtual method, and then override it in concrete animals. Or you want Jump and Run methods, but then there is nothing common between them, so abstracting it away doesn't make sense.

And there is one rule I like when doing this :

Abstractions should always be seen from point of who will use those abstractions. Not from the inside of the implementation.

If you are writing some abstraction and you haven't written code that will use this abstraction, then you are doing something wrong.

Title: How to figure out design pattern for this particular solution?

Body:
While working on a project I've come up with some design solution. I am having a hard time relating it to any general design pattern or analyzing this situation in details. This is also prohibiting me to find any better design for this.

This is a simple analogy of my solution -
Both Kangaroo and Tiger can walk but only Kangaroo can jump and only Tiger can run.

```<code>Animal<TLeg> where TLegs: ILegs
{
    TLegs Legs;
    void Walk(){ Legs.Walk(); }
}

Kangaroo: Animal<IJumpingLegs>
{
    void Jump() { Legs.Jump(); }
}

Tiger: Animal<IRunningLegs>
{
    void Run() { Legs.Run(); }
}

ILegs
{
   void Walk();
}

IRunningLegs : ILegs
{
   void Run();
}

IJumpingLegs : Ilegs
{
   void Jump();
}
</code>```

[Edit]

Problem Description:

Here, Kangaroo and Tiger share common functions and a property Legs. Therefore, I have a base class for common functions. Base class needs to have access to this property Legs.

Functions in subclasses too rely on Legs and based on type of Legs, subclass will need to call different functions of this property.

Basically, two concrete animals need some common methods and their uncommon methods(Jump and Run) require different TYPE of a common property.

For this problem, I have come up with the solution described above. Hoping that I am able to describe my problem, I would like to know if there could be any alternate solution.

Does this problem/solution sound familiar? Is there anything that can be improved?


问:
Good practice for object instantiation in MVC
In MVC the Domain Models(from Model Layer) should instantiate other Domain Models or all the Domain Models should be instantiate in the controllers and passed down using Dependency Injections?

How do you implement this in real applications? If you choose this path isn't the controller getting to fat?

答:
From what I can grasp of your questions is,  you should look into is using an Application Service Layer between your Controller and your Domain Model. Your controller would use Dependency Injection for the Application Service.

The service would then orchestrate your domain and contain no business logic. The service layer acts as a boundary between your controller and domain model. The orchestration aspect would include how your domain models get instantiated.

--MVC/UI layer

```<code>public UserController: Controller
{
    private readonly IUserService _userService;
    public UserController(IUserService userService)
    {
         _userService = userService;
    }

    public void SomeUserAction()
    {
        _userService.SomeUserAction();
    }

}
</code>```

-- Service Layer

```<code>public UserService : IUserService
{
    public void SomeUserAction()
    {
         //Orchestrate domain logic
    }
}
</code>```

Doing it this way prevents your controller getting fat. The controller only holds references to each Application Service that it requires.

Martin Fowler has a nice article on the Service Layer

Body:
From what I can grasp of your questions is,  you should look into is using an Application Service Layer between your Controller and your Domain Model. Your controller would use Dependency Injection for the Application Service.

The service would then orchestrate your domain and contain no business logic. The service layer acts as a boundary between your controller and domain model. The orchestration aspect would include how your domain models get instantiated.

--MVC/UI layer

public UserController: Controller
{
    private readonly IUserService _userService;
    public UserController(IUserService userService)
    {
         _userService = userService;
    }

    public void SomeUserAction()
    {
        _userService.SomeUserAction();
    }

}

-- Service Layer

public UserService : IUserService
{
    public void SomeUserAction()
    {
         //Orchestrate domain logic
    }
}

Doing it this way prevents your controller getting fat. The controller only holds references to each Application Service that it requires.

Martin Fowler has a nice article on the Service Layer


答:
There are a number of items that need to be addressed from your question.  I'm going to say MVC when what I really mean is "MVC and all of it's related variants."

I've been hearing a-lot about the "new" MV* frameworks.

As you should; there's a number of advantages (and disadvantages) to using an MVC framework or similar.

Also keep in mind that MVC has been around since the 70's and was first popularized with the use of SmallTalk.  See Martin Fowler's various essays on GUI architectures for additional information.

but I much prefer to write clean, modular code in raw JavaScript

So you should see the appeal of MVC then.  :-)

MVC was created to help enforce the exact thing you're proclaiming to want within your code.  UI's (Views) change.  Logic to drive the UI (Controller*) changes.  Data sources and access mechanisms (Model) change.  MVC was designed to encapsulate change and give the best odds for each component to be migrated to the next incarnation of the application.  By separating out the layers into individual components, the risk of change is minimized.

 * By Controller, I mean the modern use of the term not the original use from SmallTalk days.  And if that doesn't make sense, then ignore this sidenote.

Given a methodical/structured/SOLID approach to writing a JavaScript application, where OOP, SOC, SRP and other design principles are adhered to, wouldn't the usage of MV* frameworks be superfluous?

Perhaps it's superfluous, perhaps it isn't.  How big is your application?  How devoted is your team to "doing the right thing?" How well does your team understand the domain and where responsibilities should lie within each and every single class?

That's a lot of dependencies on others that you're introducing there.  Of course, your code is perfect and you'll never make a design mistake.  But how are you going to shield the project from the human fallibility of others?  How are you going to shield the project for the complexities of scale? A handful of views is nothing to keep in your memory. But what about hundreds?

MVC provides structure to help avoid some of those problems.

But at the same time, MVC isn't a silver bullet.  Here's some of the valid criticisms against it.

It tends to be heavy weight for implementing.  Where you could have gotten away with 1 class, you'll now have three.  On smaller projects, you're right to question the benefits of MVC.

It can be frustrating to stay within the structure of MVC.  There's always the temptation to let Controller code bleed into the View, or let the View directly access the Model. After you write your umpteenth wrapper function, you'll wonder why you're doing it.

MVC presumes your app will live forever and will change technologies.  If you never change the UI, the data source, or the business logic then you kind of wasted your time in encapsulating those layers in anticipation of change.

In summary, MVC is a tool just like any other.  Its longevity and resurgence in awareness proves how valuable it has been.  But it's not a silver bullet, not a panacea for all programming ailments.  Understand it and use it (or not!) as appropriate for your projects.

Title: Clean, Modular Code vs MV* Frameworks

Body:
I've been hearing a lot about the "new" MV* frameworks. I've tinkered with KnockoutJS (I created an invoicing application), but I much prefer to write clean, modular code in raw JavaScript - leveraging utility APIs and other libraries when necessary.

Given a methodical/structured/SOLID approach to writing a JavaScript application, where OOP, SOC, SRP and other design principles are adhered to, wouldn't the usage of MV* frameworks be superfluous?

Are there any articles that express/address these concerns?

I've found one in the past

note - I've migrated this question from SO to this site, as its more appropriate for this audience.


答:
I would probably implement something along the lines of this:

```<code>public abstract class Animal: ILegs
{
    public virtual void Walk(){/*Base logic for walking*/}
}

public interface ILegs
{
    void Walk();
}

public interface IJumpingLegs
{
    void Jump();
}

public interface IRunningLegs
{
    void Run();
}

public class Kangeroo : Animal, IJumpingLegs
{
    public void Jump()
    {
        //Logic for Jumping
    }
}

public class Tiger : Animal, IRunningLegs
{
    public void Run()
    {
        //Logic for Jumping
    }
}

//Custom Implementation
public class OtherAnimal : Animal
{
    public override void Walk() { /*Custom how I walk*/ }
}
</code>```

When instanciating my objects I would use

```<code>OtherAnimal a = new OtherAnimal();
a.Walk(); //Custom override logic fro OtherAnimal class

Tiger t = new Tiger();
t.Run();  //Custom Run logic
t.Walk(); //Logic from Animal abstract class
</code>```

Each Tiger/Kangeroo class only implements the necessary interface for each class and is not inheriting any unnecessary logic and not breaking the Liskov Substitution Principle mentioned by @Yusubov.

The Tiger/Kangeroo class also use the base Walk() logic from the Animal abstract class and have the option if necessary to override it lie the OtherAnimal class does.

Just don't implement a Fish class or similar extending the Animal. Fish don't walk, or have Legs!!

Body:
I would probably implement something along the lines of this:

public abstract class Animal: ILegs
{
    public virtual void Walk(){/*Base logic for walking*/}
}

public interface ILegs
{
    void Walk();
}

public interface IJumpingLegs
{
    void Jump();
}

public interface IRunningLegs
{
    void Run();
}

public class Kangeroo : Animal, IJumpingLegs
{
    public void Jump()
    {
        //Logic for Jumping
    }
}

public class Tiger : Animal, IRunningLegs
{
    public void Run()
    {
        //Logic for Jumping
    }
}

//Custom Implementation
public class OtherAnimal : Animal
{
    public override void Walk() { /*Custom how I walk*/ }
}

When instanciating my objects I would use

OtherAnimal a = new OtherAnimal();
a.Walk(); //Custom override logic fro OtherAnimal class

Tiger t = new Tiger();
t.Run();  //Custom Run logic
t.Walk(); //Logic from Animal abstract class

Each Tiger/Kangeroo class only implements the necessary interface for each class and is not inheriting any unnecessary logic and not breaking the Liskov Substitution Principle mentioned by @Yusubov.

The Tiger/Kangeroo class also use the base Walk() logic from the Animal abstract class and have the option if necessary to override it lie the OtherAnimal class does.

Just don't implement a Fish class or similar extending the Animal. Fish don't walk, or have Legs!!


问:
Modelling REST endpoints with data that not all users have access to
I am trying to figure out the best way around a small problem i have with a design for a Hypermedia API i am currently building.

I have a notion of a site, very simple doesn't have much going on and it is accesible via:

/sites

/sites/{id}

Sites have a bunch of properties and none is all too sensitive.  However, a site has the notion of a budget, its nothing too exotic, in fact for the offset it will be a simple object that holds a decimal field and a pointer to a currency, but this should not be visible to every person requesting the resource as it is deemed as sensitive information that project managers should have.

Some options:

Just sent it - problem here is i don't know what the clients consuming the API will do with it and this is just a terrible option all round

Send down an empty object i.e. Budget:{}

Make Budget a sub-resource of Site and only give users with the appropriate access level access to it

As this is a hypermedia API i am leaning towards option 3, as i could(or not) as the case may be provide the link and also protect that endpoint separately, but at the same time this feels a little wrong, not sure why.

Item 3 could look like this:

/sites/{id}/budget

Anyone out there with some helpful advice on something like this?

答:
Treat it as a sub-resource

Your REST API should be decoupled from the internal domain model. Therefore you can provide a limited picture of your internal domain state through the REST API. This is one of the main features of REST.

To accomplish this, you may want to look into the Hypertext Application Language (HAL) representation.


答:
It is a mistake to use inheritance with the Legs classes and interfaces.(But if your teacher/boss insists that you have to...you'll probably have to give in.)

Your design works well enough for the requirements you listed. But suppose there is a Horse that can both run and jump. How do you implement that?

I suggest that WalkingLegs, RunningLegs, and JumpingLegs should all be separate classes with no inheritance. The Tiger would have  WalkingLegs and RunningLegs, the Kangaroo would have WalkingLegs and JumpingLegs, and the Horse would have all three.

The above suggestion confuses the Legs metaphor. What we are really modeling is behavior, not types of legs.

Using classes to represent a behavior is part of the strategy pattern. In the strategy pattern, behaviors have different implementations (in this example, different implements of walking, jumping, etc.)


答: It's probably used in places where they are developing APIs for consumption. The C++ STL is one of the few APIs that has complexity restrictions imposed on its algorithms. But for the everyday working programmer/senior programmer/designer/architect it doesn't cross their minds much.</p>


问:
Origin of common list-processing function names
Some higher-order functions for operating on lists or arrays have been repeatedly adopted or reinvented.  The functions map, fold[l|r], and filter are found together in several programming languages, such as Scheme, ML, and Python, that don't seem to have a common ancestor.  I'm going with these three names to keep the question focused.

To show that the names are not universal, here is a sampling of names for equivalent functionality in other languages.  C++ has transform instead of map and remove_if instead of filter (reversing the meaning of the predicate).  Lisp has mapcar instead of map, remove-if-not instead of filter, and reduce instead of fold (Some modern Lisp variants have map but this appears to be a derived form.)  C# uses Select instead of map and Where instead of filter.  C#'s names came from SQL via LINQ, and despite the name changes, their functionality was influenced by Haskell, which was itself influenced by ML.

The names map, fold, and filter are widespread, but not universal.  This suggests that they were borrowed from an influential source into other contemporary languages.  Where did these function names come from?

答:
The only universal word in your list is map and it already appears in the original paper on Lisp in 1960 (under the guise of maplist).
The paper also has search (AKA filter, AKA remove-if-not).

I think the reason map endured while the others have variants is that map comes from relatively ancient, established, common & elementary math while catamorphism (AKA reduce AKA fold &c) is a relatively advanced concept, from a relatively obscure recently developed (more or less simultaneously with CS) domain, and it was introduced (in the late 1980-ies) when  reduce was available in Lisp for over a decade.

Others (filter AKA remove-if-not) are even more ad hoc in CS/programming, so people felt even more comfortable picking their own name for them.


问:
What's a good, concise way to explain the dangers of copy-paste programming to non-programmers?
I'm looking for a good analogy or metaphor that could illustrate the problems of copy-paste programming to non-programmers. I occasionally do code/system reviews for potential clients, and one of the common problems I see are vast amounts of copy-paste code all over their code bases. It's something I routinely call out in the reviews, and each time I have to explain why this is a problem (this is especially difficult with clients who know just enough about programming to understand that reuse is a good thing, but not enough to understand why copy-paste isn't a good form of reuse).
Obviously, I can (and do) explain the problem in terms of code maintenance, but it would be nice to have a good, concise analogy for this problem that would hit home with non-programmers. Bonus if the analogy illustrates why search-and-replace is not an effective solution for this problem.
Any suggestions?

Just to clarify (based on Jaroslav's answer below) - I'm not talking about using code snippets here; what I see (disturbingly often) is copying-and-pasting of vast swaths of code, or a ten-line piece of code to get some user data (complete with inline SQL query) pasted into dozens of PHP or ASP.NET pages. So, duplicate code from elsewhere in the same project.

Update: There are several really good answers here; I've explained in the comments why I chose Scott Whitlock's answer, but I would also highly, highly recommend whatsisname's answer if you're dealing with customers who are familiar with manufacturing at all.

答: Let's say you have 5 girlfriends (you sly dog you) and you wish to send all of them a valentine's message. You type the first letter, adds her name and mention something memorable you guys shared. You then copy and paste the letter four times, each time missing an instance of girlfriend #1's name with copy and paste because you made a typo. Now, 4 of your five girlfriends are on their way to girlfriend #1's house.</p>


答:
There are also security and code integrity concerns.

As demonstrated here, it is possible to embed malicious data in unicode characters that are transferred to the clipboard.

Depending on how your editor responds to unicode characters, this may result in unexpected changes of your sourcecode, unexpected compiler outputs or some things I haven't thought of yet.

Title: What's a good, concise way to explain the dangers of copy-paste programming to non-programmers?

Body:
I'm looking for a good analogy or metaphor that could illustrate the problems of copy-paste programming to non-programmers. I occasionally do code/system reviews for potential clients, and one of the common problems I see are vast amounts of copy-paste code all over their code bases. It's something I routinely call out in the reviews, and each time I have to explain why this is a problem (this is especially difficult with clients who know just enough about programming to understand that reuse is a good thing, but not enough to understand why copy-paste isn't a good form of reuse).
Obviously, I can (and do) explain the problem in terms of code maintenance, but it would be nice to have a good, concise analogy for this problem that would hit home with non-programmers. Bonus if the analogy illustrates why search-and-replace is not an effective solution for this problem.
Any suggestions?

Just to clarify (based on Jaroslav's answer below) - I'm not talking about using code snippets here; what I see (disturbingly often) is copying-and-pasting of vast swaths of code, or a ten-line piece of code to get some user data (complete with inline SQL query) pasted into dozens of PHP or ASP.NET pages. So, duplicate code from elsewhere in the same project.

Update: There are several really good answers here; I've explained in the comments why I chose Scott Whitlock's answer, but I would also highly, highly recommend whatsisname's answer if you're dealing with customers who are familiar with manufacturing at all.


问:
What are examples of comments that tell you why instead of how or what?
First of all, in this question I'd like to stay away from the polemic on whether source code commenting is good or bad. I'm just trying to understand more clearly what people mean when they talk about comments that tell you WHY, WHAT or HOW.

We often see guidelines like "Comments should tell you WHY; code itself should tell you HOW". It is easy to agree with the statement on an abstract level. However, people usually drop this like a dogma, and leave the room without further explanation. I've seen this used in so many different places and contexts, that it looks like people can agree on the catchphrase, but they seem to be talking about different things entirely.

So, back to the question: if comments should tell you WHY, what is this WHY we are talking about? Is this the reason why that piece of code exists in the first place? Is this what that piece code should be doing? I would really appreciate if someone could give a clear explanation, and then add some good examples (bad examples are not really needed, but fell free to add them for contrast).

There are many questions on whether comments are good or bad, but no one that addresses the specific question of what are good examples of comments that tell you WHY.

答:
I just wrote this comment; it's a concrete example of explaining why a line of code is what it is, and in particular why I changed it.

The method examines stored data and assesses whether it's complete through the present day on the one end, and through the start date on the other end.

```<code>// In principal, this should be ">=", as we may have data up to the account start
// date but not complete for that day; in practice, 98% of the time if we have
// data for the start date it *is* complete, and requerying it would be a waste
// of time.
while (endDate > accountStartDate)
    ...
</code>```

As you can probably guess, the greater-than operator had been a greater-or-equal.  The comment explains why the old value makes sense and why the new value is better.  If anyone looks at this in the future, they'll see that the use of ">" is not an oversight, but an optimization.  They can then change it or leave it, based on the need at that time.

Body:
I just wrote this comment; it's a concrete example of explaining why a line of code is what it is, and in particular why I changed it.

The method examines stored data and assesses whether it's complete through the present day on the one end, and through the start date on the other end.

// In principal, this should be ">=", as we may have data up to the account start
// date but not complete for that day; in practice, 98% of the time if we have
// data for the start date it *is* complete, and requerying it would be a waste
// of time.
while (endDate > accountStartDate)
    ...

As you can probably guess, the greater-than operator had been a greater-or-equal.  The comment explains why the old value makes sense and why the new value is better.  If anyone looks at this in the future, they'll see that the use of ">" is not an oversight, but an optimization.  They can then change it or leave it, based on the need at that time.


问:
MyListActivity, MyCursorAdapter, MyViewHolder -- nested classes or not?
I am using several activities based on the ListActivity. All of them display information from different SQLite queries, and all of them use the ViewHolder optimization. The cursor adapter have to be specialized, and the view holder is also special for the purpose. Therefore, they are defined as private classes inside the MyListActivity definition.

Not having too much experience with Java, my question is whether the chosen approach is correct. Possibly the non-nested classes (i.e. flat, separate *.java file) is not better for reasons unknown to me.

What are the pros and cons of nested/flat approaches?

To be more specific, here is the code skeleton:

```<code>public class MyListActivity extends ListActivity
        implements LoaderManager.LoaderCallbacks<Cursor> {

    private MyCursorAdapter myAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        ...
        initLoaderAndSetListAdapter();
    }

    private static class MyViewHolder {
        public TextView code;
        public CharArrayBuffer codeBuffer = new CharArrayBuffer(20);
        ...
    }

    private class MyCursorAdapter extends CursorAdapter {

        private final LayoutInflater mInflater;
        private final int mLayout;

        public MyCursorAdapter(Context context, Cursor c, int flags) {
            super(context, c, flags);
            mLayout = R.layout.the_specific_view_for_the_list_item;
            mInflater = (LayoutInflater)
                    context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            View v = mInflater.inflate(mLayout, parent, false);
            MyViewHolder holder = new MyViewHolder();
            holder.code = (TextView) v.findViewById(R.id.code);
            v.setTag(holder);
            return v;
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            MyViewHolder holder = (MyViewHolder) view.getTag();
            cursor.copyStringToBuffer(1, holder.codeBuffer);  // COLUMN_CODE
            ...
            holder.code.setText(holder.codeBuffer.data, 0, holder.codeBuffer.sizeCopied);
            ...
        }
    }

    private void initLoaderAndSetListAdapter() {
        getLoaderManager().initLoader(0, null, this);
        myAdapter = new MyCursorAdapter(this, null, 0);
        setListAdapter(myAdapter);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        Uri uri = ... set the uri based on situation... ;
        String[] projection = { ... };
        CursorLoader cursorLoader = new CursorLoader(this,
                uri, projection,
                null, null,
                orderingInfo);
        return cursorLoader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        myAdapter.swapCursor(data);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        myAdapter.swapCursor(null);
    }
}
</code>```

The question is specific to the described situation that I meet repeatedly. Please, do not consider it as general nested classes or not.

答:
Oracle says:

Why Use Nested Classes?

There are several compelling reasons for using nested classes, among
them:

It is a way of logically grouping classes that are only used in one place.

It increases encapsulation.

Nested classes can lead to more readable and maintainable code.

Logical grouping of classes  — If a class is useful to only one other class, then it is logical to embed it in that class and keep the
two together. Nesting such "helper classes" makes their package more
streamlined.

Increased encapsulation — Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared
private. By hiding class B within class A, A's members can be declared
private and B can access them. In addition, B itself can be hidden
from the outside world.

Now apply those criteria to your proposed use of nested classes.  Do the benefits justify the additional complexity of class nesting?

Nested classes can only be used inside their outer class, so they need to prove their worth within the class, since they're not usable anywhere else.  The overall question is this: can MyViewHolder be useful anywhere else in the program, or is it only ever going to be useful in MyListActivity?


答:
It depends on what your are doing.

For web developers (such as me) this usually matters a lot. You want web apps to scale. If your app has a bottleneck that scales with O(n^2), and you think this is just fine, because your server can handle 1000 simultaneous users, it seems you needn't care. The thing is, to handle just twice as many (which is reasonably probable to happen just over night), you'll be needing 4 times the computational power. Ideally you want web apps to scale at O(n), because hardware is cheap at a sensible constant user/server ratio.

Generally in apps, where you have 100000s of objects, big O will come and eat you. You are enourmously vulnerable to peaks. For example, I am currently working on a 3D game, which is an app that handles loads of data. Apart from the rendering, you have collision checking, navigation etc. You can't afford just going the obvious way. You need efficent algorithms, you need a lot of caching so the less efficient ones amortize. And so on.

Of course if what you do is something like making a mobile app by throwing together a GUI in an interface designer, wire that up with some web services and that's it, then you will never have issues with complexity. Because the web services you call already take care of it.


问:
Why are there no package management systems for C and C++?
There are some programming languages for which exist a package management system:

CTAN for TeX

CPAN for Perl

Pip & Eggs for Python

Maven for Java

cabal for Haskell

Gems for Ruby

npm for NodeJS

bower for frontend Javascript & CSS

nuget for C#

composer for PHP

Is there any other languages with such systems? What about C and C++? (that's the main question!) Why there are no such systems for them? And isn't creating packages for yum, apt-get or other general package management systems better?

答:
I realize this is not a cross-platform solution, but it should be added to the mix.

CoApp recently announced support for C++ package management using NuGet: http://blog.nuget.org/20130426/native-support.html

This currently only works with the Visual Studio compiler, but there have been many requests to get this working on other platforms.


答:
I think the questions we need to ask in order to answer yours are "What do other languages/ecosystems gain from having their own centralized package repository?" and "Does this apply to C/C++?"

I feel the answer to the first question has something to do with the initial promotion of a new language: the early adopters want to make it as easy as possible for newcomers to enter the ecosystem, acquire useful, tested code and contribute back their own. For obvious reasons, the "usage graph" always has a single root - the creator(s) of the language. There's usually one reference implementation (at least initially) and therefore any code you might want to share has to conform to it.

This makes it easy to create packages that just download and compile. Certainly, had C or C++ been introduced in 2013, their communities could have followed a similar evolutionary path, but they hadn't and there's no one single prevailing toolchain to apply a package manager to. This makes the implementation of such a program too troublesome to be worth the hassle. (should you make users choose between libfoo-gcc and libfoo-vs? Do you leave it up to the packager to resolve? Or the build process? If so, how is a package any different than a straight-up tarball?)

So to sum up my answer to the first question, I think the pattern of creating package managers serves mostly to drive adoption.

With that in mind, I think it's fairly easy to see why no single system has risen to fulfill this need - because the need doesn't exist for C and C++ programmers. What does constitute a problem for the C and C++ community (or any programmer community, really) is the need originally implied: to distribute, keep up to date and contribute back code. This has been solved many times by different people with varying degrees of success, and indeed one system is gaining significant market share: git (and some other systems before that).

Basically when the problems differ, the solutions look different too, but IMHO the difference between typing gem install and git clone is moot.

Title: Why are there no package management systems for C and C++?

Body:
There are some programming languages for which exist a package management system:

CTAN for TeX

CPAN for Perl

Pip & Eggs for Python

Maven for Java

cabal for Haskell

Gems for Ruby

npm for NodeJS

bower for frontend Javascript & CSS

nuget for C#

composer for PHP

Is there any other languages with such systems? What about C and C++? (that's the main question!) Why there are no such systems for them? And isn't creating packages for yum, apt-get or other general package management systems better?


问:
What should be the sense to use strict comparison to this specific string: 'final'
In a code review that I was doing to a coworker, I said that here:

```<code>if (someValue === 'final'){
</code>```

There is no sense to use strict comparison because the only way to pass it as true is with other string value equals to final.

I think that it is enough:

```<code>if (someValue == 'final'){
</code>```

His argument is that an object could have a toString method that returns that string but strictly it does not have the same datatype.

While that is true, as a computer(that are not intelligent as human), in the other hand, there is not sense, as at the end of the way the only way to pass this as true is with a string equals to final. This was his sample code:

```<code>Test = function(){}
Test.prototype.toString = function () { return 'final'; }
var disagreeDaniel = new Test();
document.getElementById('foo').innerHTML = (disagreeDaniel == 'final');
</code>```

So my point here guys, is that I need you get better explanation to him why there is not sense of the strict comparison on a fixed strict like 'final' because there is no way to pass it as positive with a value different than 'final'.(his example at the end return the string)

For me strict comparison is useful for booleans, nulls, undefined, zero, where those could pass all as false in some cases. I want to hear your opinions.

====== Update ==========

It is easy to identify that people does not read. My question was the sense of use === to compare to 'final'. I got a lot of explanations of things nothing to do. For compare to null, false, zero etc, I said that I used === for THOSE cases but not for long strings. but people tried to explained me about null, false, zero, etc. The verdict until now is that there is not a SOLID argument(there are some good ones but not solid) that demonstrate why using === for compare to 'final' should be better than use ==(read again, is just this use case, I'm talking about one specific use case).

I also spoke with my coworker, I gave him the +1 to the code. I do not have problems with ===, my problem never had to use it, my point always was and is, and will be, what should be the sense, and looks like it would be a question with nevertheless answer.

ps. other thing that I learned time ago, is to never be aggressive with other opinions; "technical topics" for several programmers, are like religion for religious(and some guys here just remembered me it).

ps2. I marked as solved to be democratic, I do not want to demonstrate anything, just thought this site is for good discussions, and I got that. :D

答:
Yes, for example typeof x == "string" is functionally exactly the same as typeof x === "string".

However, x == " ", is not even remotely the same as x === " " since a string that is full of whitespace coerces towards 0 and 0 == " " //true or false == " " //true .

=== is written because the extra cognitive load required to judge each scenario individually for possible one character savings is just not worth it. I bet you that you or most programmers did not even know about the whitespace strings. Your brain needs to confirm that == "final" is not in any corner case, and only then you can proceed writing it.

You can wake me up the middle of the night and I will recite all the == rules and corner cases by heart, but that doesn't mean I will want to go through to them every time an equality comparison is needed.

A notable exception is == null which should be memorized as "undefined or null" and is even specially supported by jshint which otherwise enforces ===.

And wait, there is more. From spec

ECMAScript implementations must recognise all of the white space characters defined in Unicode 3.0. Later editions of the Unicode Standard may define other white space characters. ECMAScript implementations may recognise white space characters from later editions of the Unicode Standard

That implies the operation == is implementation defined for comparisons of string and boolean/object/number

For example:

```<code>function equals( x ) {
    return x == "\ufeff\ufeff";
}
alert(equals(0));
</code>```

Gives true on Firefox but false on Chrome.

Body:
Yes, for example typeof x == "string" is functionally exactly the same as typeof x === "string".

However, x == " ", is not even remotely the same as x === " " since a string that is full of whitespace coerces towards 0 and 0 == " " //true or false == " " //true .

=== is written because the extra cognitive load required to judge each scenario individually for possible one character savings is just not worth it. I bet you that you or most programmers did not even know about the whitespace strings. Your brain needs to confirm that == "final" is not in any corner case, and only then you can proceed writing it.

You can wake me up the middle of the night and I will recite all the == rules and corner cases by heart, but that doesn't mean I will want to go through to them every time an equality comparison is needed.

A notable exception is == null which should be memorized as "undefined or null" and is even specially supported by jshint which otherwise enforces ===.

And wait, there is more. From spec

ECMAScript implementations must recognise all of the white space characters defined in Unicode 3.0. Later editions of the Unicode Standard may define other white space characters. ECMAScript implementations may recognise white space characters from later editions of the Unicode Standard

That implies the operation == is implementation defined for comparisons of string and boolean/object/number

For example:

function equals( x ) {
    return x == "\ufeff\ufeff";
}
alert(equals(0));

Gives true on Firefox but false on Chrome.


答:
Memo to self!:

I and many others ask themselves this question regularly.

I think the real reason we ask this is because we have become lazy.

This knowledge will never date or become obsolete. You may not apply it directly on a day to day basis but you will use it subconsciously and it will have a positive affect on your design decisions. One day it may save you or others hours and days of coding.

As more problems are encapsulated by 3rd party libraries and tools and are available to more and more developers, you will need to know this knowledge to distinguish yourself from others and to help solve new problems.


问:
Is this a good use case?
I've been studying object oriented analysis and, so to get started with this in practice I've decided to first of all build my own management system to have my customers data and so on. Trying to gather requirements for the first time and write use cases for the first time led me to some doubts. I want to ask here about some doubts regarding the use cases.

One of the requirements I've thought of was "manage customers". From this requirement I've obtained some use cases:

Register new legal person as customer;

Register new natural person as customer;

Update and correct customer data;

Remove a customer from the system;

Read customer's summary;

Now, I'm greatly in doubt about all of this. First, is this right: take one single requirement and from it derive many different use cases? Or should be just one use case "Manage Customers" containing everything?

Second, I'll give an example about what I did. I choose to start by the first one. So I wrote the following use case:

Title: Register new legal person as customer;

Actor: User;

Scenario: The user chooses to register a new company as customer. The user informs the company data and the system validates the data informed. The user is then prompted to inform the data of the responsible for the company and the system validates the data informed. The user is then taken to the list of all legal person customers.

Now, I'm pretty sure I'm not doing this right. First, this seems to simple, it's just like if we said "well, the user goes and register the data". Second, all of the others use cases would be exactly like that, so I can't see how this is going to help me out. Third, from this use case I could obtain just three possible objects "legal person customer" and "responsible for the company", so I really think this is not enough.

Also, usually there are many requirements like that "manage customers", "manage employees" or "manage suppliers" and it seems at first tha they will always be like that. Is this correct? Those kind of requirements always end up with this kind of uses cases that are simple like this?

Am I doing this right? Is there something wrong with the uses cases I've figured out and the way I wrote that particular use case? How do we work with this kind of use cases that are so simple that the scenario is almost like just stating again the objective of the use case?

I know there are many questions there, but any kind of help is appreciated. I'm starting now to work with this kind of thing and I'm unsure if I'm doing things right. Thanks very much in advance!

答:
These use cases look fine to me.

What you may not be realizing is that use cases can differ based on "roles..." that is, some people may have the authority to review customer accounts, but others may not.  The roles and responsibilities of a product manager are going to be dramatically different than those of a clerk.

Consequently, writing your use cases this way will surface requirements based not only on what kind of information certain users have access to, but also what services are required and expected from the system by each user.

Your use cases will also help you define the roles... If you find that a lot of the use cases are similar, you can combine their common elements into a role.  Like many other software development activities, this process is iterative: you will refine your use cases as you and your customer begin to understand them better.

Title: Is this a good use case?


答:
The question I would ask your coworker is why someone would go through all the trouble of creating an object with an appropriate toString method, then not want it to compare equal to 'final'?  In other words, why would not being the same type be a problem if the values are semantically equivalent?  Certainly no one is going to write code like his counter-example by accident.

In my opinion, using strict comparison when it isn't needed violates the open/closed principle.  It shuts down potential avenues of extension.  Not using a feature of a language for the sake of "consistency" is ridiculous.  You don't write i += 1 instead of i++ so you can be consistent with i += 2.  By all means, be consistent where the situations are the same, but don't be a slave to superficial consistency when the situations differ.

Most people think of the OCP in terms of classes, but it also applies to functions.  In general, it means to minimize the amount of code that will need to change when you add functionality to your program.  In other words, prefer adding code to changing code.

99% of the time, you should be comparing two values of the same type, and those times where comparing different types is required should be blindingly obvious and intentional.  If you have no idea whether someValue is a string or not, you have bigger fish to fry.

Title: What should be the sense to use strict comparison to this specific string: 'final'

Body:
In a code review that I was doing to a coworker, I said that here:

```<code>if (someValue === 'final'){
</code>```

There is no sense to use strict comparison because the only way to pass it as true is with other string value equals to final.

I think that it is enough:

```<code>if (someValue == 'final'){
</code>```

His argument is that an object could have a toString method that returns that string but strictly it does not have the same datatype.

While that is true, as a computer(that are not intelligent as human), in the other hand, there is not sense, as at the end of the way the only way to pass this as true is with a string equals to final. This was his sample code:

```<code>Test = function(){}
Test.prototype.toString = function () { return 'final'; }
var disagreeDaniel = new Test();
document.getElementById('foo').innerHTML = (disagreeDaniel == 'final');
</code>```

So my point here guys, is that I need you get better explanation to him why there is not sense of the strict comparison on a fixed strict like 'final' because there is no way to pass it as positive with a value different than 'final'.(his example at the end return the string)

For me strict comparison is useful for booleans, nulls, undefined, zero, where those could pass all as false in some cases. I want to hear your opinions.

====== Update ==========

It is easy to identify that people does not read. My question was the sense of use === to compare to 'final'. I got a lot of explanations of things nothing to do. For compare to null, false, zero etc, I said that I used === for THOSE cases but not for long strings. but people tried to explained me about null, false, zero, etc. The verdict until now is that there is not a SOLID argument(there are some good ones but not solid) that demonstrate why using === for compare to 'final' should be better than use ==(read again, is just this use case, I'm talking about one specific use case).

I also spoke with my coworker, I gave him the +1 to the code. I do not have problems with ===, my problem never had to use it, my point always was and is, and will be, what should be the sense, and looks like it would be a question with nevertheless answer.

ps. other thing that I learned time ago, is to never be aggressive with other opinions; "technical topics" for several programmers, are like religion for religious(and some guys here just remembered me it).

ps2. I marked as solved to be democratic, I do not want to demonstrate anything, just thought this site is for good discussions, and I got that. :D


问:
What to name a new interface that is replacing an existing one?
We're redesigning our application's plugin interface, so we're using the Adapter pattern with our proof-of-concept design to show that the new interface will function without committing to using it in the application itself.

We don't know what to call this new interface. It serves the same purpose as the old one - let's call that one CAbstractAppPlugin. Furthermore it will likely be, like its predecessor, an abstract class rather than a pure virtual interface (C++) indicating that we should still use "CAbstract" instead of "I". Slapping a "New" or "2" onto the name seems silly, but adopting a very similar name could lead to confusion until the old one is deprecated.

So how do you name a thing X that's replacing thing Y?

答:
Unless they're something conceptual that you can add to the name, I'd just go with CAbstractAppPlugin2 or something similar.  Your documentation can identify the differences.

CAbstractAppPluginWithSuperSizeFunctionAdded seems equally ridiculous, if not more so.


问:
Inner workings of the IF() function - why aren't expressions evaluated?

Short version

How does the IF() function cause the passed expressions to NOT be evaluated prior to being passed in as parameters?

Detailed version

I am part of a standards committee, and a discussion was initiated which, in general, is trying to ban the use of the IIF() function. The general consensus is that if you want to do a short line-length assignment IF() is okay. And if you for some reason want to evaluate two expressions, don't try to accomplish that all on one line, explicitly and purposefully evaluate the expressions on seperate lines, then do an IF() call with the results in the If True and If Else parameters.

I'm asserting that before a Function(param1, expression) is stepped into, any expressions are evaluated. Then, their evaluated value is passed as a parameter.

That being asserted, this makes sense:

```<code>Sub Main()
    Dim intTest As Integer = 0
    Dim blnResult As Boolean = IIf(2 = 2, Integer.TryParse("3", intTest), Integer.TryParse("4", intTest))
    'intTest = 4
End Sub
</code>```

As expected, blnResult is True.

Because the conditional of the IIF() function is True, the value of the expression in the "If True" parameter is the resulting assignment.

But BOTH the If True AND If Else expressions were evaluated (in written order) prior to even stepping into the IIF() function, so intTest became 4.

As far as I'm concerned, that is programatically expected, but not the results desired.

On the reverse side of the coin, we have this:

```<code>Sub Main()
    Dim intTest As Integer = 0
    Dim blnResult As Boolean = If(2 = 2, Integer.TryParse("3", intTest), Integer.TryParse("4", intTest))
    'intTest = 3
End Sub
</code>```

As the inverse of the previous issue, we now have:

As expected, blnResult is True.

Because the conditional of the IF() function is True, the value of the expression in the "If True" parameter is the resulting assignment.

But ONLY the If True (in this case) is evaluated, so intTest became 3.

As far as I'm concerned, that is the results desired, but not programatically expected.

I'd like to see a custom function that does the same thing as IF().

答: IF() is treated as a special case by the compiler.  You can't make your own function that works exactly the same way without making your own compiler.  You could use delegates or lambda expressions to similar effect, though.


问:
Deciding how to model customer when it can be both natural and legal person
Suppose that we are developing some application that requires us to be able to manage customers and that those customers can be both natural and legal person. There are some different ways on which we can deal with it and I'm not sure which of them is the best regarding extensibility, code reuse and so on.

The first thing I thought was to construct two classes "NaturalCustomer" and "LegalCustomer". Then, the shared properties would be moved to a base class "Customer" and both NaturalCustomer and LegalCustomer would inherit from it.

The second thing I thought was "consider every customer as a natural person, and consider that a legal person customer is just a natural person that has one or more companies". In that case I would create a class "Customer" and then a class "CustumerCompany". If there are other companies in the application that share properties with CustomerCompany I would build a new class Company and inherit from it. In this approach there would be a zero-to-many relationship between Customer and CustomerCompany: a customer can have one or none companies.

I'm not really sure how to deal with this kind of problem. I'm just beginning with object oriented analysis and design and I'm still confused. The main problem is that if I select the first approach I wouldn't be really reusing lots of code. For instance, there could be other kinds of natural person in the app like "Employee" and it would share lots of properties with NaturalCustomer, and the same for companies, there could be companies like "Supplier" and it would share lots of properties with LegalCustomer and still I wouldn't be reusing it - so if I have to make a change on data that should be stored for companies I would have to change everywhere.

How do we deal in this kind of situation when multiple inheritance isn't allowed (that is I cannot make LegalCustomer inherit both from Customer and LegalPerson)?

Thanks very much in advance!

答:
What are you using Customer (legal or otherwise) for?

I suspect you might be confusing an account (id, balance, order history, etc..) and an authentication/person (name, form of address, etc.).

If you stretch things, it's a N-N relationship (although practically you can probably get away with a person having at most one account).


问:
Ruby: Multithreading a CSV with output
I have a script written in Ruby that has maxed out a core in my server's Xeon processor for the last 2 hours.  Since it's currently only using 1 of four possible cores, I want to try and rewrite the script to take advantage of all four cores.

I can use the .each_slice(n) method on the array that contains my data, but I'm curious as to what would then be the best/most efficient way to then write this data to a file.  It seems that I have a couple options.

Pass the file object to the functions being called by the Thread.new function (I assume this is legal in ruby?) and have them write as they see fit.

Have each function store the results in arrays, return the array on completion and let the main program then write to the disk.

Pass the same array object to each item and have them all add to it, then sort it.

My assumption is that although 2 would probably be more memory intensive, it'll by far be most efficient method.  Is there a different way to accomplish what I'm doing?

答:
Pass the file object to the functions being called by the Thread.new function (I assume this is legal in ruby?) and have them write as they see fit.

The way you describe it each thread will process the whole file.

Have each function store the results in arrays, return the array on completion and let the main program then write to the disk.

This is possible, however it may be memory intensive to fire up a new Thread.

Pass the same array object to each item and have them all add to it, then sort it.

Again this is possible, but may suffer from the same issues as 2.

If the tool maxed one core it may use a good chunk of 4 cores and starting up too many threads will use capacity you may want for the processing of the file. You may want to use a thread pool and farm out the work from there.

You may also want to preprocess the file, partially processing it or splitting it into more manageable chunks from processing.

Title: Ruby: Multithreading a CSV with output


答:
You're basically describing short-circuit evaluation.

I don't see the issue you describe as fundamentally different than the difference between And and AndAlso.  If you're going to ban IIF, you're also going to have to ban And, since it doesn't short-circuit either (both operands are always evaluated).

Banning language constructs that do not short circuit might make more sense if you also require your functions to never have side-effects.  If you allow side effects in your functions, those side effects will not occur if they are in the short-circuited part of a function evaluation.

Further Reading

Why would a language NOT use Short-circuit evaluation?

Title: Inner workings of the IF() function - why aren't expressions evaluated?

Body:
Short version

How does the IF() function cause the passed expressions to NOT be evaluated prior to being passed in as parameters?

Detailed version

I am part of a standards committee, and a discussion was initiated which, in general, is trying to ban the use of the IIF() function. The general consensus is that if you want to do a short line-length assignment IF() is okay. And if you for some reason want to evaluate two expressions, don't try to accomplish that all on one line, explicitly and purposefully evaluate the expressions on seperate lines, then do an IF() call with the results in the If True and If Else parameters.

I'm asserting that before a Function(param1, expression) is stepped into, any expressions are evaluated. Then, their evaluated value is passed as a parameter.

That being asserted, this makes sense:

```<code>Sub Main()
    Dim intTest As Integer = 0
    Dim blnResult As Boolean = IIf(2 = 2, Integer.TryParse("3", intTest), Integer.TryParse("4", intTest))
    'intTest = 4
End Sub
</code>```

As expected, blnResult is True.

Because the conditional of the IIF() function is True, the value of the expression in the "If True" parameter is the resulting assignment.

But BOTH the If True AND If Else expressions were evaluated (in written order) prior to even stepping into the IIF() function, so intTest became 4.

As far as I'm concerned, that is programatically expected, but not the results desired.

On the reverse side of the coin, we have this:

```<code>Sub Main()
    Dim intTest As Integer = 0
    Dim blnResult As Boolean = If(2 = 2, Integer.TryParse("3", intTest), Integer.TryParse("4", intTest))
    'intTest = 3
End Sub
</code>```

As the inverse of the previous issue, we now have:

As expected, blnResult is True.

Because the conditional of the IF() function is True, the value of the expression in the "If True" parameter is the resulting assignment.

But ONLY the If True (in this case) is evaluated, so intTest became 3.

As far as I'm concerned, that is the results desired, but not programatically expected.

I'd like to see a custom function that does the same thing as IF().


答:
You're occluding CUSTOMER with CONTACT.  The latter is whom you write contracts to and send bills to and if necessary send to a lawyer to sue.  The former is who can manage the details of your relation with.

Note that, while customers may or may not be actual persons, contacts always are.  And even customers who are legal persons may have someone else appointed as their contact.  (spouse, guardian, poa, executor, etc.)

If you need to indicate the precise relation between a contract and a customer, include it as a property of the relation between them, which may be included in the contact object if you will not be sharing contracts between customers.

Title: Deciding how to model customer when it can be both natural and legal person

Body:
Suppose that we are developing some application that requires us to be able to manage customers and that those customers can be both natural and legal person. There are some different ways on which we can deal with it and I'm not sure which of them is the best regarding extensibility, code reuse and so on.

The first thing I thought was to construct two classes "NaturalCustomer" and "LegalCustomer". Then, the shared properties would be moved to a base class "Customer" and both NaturalCustomer and LegalCustomer would inherit from it.

The second thing I thought was "consider every customer as a natural person, and consider that a legal person customer is just a natural person that has one or more companies". In that case I would create a class "Customer" and then a class "CustumerCompany". If there are other companies in the application that share properties with CustomerCompany I would build a new class Company and inherit from it. In this approach there would be a zero-to-many relationship between Customer and CustomerCompany: a customer can have one or none companies.

I'm not really sure how to deal with this kind of problem. I'm just beginning with object oriented analysis and design and I'm still confused. The main problem is that if I select the first approach I wouldn't be really reusing lots of code. For instance, there could be other kinds of natural person in the app like "Employee" and it would share lots of properties with NaturalCustomer, and the same for companies, there could be companies like "Supplier" and it would share lots of properties with LegalCustomer and still I wouldn't be reusing it - so if I have to make a change on data that should be stored for companies I would have to change everywhere.

How do we deal in this kind of situation when multiple inheritance isn't allowed (that is I cannot make LegalCustomer inherit both from Customer and LegalPerson)?

Thanks very much in advance!


答:
Much of the benefit of use cases comes from the answer to "What if?" For example, you say the system validates the information. What will your validations be? Are some fields mandatory, or is this just about the phone number or email address meeting a particular format? Let's say it's that some fields are mandatory,

What happens when the data doesn't meet the rules?

Can you save a customer that's only partially filled in? Will you just have to hit Cancel and lose all the other fields you typed in? If you can save a partial one, will it look different on the list of all customers? Will there be some things you can't do with it because it's not valid yet?

As you go through these use cases you will think of others too. For example what does it mean to remove a customer? Do you throw all the data away or keep it in some sort of history or archive section? If you keep it, how does a user ever go and look at it? Would you still include it in some summaries or lists or reports? What is the point of keeping it, or of deleting it?

And that might make you think hey, I should be able to back this data up some how. Or export it to Excel. Or make a list I can paste into some other application. And more use cases appear to you.

The most important thing about them is the thought process they lead you through. This matters most when you're interviewing someone else to get the business needs, and less when it's yourself, but it's still not zero. They can also be a handy reference for you later.

Title: Is this a good use case?

Body:
I've been studying object oriented analysis and, so to get started with this in practice I've decided to first of all build my own management system to have my customers data and so on. Trying to gather requirements for the first time and write use cases for the first time led me to some doubts. I want to ask here about some doubts regarding the use cases.

One of the requirements I've thought of was "manage customers". From this requirement I've obtained some use cases:

Register new legal person as customer;

Register new natural person as customer;

Update and correct customer data;

Remove a customer from the system;

Read customer's summary;

Now, I'm greatly in doubt about all of this. First, is this right: take one single requirement and from it derive many different use cases? Or should be just one use case "Manage Customers" containing everything?

Second, I'll give an example about what I did. I choose to start by the first one. So I wrote the following use case:

Title: Register new legal person as customer;

Actor: User;

Scenario: The user chooses to register a new company as customer. The user informs the company data and the system validates the data informed. The user is then prompted to inform the data of the responsible for the company and the system validates the data informed. The user is then taken to the list of all legal person customers.

Now, I'm pretty sure I'm not doing this right. First, this seems to simple, it's just like if we said "well, the user goes and register the data". Second, all of the others use cases would be exactly like that, so I can't see how this is going to help me out. Third, from this use case I could obtain just three possible objects "legal person customer" and "responsible for the company", so I really think this is not enough.

Also, usually there are many requirements like that "manage customers", "manage employees" or "manage suppliers" and it seems at first tha they will always be like that. Is this correct? Those kind of requirements always end up with this kind of uses cases that are simple like this?

Am I doing this right? Is there something wrong with the uses cases I've figured out and the way I wrote that particular use case? How do we work with this kind of use cases that are so simple that the scenario is almost like just stating again the objective of the use case?

I know there are many questions there, but any kind of help is appreciated. I'm starting now to work with this kind of thing and I'm unsure if I'm doing things right. Thanks very much in advance!


答:
Look into the concept of "Involved Party".

These can be legal or natural persons. You can then define a set of roles which relate them to your other Customers e.g. "Owns", "Works For", "Manages","Supplies", "Major Customer", "Creditor", "Debtor" etc. etc.

This concept is commonly used in financial systems to evaluate the overall risk. If you know a person "Owns" a company which is performing badly then it increases the risk of lending to the owner etc.


问:
BSD-2 Licence Code modifying
I'm using a BSD-2 Licence code in my project and with author permission, I modify the code. Now, I am using this code in my project. I know, I should mention Author's name and copyright information. Should, I mention What I modify in this code??</p>

答: You note in your answer that you got the authors permission to modify the code. This means that you now have a license, separate from the BSD license, to create a derived work. I would go back to the original author and ask if and how the author wants to be credited.</p>

OwnerDisplayName: Yasir Adnan

Title: BSD-2 Licence Code modifying


问:
difference between accounting and potential methods in Amortized Analysis
I was going through the Introduction to Algorithms by Cormen et al.In the chapter titled Amortized Analysis,the difference between accounting and potential methods is given like this

The accounting method overcharges some operations early in the
  sequence, storing the overcharge as “prepaid credit” on specific
  objects in the data structure. ...

The potential method maintains the credit as the “potential energy” of
  the data structure as a whole instead of associating the credit with
  individual objects within the data structure.

I tried to understand this using the example of resizable array which doubles its size when there is no space to insert an element.What I couldn't understand was the following sentence

storing the overcharge as “prepaid credit” on specific
  objects in the data structure

Using Accounting method:

ci = the charge for the i-th operation

c'i = amortized cost of the i-th operation

Si = array size after the i-th operation

bi = balance of credit after the i-th operation

```<code>i   1  2  3  4  5  6  7  8  9 10
si  1  2  4  4  8  8  8  8 16 16
ci  1  2  3  1  5  1  1  1  9  1
c'i 3  3  3  3  3  3  3  3  3  3
bi  2  3  3  5  3  5  7  9  3  5
</code>```

what exactly does "storing on specific  objects in the data structure"  mean  here?

In potential method ,if I use phi to be 2n-m where n = number of currebt elements in the array ,and m=array size

```<code>                n     m    phi
empty            0     0    0
add first elem   1     1    1
add secondelem   2     2    2
add third elem   3     4    2
add fourth elem  4     4    4
add fifth  elem  5     8    2
</code>```

In this ,what does it mean by "...the “potential energy” of the data structure as a whole instead of associating the credit with individual objects within the data structure."

答: The easiest way to understand amortized worst case analysis is to look at it as the average of the worst case performance over a long sequence of calls. A specific call can perform significantly worse or significantly better than the value, but the average of all the calls you make is going to deterministically approach that value.


答:
Technical answer:

We all know the If() function is "the ternary operator for VB.NET", whereas IIF() is a function (though still technically ternary). But saying If() is "the ternary operator" doesn't mean we know what's going on behind the scenes. Well, it turns out literally what's going on behind the scenes is that the If() function is evaluated as an expression which is interpreted by Common Intermediate Language (CIL) as a C-esque ternary operator, as displayed in the CIL below:

```<code>bool arg_20_0 = true ? int.TryParse("3", out intTest) : int.TryParse("4", out intTest);
</code>```

Description:

As part of the previous answers, it was brought up that the compiler probably interprets the IF() function as an expression instead of IF() actually being a regular function. It is partially true.

It was also brought up that if you were to ban IIF(), you'd also ban things like And and Or in place for short-circuit-only code. That was much closer to the real answer than I expected at first.

As a simple test, to which I am emberrassed I didn't try first, since I have ILSpy right on my desktop and use it all the time, I found that the real answer was the very first comment... MichaelT asked:

Just verifying, the IFF(A,B,C) is equivalent to A?B:C in a C-esque language?

LAWL!!! This is the CIL code:

```<code>bool arg_20_0 = true ? int.TryParse("3", out intTest) : int.TryParse("4", out intTest);
</code>```

So it's partially true that IF() is not a real function, but it's evaluated in the CIL before going to the compiler, so it's not a function of creating your own compiler. I'll give credit to MichaelT if he posts this as his answer, he was 100% correct without even knowing it.

Edit (addition):

As stated in the comment, I said I'd post the CIL for IIF(). This is it...

```<code>bool blnResult = Conversions.ToBoolean(Interaction.IIf(true, int.TryParse("3", out intTest), int.TryParse("4", out intTest)));
</code>```

Which is exactly as expected, because IIF is an actual function, so of course the parameters are evaluated before stepping into the function. I also sort of knew it was in the Interaction namespace. But like I said, IIF() isn't the mystery, it's understood, but just not the intended results.

Body:
Technical answer:

We all know the If() function is "the ternary operator for VB.NET", whereas IIF() is a function (though still technically ternary). But saying If() is "the ternary operator" doesn't mean we know what's going on behind the scenes. Well, it turns out literally what's going on behind the scenes is that the If() function is evaluated as an expression which is interpreted by Common Intermediate Language (CIL) as a C-esque ternary operator, as displayed in the CIL below:

bool arg_20_0 = true ? int.TryParse("3", out intTest) : int.TryParse("4", out intTest);

Description:

As part of the previous answers, it was brought up that the compiler probably interprets the IF() function as an expression instead of IF() actually being a regular function. It is partially true.

It was also brought up that if you were to ban IIF(), you'd also ban things like And and Or in place for short-circuit-only code. That was much closer to the real answer than I expected at first.

As a simple test, to which I am emberrassed I didn't try first, since I have ILSpy right on my desktop and use it all the time, I found that the real answer was the very first comment... MichaelT asked:

Just verifying, the IFF(A,B,C) is equivalent to A?B:C in a C-esque language?

LAWL!!! This is the CIL code:

bool arg_20_0 = true ? int.TryParse("3", out intTest) : int.TryParse("4", out intTest);

So it's partially true that IF() is not a real function, but it's evaluated in the CIL before going to the compiler, so it's not a function of creating your own compiler. I'll give credit to MichaelT if he posts this as his answer, he was 100% correct without even knowing it.

Edit (addition):

As stated in the comment, I said I'd post the CIL for IIF(). This is it...

bool blnResult = Conversions.ToBoolean(Interaction.IIf(true, int.TryParse("3", out intTest), int.TryParse("4", out intTest)));

Which is exactly as expected, because IIF is an actual function, so of course the parameters are evaluated before stepping into the function. I also sort of knew it was in the Interaction namespace. But like I said, IIF() isn't the mystery, it's understood, but just not the intended results.


问:
What's the best way to scale and split an agile team building a web app?
I've recently joined a company where I'm working as the scrum master on an agile development project building a web app.

The team is just about to be the maximum size for an agile team (expecting 9 next week).  We have talked about potentially splitting the team into two teams, not so much to shorten standups (which aren't excessive at the moment) but to stop people from being completely bored in sprint planning sessions (which again aren't excessively long).

There are two very distinct layers to the project - high technical backend dev (like seriously complex), and UI design/build/integration.  It seems that when the backend guys are talking technical the UI guys zone out, and vice versa.  It seems like the logical way to split the team if only to be more time efficient, but I have one massive reservation in that all I might really be doing is reducing collaboration and knowledge sharing.  The two teams just won't really have a good idea about what the rest of the team are building.

Does anyone have any experience in dealing with something like this?

答:
That is unfortunate the UI guys don't care about the detail of the complex backend work.  This sounds more like a discussion topic for a retrospective.  Splitting the team along discipline would set a dangerous precedent, how soon would it be before the Requirements folks begin zoning out and not caring about what the UI guys are doing and ask for their own team.

I have always been in favor of vertical slices for my teams.  UI should listen to what the technical folks have to say, as they are the very folks who could help to make their job easier (Oh, that widget is going to cause you to do this, what if we used this widget instead).

Personally I would focus on the issue of the UI guys zoning out first, then once that dysfunction has been resolved, discuss how to best split up the teams.  I am not trying to vilify the UI guys, perhaps the technical folks could also do more to make their discussions more relatable to for the UI guys.

As others have said, the team should be allowed to self organize to determine the new structure.  Past experiences have taught me self-organization can only really work when everyone is concerned for the team, rather than their own discipline or interests.

Cheers!


问:
How much time should be spent with use cases?
I'm starting to work with agile iterative approach to software development and this question seems quite natural. After gathering the requirements I should write a few use cases to describe how the user interacts with the system while the requirements are being met. Now, how much time should we spent with this?

Should I spent something like a week figuring out the use cases, finish then and only then move to working with each of them to find the main objects? Or should I just write a few of them and get a small number to work with?

If I understood agile well, I think I should get just some of them and assure that the functionality being purposed there is indeed constructed and is already usable. Only then I should move to other use cases and review what was done in the use case finished. Am I right with this idea?

Thanks very much in advance!

答:
Spend enough time developing use cases to get a reasonably complete understanding of the problem domain.

There is some benefit to having a big-picture view of the system as a whole.  Therefore, I recommend that you complete your use case study first, before writing any code.

You can, however, begin identifying the objects from the use cases right away, as you will need some of those also before you begin coding.  Working with the object definitions and use cases together will also help increase your confidence in the overall design.


问:
Should model / table names be as generic as possible?
When naming a model, should the name be as generic as possible-- even if that won't be the name displayed to users?

For example let's imagine a Django model for liking another user's posts.

Does it make sense to name the model 'Like' even if I plan on displaying it as Kudos, Endorsements, Ups, etc?

Does it make sense to make the name as generic as possible, even if the name won't be the one displayed to the user?

答:
In my humble opinion, naming should be as specific as possible.  Following the single responsibility principle, table/field names should describe exactly what they were created for.  This can help a lot down the track.

Taking your example, I would name the model "Kudos" (if that's what you're going to call your likes) as you may, down the track have another field named "Like".  It will also help your developers communicate internally about concepts.  If, for example, you are told by management to "add 15 kudos to everyone's account", that directly maps to your database.  There is no translation required.

The only exception to this rule is if you have not yet decided on the name that will be shown to the user (which may happen for any number of reasons), in which case, it would be best to use the "best guess" at the most specific name.  You can always change it later (though, like all requirements changes, this gets more expensive down the track).