问:
"Comments are a code smell"
A coworker of mine believes that any use of in-code comments (ie, not javadoc style method or class comments) is a code smell.  What do you think?

答:
Comments should explain why, not how.

How type comments are usually better dealt with using refactoring. Personally, I usually avoid comments in favor of refactoring.

Before:

```<code># convert to cents
a = x * 100

# avg cents per customer
avg = a / n

# add to list
avgs < avg
t += 1
</code>```

after:

```<code>total_cents = total * 100
average_per_customer = total_cents / customer_count

track_average(average_per_customer)
</code>```

Title: "Comments are a code smell"

Body:
Comments should explain why, not how.

How type comments are usually better dealt with using refactoring. Personally, I usually avoid comments in favor of refactoring.

Before:

# convert to cents
a = x * 100

# avg cents per customer
avg = a / n

# add to list
avgs < avg
t += 1

after:

total_cents = total * 100
average_per_customer = total_cents / customer_count

track_average(average_per_customer)


问:
The present and future of programming in local languages
Can programming become language-independent? Will we always program in English? Will we ever be able to program in our local languages? Is there any research that addresses the matter? Are there any such developments?</p>

答:
As a matter of fact, programming already is as "language independent" (I suppose you wanted to say "natural language...") as it gets. You see out of 3-4 thousand languages spoken today on Earth, it only depends on one major natural language, that is English.

Imagine what would it look like if the dozens of major programming languages in use today were based on Swahili, French, Swedish, Russian, Slovak, Bosnian, Hungarian, Spanish, Catalonian...?

How would anyone not understanding these languages (all are admittedly by far harder than English in grammar) be able to make even a modest career advance, or just keep one self up-to-date. English today is what Latin used to be 2,000 years ago. Actually I dare say it delivers the promise of Esperanto without the hassle of reinventing the whe.. err.. the language.

ContentLicense: CC BY-SA 2.5


问:
How to illustrate to students why they should use the standard library?
Too often I run into students who:

Use arrays instead of vectors, thinking that it's "faster"

Use pointers because it's "faster"

Reinvent-the-wheel, often copying-pasting terrible C-ish code from the Internet

They have this ingrained impression that before they write "correct" code, they have to write "fast" code, at the expense of learning. I know that gurus like Stroustrup and Meyers don't spend many hours and dollars writing books and speaking at conferences about the standard library only for it to be completely ignored because the student thinks they're better than the compiler.

I suspect the reason is:

They're lazy. It's a lot easier to come up with crappy, C-ish code than it is to actually think about the problem and apply the appropriate tools

They don't want to read books

They think the standard library is slow

It's fun reinventing-the-wheel; unfortunately they don't do a lot of research into understanding the problem or how to solve it properly

The problem, I believe, is that to students, reading and watching videos are boring, and they tend not to listen to those who say "use vectors instead of arrays" but have trouble articulating why. I struggle to find an alternative means of teaching the important concepts without being obtuse or boring.

Any suggestions?

答:
If you're a teacher: set them the appropriate assignment.

Write a program using stl vector to do something. Then set them another assignment to repeat the same task using C arrays. Get them to compare the performance of each. You should be able to demonstrate the insignificant difference in performance afterwards. Don't use collections of primitive types either, make sure its a complex type - a map of Students in a list of Classes using a vector of classrooms might be a good place to start explaining these things (as a map is for lookup of student ID - make it a string not a int that can be used as an array index - a list of classes that are dynamically changed, and fixed list of rooms.)

Then do the same for map and list and dequeue. The idea is not so much to teach them the difference of reusing the sTL containers, but to let them find out for themselves. Once they've implemented a linked list using C pointers, compared to the 1-line of code to do a stl list, they might start to get a clue.

The other aspect is to teach them when to use which kind of container. If you also set tasks that use unique_ptr and shared_ptr you could teach them how much faster and safer it is to use these compared to juggling object lifetimes with raw pointers.

ContentLicense: CC BY-SA 3.0


问:
How do you dive into large code bases?
What tools and techniques do you use for exploring and learning an unknown code base?

I am thinking of tools like grep, ctags, unit-tests, functional test, class-diagram generators, call graphs, code metrics like sloccount, and so on. I'd be interested in your experiences, the helpers you used or wrote yourself and the size of the code base with which you worked.

I realize that becoming acquainted with a code base is a process that happens over time, and familiarity can mean anything from "I'm able to summarize the code" to "I can refactor and shrink it to 30% of the size". But how to even begin?

答:
Your situation is actually common. Anyone having to walk into a new job where there is existing code to work with is going to deal with some element of it. If the system is a really nasty legacy system, then it is very much like what you've described. Of course, there is never any current documentation.

First, many have recommended Working Effectively with Legacy Code by Michael Feathers. This is indeed a good book, with useful chapters like "I can't get this class into a test harness" or "My application has no structure" though sometimes Feathers can only offer more sympathy than solution. In particular, the book and its examples are largely geared to curly braces languages. If you are working with gnarled SQL procedures it may not be quite as useful. I think the chapter, "I don't understand this code well enough to change it," speaks to your issue. Feathers mentions here the obvious things like taking notes and marking up listings, but also makes a good point that you can delete unused code if you have source control. Lots of people leave commented sections of code in place, but that often isn't of help.

Next, I think your suggested approach is certainly a good step. You have to understand first at a high level what the purpose of the code is.

Definitely work with a mentor or someone on the team if you have to get questions answered.

Also, take the opportunity to support the code if defects are revealed (though sometimes you don't have to volunteer for this...the defect will find you!). Users can explain what they use the software for and how the defect is affecting them. That can often be a very useful bit of knowledge when trying to understand the meaning of the software. In addition, going into the code with a purposeful target to attack can sometimes help focus you when facing "the beast."

Title: How do you dive into large code bases?


问:
Object creation: when should I expose a factory vs wrapping class?
I am having some problems trying to figure out when to use a factory or to wrapper class. This question is slightly geared towards C# I guess, so I'm not sure if this is the correct place to ask.

Say there is a library that exposes an interface called IStackExchangeClient, and multiple differing implementations of that interface (private implementations that clients will not know about), HttpStackExchangeClient, UdpStackExchangeClient.

We can allow the object creation of the interface through a factory, like StackExchangeClientFactory.Create(), or we can wrap it up in another class like StackExchangeClient that internally does the same thing, but simply proxies.

In the second instance, clients can write new StackExchangeClient() which feels much more natural to me. So my question is, when do I choose one or the other? What are some of the considerations that I should be taking in?

I've thought hard about it and I can't choose between one style or the other, but clearly some parts of the .NET framework use factories, and some parts don't, even when there are multiple underlying implementations of its interface.

Thank you!

答:
```<code> > Object creation: when should I expose a factory vs wrapping class?
</code>```

Answer from unit-testing point of view:

If you want to do unit-testing and the test requires you to change the object-creation of child-items the factory (method or class) is the way to go.

If your program is scattered with several IOrderItem orderItem = new OrderItem(...) you cannot replace OrderItem with a fake.

If your progam uses the factory method IOrderItem orderItem = createOrderItem(..) it is easy to replace OrderItem with a fake by reimplementing/mocking the factory method.

The only pro wrapping-class argument i can think of is that it is more intuitive and easier to discover for the api-consumer as stated in @Frank Hileman s comment.

Body:
 > Object creation: when should I expose a factory vs wrapping class?

Answer from unit-testing point of view:

If you want to do unit-testing and the test requires you to change the object-creation of child-items the factory (method or class) is the way to go.

If your program is scattered with several IOrderItem orderItem = new OrderItem(...) you cannot replace OrderItem with a fake.

If your progam uses the factory method IOrderItem orderItem = createOrderItem(..) it is easy to replace OrderItem with a fake by reimplementing/mocking the factory method.

The only pro wrapping-class argument i can think of is that it is more intuitive and easier to discover for the api-consumer as stated in @Frank Hileman s comment.


答:
It's all about incentive.

This doesn't count for each and every student but in general:
Your students are in school to get a diploma. Your class is one of many obstacles they need to overcome to get that diploma. They want to pass that class with the least amount of effort.

Now you're also working with smart individuals and when you post a problem (give an assignment) your students will not start looking for different ways to solve it if they already "think" they have the answer.

Why read the book if you think you already know how to solve the assignments?

Your job as a teacher is to provide enough "obstacle" that the diploma doesn't lose its value.

Title: How to illustrate to students why they should use the standard library?

Body:
Too often I run into students who:

Use arrays instead of vectors, thinking that it's "faster"

Use pointers because it's "faster"

Reinvent-the-wheel, often copying-pasting terrible C-ish code from the Internet

They have this ingrained impression that before they write "correct" code, they have to write "fast" code, at the expense of learning. I know that gurus like Stroustrup and Meyers don't spend many hours and dollars writing books and speaking at conferences about the standard library only for it to be completely ignored because the student thinks they're better than the compiler.

I suspect the reason is:

They're lazy. It's a lot easier to come up with crappy, C-ish code than it is to actually think about the problem and apply the appropriate tools

They don't want to read books

They think the standard library is slow

It's fun reinventing-the-wheel; unfortunately they don't do a lot of research into understanding the problem or how to solve it properly

The problem, I believe, is that to students, reading and watching videos are boring, and they tend not to listen to those who say "use vectors instead of arrays" but have trouble articulating why. I struggle to find an alternative means of teaching the important concepts without being obtuse or boring.

Any suggestions?


答:
Is it your job to rate your students or their code? Then it is easy: make clear what you expect from them and what kind of code you think is good, and when they present you solutions with good or bad code, give them the appropriate ratings. Be sure your students know to get past your course the goal is not writing the "fastest" code, but the most correct, most readable and most standard code.

And lead by example: when you present programming concepts or show example solutions, do not use C-style arrays or C-style pointers by yourself. Mention their existence only as a side-note, but tell your students clearly that those are language elements C++ inherited from C, for which the standard lib has better alternatives. Tell them they should learn these when they have to deal with legacy code, but not for passing the exams.


问:
Should every member of a team use the same IDE?
Do you think it makes sense to enforce that every member of a team must use the same IDE?

For instance all engineers that are already on the team use IDE X. Two new engineers come and want to use IDE Y instead because that's what they have been using for several years now.

Do you have any experience with "mixed IDE" teams? If so what is it?

答: If your team relies on certain plugins available only to certain IDEs, then it only makes sense to unify everyone under the same development platform. I also find it easier to help someone with a development issue if they have the same IDE as me, whereas if I'm to read someones screen with an unfamiliar interface it'll take a bit longer.</p>


问:
Creating service to distribute passwords to architecture
We have big legacy code working for big corporation connecting to multiple remote/local databases.

The configuration files with IP, name and password for connecting to different databases are now handled manually. We have these files in git, but our passwords rotate on different schedule than our deployment, so we need to directly edit the configs on our servers(production, UAT, testing, development).

This is really tedious task and errors appear regularly. Different servers are connected to different databases and connecting multiple times with bad password will lock the id.

We are thinking about creating a service to distribute the config files into the servers. The idea is, that every midnight, some bash script on the server will access this service, and rewrite config files with data provided by this service.

Than, we only need to store name of server(to tell the service, which config we need) and SSH key to connect to service.

The question is, is this good solution? I see the problem that when one ssh key gets compromised, than all our passwords are available. Is there some other more standard way to solve our problem?

答:
You can use some Deployment management tool like Ansible ( my personal favourite, needs only python2, and public SSH keys added on server nodes ), Chef, Salt, and Puppet.

The question is, is this good solution? I see the problem that when one ssh key gets compromised, than all our passwords are available. Is there some other more standard way to solve our problem?

You can use different SSH keys for different servers/services and have this distribution service on small device ( like Raspberry Pi ), that doesn't have any open ports ( no SSH, only local management! ).

And in "strong security scenario" protect those SSH keys with password which will be provided by an admin ( each day ) and stored in encrypted memory ( and protected by IOMMU ).


问:
How to achieve inheritance when using just modules and vanilla functions in Python?
Python doesn't enforce any paradigm. It gives you freedom.
Python provides encapsulation at module level.

If I have a module A and have a module B with same interface. How do I sort of inherit B from A and override some functionality provided by B ?

答:
When You import Y module, that imports functions from module X with from X import *, all functions from X are available as they were in Y ( You can thing of that, like pasting content of X into Y ).

And, when you have multiple defs, Python will take the last one. So to override functions You have just to redefine those function after you import X.

Also, when You want to use original function from X in Your Y, you can add aditional import X and access it with X.functionName().

Example:

module1.py

```<code>def foo():
   print "this will be overridden"
def bar():
   print "this will be preserved"
</code>```

module2.py

```<code>from module1 import *
import module1

def foo():
   print "This was foo:"
   module1.foo()
   print "But it was overridden."
</code>```

run.py

```<code>import module2

module2.foo()
module2.bar()
</code>```

Example's result:

```<code>-> % python run.py
This was foo:
this will be overridden
But it was overridden.
this will be preserved
</code>```

Body:
When You import Y module, that imports functions from module X with from X import *, all functions from X are available as they were in Y ( You can thing of that, like pasting content of X into Y ).

And, when you have multiple defs, Python will take the last one. So to override functions You have just to redefine those function after you import X.

Also, when You want to use original function from X in Your Y, you can add aditional import X and access it with X.functionName().

Example:

module1.py

def foo():
   print "this will be overridden"
def bar():
   print "this will be preserved"

module2.py

from module1 import *
import module1

def foo():
   print "This was foo:"
   module1.foo()
   print "But it was overridden."

run.py

import module2

module2.foo()
module2.bar()

Example's result:

-> % python run.py
This was foo:
this will be overridden
But it was overridden.
this will be preserved


问:
In C# Is using private constant strings better than using strings directly in the code?
Consider the following two cases:

case 1:

```<code>class A
{
    private const string MyConst="Hello";

    internal void CallMe()
    {
        System.Console.WriteLine(MyConst);
    }
}
</code>```

Case2:

```<code>class A
{
    internal void CallMe()
    {
        System.Console.WriteLine("Hello");
    }
}
</code>```

Now if the CallMe() method would be called 1000 times, is it a good idea to define it as a constant (which means only one copy of the string per class) or using a plain string would be better. I just checked the MSIL code for both the classes and found that in both cases, .Net compiler is putting the string literal inside WiriteLine(). Then is it an overhead to define the string as a constant?

The main reason I asked this question was because I wanted to understand how CLR works when something is defined as a constant at the class level and when I saw that the MSIL code had const field as well as the string in WriteLine() replaced with the actual string so I was wondering why create constant field  if it will be used in only one method. This is just a sample code I wrote to present my doubt.And from the responses I learnt following:

It's better to use the string directly if it won't be used outside the method

If it's used throughout the class/classes then declare it as constant at the class level

Put it in resex if it needs localization

Thanks all for responses/comments.

答: Case2 is better because the string has no more than the scope it needs and I don't have to chase variables to read your code. Simple. Performance doesn't matter here.</p>


答:
To put it slightly in another direction:

In case of Hello it is nonsense to define a constant and I would go for the second solution. But say you have deoxyribonucleicacid and use it more than once in a class, I would opt for a constant, so you could leverage the IDE / compiler to do your spellchecking. I find that always a nice trick.

Title: In C# Is using private constant strings better than using strings directly in the code?

Body:
Consider the following two cases:

case 1:

```<code>class A
{
    private const string MyConst="Hello";

    internal void CallMe()
    {
        System.Console.WriteLine(MyConst);
    }
}
</code>```

Case2:

```<code>class A
{
    internal void CallMe()
    {
        System.Console.WriteLine("Hello");
    }
}
</code>```

Now if the CallMe() method would be called 1000 times, is it a good idea to define it as a constant (which means only one copy of the string per class) or using a plain string would be better. I just checked the MSIL code for both the classes and found that in both cases, .Net compiler is putting the string literal inside WiriteLine(). Then is it an overhead to define the string as a constant?

The main reason I asked this question was because I wanted to understand how CLR works when something is defined as a constant at the class level and when I saw that the MSIL code had const field as well as the string in WriteLine() replaced with the actual string so I was wondering why create constant field  if it will be used in only one method. This is just a sample code I wrote to present my doubt.And from the responses I learnt following:

It's better to use the string directly if it won't be used outside the method

If it's used throughout the class/classes then declare it as constant at the class level

Put it in resex if it needs localization

Thanks all for responses/comments.


答:
As covered doing this as a performance thing is not sensible. However doing it for code readability is very sensible. In a non trivial bit of code I would use constants to add syntactic meaning to the variable. Fear the magic string.

```<code>class GreetingPrinter
    {
        private const string Greeting = "Hello";

        internal void CallMe()
        {
            Console.WriteLine(Greeting);
        }
    }
</code>```

The c_str prefix makes my eyes break and adds nothing to the readability of the code.

Body:
As covered doing this as a performance thing is not sensible. However doing it for code readability is very sensible. In a non trivial bit of code I would use constants to add syntactic meaning to the variable. Fear the magic string.

class GreetingPrinter
    {
        private const string Greeting = "Hello";

        internal void CallMe()
        {
            Console.WriteLine(Greeting);
        }
    }

The c_str prefix makes my eyes break and adds nothing to the readability of the code.


问:
Delphi vs C# for GUI programming
I'm coming from PHP and Python background with little knowledge of C, I have done many web based application now I'm thinking of Desktop application for windows platform.

A friend told me to go for Delphi and others are saying C# is the best, well, what I'm looking for is

Simplicity

Productivity

Good API documentation

Speed

Drag and Drop

Multi threading & Good Network API

Thanks

答:
Delphi, definitely:

Simplicity - Delphi's syntax is based on Pascal, which was explicitly designed to be easy to learn, and it can deliver on that promise. C#'s is based on the C family, which... well... was not.

Productivity - Delphi is a descendant of Turbo Pascal, and it still has the fastest compiler known to man, which will boost your productivity enormously.  Plus it has the debugger Visual Studio wishes its debugger will be like when it grows up.  Especially in the latest version of Delphi, debugging is much easier.

Good API documentation - "API" is a pretty vague word these days, encompassing all sorts of things.  I assume you mean libraries, and here it's sort of a tossup. Both the .NET framework and the Delphi standard libraries have good online documentation and mediocre, difficult-to-use offline documentation. (A consequence of the Delphi team choosing to use the same horrible help system as Visual Studio, which they will hopefully move away from in the next version.)

Speed - Delphi wins easily.  It compiles to native code (faster execution and much faster startup because there's no JIT phase,) and it doesn't use managed pointers so object access is faster and less cache-unfriendly.

Drag and Drop - A built-in feature of the VCL.

Multi threading - Delphi has a built in thread class, but if you want to do complex things with concurrency there are better options. Primoz Gabrijelcic, a Delphi community member, has been working on an excellent concurrency library that I've helped contribute to.  It provides high-level support for common threading goals such as task pooling, parallel FOR loops and multi-stage pipeline processes.

Good Network API - Delphi ships with Indy, a mature open-source library that makes Internet connections easy to set up and manage.  We use it at work to provide the communications layer for an industry-leading app that you've probably never heard of unless you work in broadcast media.

Deployment - This wasn't on your list, but it's worth mentioning.  There are still systems out there that don't have the .NET framework preinstalled.  By default, Delphi compiles its standard library into the EXE, then uses a smartlinker to remove parts you don't use, resulting in small EXEs that don't have dependencies on massive runtime libraries weighing in at hundreds of MBs that your users will have to download and install separately.

Title: Delphi vs C# for GUI programming


问:
Why is trailing whitespace a big deal?
Trailing whitespace is enough of a problem for programmers that editors like Emacs have special functions that highlight it or get rid of it automatically, and many coding standards require you to eliminate all instances of it. I'm not entirely sure why though. I can think of one practical reason of avoiding unnecessary whitespace, and it is that if people are not careful about avoiding it, then they might change it in between commits, and then we get diffs polluted with seemingly unchanged lines, just because someone removed or added a space.

This already sounds like a pretty good reason to avoid it, but I do want to see if there's more to it than that. So, why is trailing whitespace such a big deal?

答: There are programming languages that are sensitive to end-line whitespace. For example, a TCL script will give an error if there is a whitespace at the end of a line.</p>

Title: Why is trailing whitespace a big deal?


问:
How to track technical tasks with BDD?
I am working on a team that is adopting BDD for the first time. We are doing greenfield work building a market data system that allows users to request market data from different sources.

We are using Mingle (https://www.thoughtworks.com/mingle/) and the BDD card hierarchy that has been set up is: A release consists of one or more iterations and an iteration consists of one or more stories.

A story is expressed in the BDD format of: As a <type of user>, I want <some goal> so that <some reason>

As stated, this is a greenfield project so there is nothing currently in place. From a BDD perspective we have captured end-user system requirements with stories like:

As a user I want yesterday's end-of-day prices available each morning so that I can use them as inputs to my models.

As this is a completely new project this single story requires quite a lot of technical tasks to be completed e.g.:

Build a scheduler

Build a gateway to connect to the external market data source

Get a database to hold the results

etc...

I am entirely unsure how to track these technical tasks against my story in a BDD format.  What am I doing wrong? Are the stories to high level? Is there a level in the release -> iterations -> stories hierarchy missing? Is BDD  not suitable for this and, if not, what are other people doing? Something else?

答:
You are making a mistake by skipping the sprint 0.

In sprint 0, you should preprare everything (architecture, design, build system, frameworks, etc). After you finish sprint 0, you can start delivering buisness value.

Another option is to add some stories in sprint 0, but give it enough time to prepare everything I listed. This way, you deliver some business value.

Just to make it clear, sprint 0 should deliver :

The team needs to be assembled in Sprint Zero

Organization and logistics need to be set up in Sprint Zero

Consider planning, product backlog setup, and design

Title: How to track technical tasks with BDD?


答:
In industry, we solve this problem by:

Reviewing the code before it gets checked in.

Marking code with such problems as defects.

Not allowing it to be checked in until the author either fixes all the defects or successfully defends their design decisions as they stand.

Your colleagues over in English composition work the same way, going through multiple drafts.  Programming languages are just as difficult to write in as English.  I don't know why schools seem to think students can get it right on the first draft.


答:
It's natural for your first few stories to have a lot of overhead, and in the beginning it's even common to have stories that do not amount to a BDD test. You need to set up repositories for your code, configure CI servers, lay out your basic project structure, build files, etc... Some things just take time and don't deliver any business value to your customers, but business value can be some value that is added for you as well. You can pour these into a story too: remember that the role in BDD is not limited to users. A story that reads "as a developer, I want the application to be built nightly" is a valid story!

As your project grows, stories can speed up because you will have the infrastructure. You first story might encompass the need to build a sandbox database with a single script-file you can execute, but all the other stories will benefit from that. This needs to be taken into account if you do estimations, obviously, but there is no need to shy away from doing this.

Remember that you can also start with a more simple story: you could simply have a story where "As a user I want to be able to retrieve a list of end-of-day prices". That eliminates the scheduler and the gateway. Iterate over that so that "As a user I want to be able to update the end-of-day prices with those in the external system" and finally "as a user I want the update to the end-of-day prices to occur automatically every night". The first story gets you the database, the second one gets you the gateway and the third one the scheduler.

Title: How to track technical tasks with BDD?

Body:
I am working on a team that is adopting BDD for the first time. We are doing greenfield work building a market data system that allows users to request market data from different sources.

We are using Mingle (https://www.thoughtworks.com/mingle/) and the BDD card hierarchy that has been set up is: A release consists of one or more iterations and an iteration consists of one or more stories.

A story is expressed in the BDD format of: As a <type of user>, I want <some goal> so that <some reason>

As stated, this is a greenfield project so there is nothing currently in place. From a BDD perspective we have captured end-user system requirements with stories like:

As a user I want yesterday's end-of-day prices available each morning so that I can use them as inputs to my models.

As this is a completely new project this single story requires quite a lot of technical tasks to be completed e.g.:

Build a scheduler

Build a gateway to connect to the external market data source

Get a database to hold the results

etc...

I am entirely unsure how to track these technical tasks against my story in a BDD format.  What am I doing wrong? Are the stories to high level? Is there a level in the release -> iterations -> stories hierarchy missing? Is BDD  not suitable for this and, if not, what are other people doing? Something else?


问:
How to decouple SELF as a special word within Rebol objects?
Rebol has no keywords. It's a concept that forms a part of what makes the language so versatile—any word can be reassigned, any word can be assigned the value of a 'built-in' function—and one that in the general flow of the language holds true*. However there are notable exceptions within two of Rebol's basic structural datatypes that break that rule:

return within a function, and

self within an object.

There has been some discussion in the Rebol and Red chat room as to possible ways to build functions and objects where these words are not predetermined, my question alludes to my best understanding of that discussion: Is there an approach to removing the special qualities of these words that'd work while retaining the characteristics of each type? Take for instance:

```<code>document: make object! [
    title: none
    rename: function [title][self/title: title]
]

essay: make document []
essay/rename "My Document"
</code>```

In the above example, we might wish to replace self with this-document:

```<code>document: object/self [
    title: none
    rename: function [title][this-document/title: title]
] 'this-document
</code>```

How would this propagate to derivative objects without requiring a special word to keep tabs?

```<code>essay: make document [probe this-document]
essay/rename "My Document"
</code>```

What would be the best way to express this word? The above, or something like:

```<code>document: object [self: 'this-document][
    title: "Untitled"
    rename: function [title][this-document/title: title]
]
</code>```

Using a two-argument approach to creating objects opens the possibility that we could add more qualities to an object: type-checking certain fields, hidden or protected fields—but all of this would somehow have to be tracked within the base object structure as well.

* Dialects within Rebol—such as parse—do contain keywords, but the parse dialect is not processed by the Rebol evaluator, it's its own sub-language.

答:
Is there an approach to removing the special qualities of these words that'd work while retaining the characteristics of each type?

Well, what are those characteristics?  For SELF:

Points to the object instance so it can self-reflect.

Cannot be overwritten by your own code.

Automatically present without you having to ask for it.

Is not inherited as-is, but is updated to reflect a new object.

Doesn't show up when you use words-of or mold.

Point (1) is technically possible, but due to point (2) you can't use the name self for a custom SELF (unless a decoupling happened and the word were opened up for user use).  You can get it with binding:

```<code>document: make object! [
    x-self: bind? 'x-self
    name: "Document"
    rename: func [new-name] [
        x-self/name: new-name
    ]
]

>> document/rename "This changed name will print"
print document/name
</code>```

A user-made "self" like x-self can get some of (2) with PROTECT, but today's SELF appears immune to UNPROTECT:

```<code>>> test make object! [unprotect 'self self: 10]
** Script error: cannot set/unset self - it is protected
</code>```

User values can't do that, so if it were considered desirable there'd have to be something that made protects permanent.

For (3)'s automatic-ness, you can move the self-like thing into a generator.  So going with the theory that SELF is no longer special and we call that generator OBJECT (as today's generator):

```<code>object: func [body [block!]] [
    make object! compose [
       self: bind? 'self
       (body)
    ]
]
</code>```

How would this propagate to derivative objects without requiring a special word to keep tabs?

So this is (4).  If someone doesn't use the OBJECT generator, what keeps the SELF convention going in inheritance steps?  One answer is to just use another generator, e.g. an INHERIT that coordinates:

```<code>inherit: func [parent [object!] body [block!]] [
    make parent compose [
        self: bind? 'self
        (body)
    ]
]
</code>```

A better idea would likely be to reuse the OBJECT generator if it had a way of acting like INHERIT based on another cue.  Some keyword in the spec or body indicating the parent, so it could do the inheritance in that case.

Note: In order for these to work, something about SELF must allow it to be overwritten from the base class in spite of (2).

As for being able to hide the SELF in user-space in (5), the only way that can be achieved today is with PROTECT/HIDE.  But HIDE as currently implemented doesn't just block it from view in enumerations, but also from new bindings.  So that suggests another shade of meaning to protect to discern between whether something is not shown vs. not bindable.

This further raises the question about persistence across serializations.  If you mold an object out, and SELF is invisible, when you LOAD it back it wouldn't have one.  On the other hand, it were visible and it was a reference to an object, you're dealing with serializing object references in text.  Because it's a reference to the object being serialized it could be done specially in mold syntax vs. an arbitrary object reference, but then it becomes special again.

TL;DR - In the case of SELF behavior being relegated to generators, serialization and deserialization is probably the hardest point--e.g. how to make it work where the generator is not in the picture.  Yet it may be that needing a SELF at all is not so different from needing PARENT, where all the same problems would show up.  So I wouldn't let that kill the idea, it's worth thinking about.

(As for RETURN...same basic issues, except people don't try to mold functions as a method of serialization...usually.)

Body:
Is there an approach to removing the special qualities of these words that'd work while retaining the characteristics of each type?

Well, what are those characteristics?  For SELF:

Points to the object instance so it can self-reflect.

Cannot be overwritten by your own code.

Automatically present without you having to ask for it.

Is not inherited as-is, but is updated to reflect a new object.

Doesn't show up when you use words-of or mold.

Point (1) is technically possible, but due to point (2) you can't use the name self for a custom SELF (unless a decoupling happened and the word were opened up for user use).  You can get it with binding:

document: make object! [
    x-self: bind? 'x-self
    name: "Document"
    rename: func [new-name] [
        x-self/name: new-name
    ]
]

>> document/rename "This changed name will print"
print document/name

A user-made "self" like x-self can get some of (2) with PROTECT, but today's SELF appears immune to UNPROTECT:

>> test make object! [unprotect 'self self: 10]
** Script error: cannot set/unset self - it is protected

User values can't do that, so if it were considered desirable there'd have to be something that made protects permanent.

For (3)'s automatic-ness, you can move the self-like thing into a generator.  So going with the theory that SELF is no longer special and we call that generator OBJECT (as today's generator):

object: func [body [block!]] [
    make object! compose [
       self: bind? 'self
       (body)
    ]
]

How would this propagate to derivative objects without requiring a special word to keep tabs?

So this is (4).  If someone doesn't use the OBJECT generator, what keeps the SELF convention going in inheritance steps?  One answer is to just use another generator, e.g. an INHERIT that coordinates:

inherit: func [parent [object!] body [block!]] [
    make parent compose [
        self: bind? 'self
        (body)
    ]
]

A better idea would likely be to reuse the OBJECT generator if it had a way of acting like INHERIT based on another cue.  Some keyword in the spec or body indicating the parent, so it could do the inheritance in that case.

Note: In order for these to work, something about SELF must allow it to be overwritten from the base class in spite of (2).

As for being able to hide the SELF in user-space in (5), the only way that can be achieved today is with PROTECT/HIDE.  But HIDE as currently implemented doesn't just block it from view in enumerations, but also from new bindings.  So that suggests another shade of meaning to protect to discern between whether something is not shown vs. not bindable.

This further raises the question about persistence across serializations.  If you mold an object out, and SELF is invisible, when you LOAD it back it wouldn't have one.  On the other hand, it were visible and it was a reference to an object, you're dealing with serializing object references in text.  Because it's a reference to the object being serialized it could be done specially in mold syntax vs. an arbitrary object reference, but then it becomes special again.

TL;DR - In the case of SELF behavior being relegated to generators, serialization and deserialization is probably the hardest point--e.g. how to make it work where the generator is not in the picture.  Yet it may be that needing a SELF at all is not so different from needing PARENT, where all the same problems would show up.  So I wouldn't let that kill the idea, it's worth thinking about.

(As for RETURN...same basic issues, except people don't try to mold functions as a method of serialization...usually.)


答:
What is the point of modules?

Modules are a mechanism to structure an application into distinct, reusable parts. E.g. a command line utility could factor out the code that does the argument parsing into a separate module that can then be used in other command line tools as well. Since a module has a clear public interface and can hide implementation details within the module, the overall application also becomes less tightly coupled.

Can I swap out a module for another module with the same interface?

Not necessarily, and that is not the point of modules. However, there are various techniques to implement modules. One is to define a structure of function pointers that defines the type of the whole module. When a module is loaded, it provides an instance of this module. This technique is frequently used to mimic modules in JavaScript:

// a mathModule may be anything that supplies "add" and "sub" functions
var mathModule = (function () {
  var privateVar = "secret";
  function add(a, b) { return a + b; }
  function sub(a, b) { return a - b; }
  function privateFunction() { return "very" + privateVar; }

  // return an “object” (Python: dict) that defines the public interface
  return {
    add: add,
    sub: sub,
  };
})();
```

<p>This technique can also be adapted to C to provide real modules, and can be easily translated to Python. However, neither language has lambdas and C lacks closures, so the translated example would be more restricted.</p>

<p>Since we are dealing with function pointers here, we have an important level of indirection. In principle, we could have multiple instances of the same module interface at once, and we can easily switch to a different implementation if it offers the same interface.</p>

<p>This sounds very much like object-oriented programming, but a few important details are missing: for OOP, the instance structure must also contain data in addition to methods, and must pass the instance structure as an argument back into any method that was invoked. I discuss creating a JavaScript object system out of closures in a blog post in more depth.</p>

<p><strong>Do Python's modules work like this?</strong></p>

<p>Kind of. In fact, Python's modules act very much like a regular object except that we don't have a <code>self</code> argument. However, Python misses the part where we actually define a clear interface for our module. Where the above JavaScript example can explicitly choose whether to expose a function through the public interface, Python makes any symbol in file scope accessible when <code>import</code>ing a module. There are tricks that limit this issue (such as defining functions in helper modules and then selectively importing the public interface into the module's <code>__init__.py</code>), but in Python we end up defining the interface through our documentation, not through the code. </p>

<p>So, long story short, Python has namespaces that it calls “modules”, but don't offer any encapsulation.</p>

<p><strong>So, how can I inherit a module?</strong></p>

<p>The concept of “inheritance” makes no sense when discussing modules, as it's more of an OOP term. There, “<code>Subclass</code> inherits from <code>Base</code>” means (a) that <code>Subclass</code> is a subtype of <code>Base</code> and (b) that <code>Subclass</code> instances can somehow use the implementation defined by <code>Base</code>. As you might know, reusing the implementation can be done via two mechanisms: implementation inheritance (where the method lookup mechanism for <code>Subclass</code> is initialized with the methods for <code>Base</code>) and composition (where <code>Subclass</code> delegates to a <code>Base</code> instance).</p>

<p>With the module-as-dict encoding, this can be illustrated as such:</p>

```# The original module.
# Can be instantiated like `mathModule = mathModule_load()`
def mathModule_load():
  private_var = "secret"
  def add(a, b): return a + b
  def sub(a, b): return a - b
  def private_function(): return "very" + private_var

  return {
    'add': add,
    'sub': sub,
  }

# Inherit the mathModule via composition
# Overrides "add" to type-check for int arguments
def checkedMathModule_load():
  base = mathModule_load() # the module instance we inherit

  def add(a, b):
    if type(a) is not int or type(b) is not int:
      raise TypeError("give me ints!")
    return base['add'](a, b)

  def sub(a, b):
    return base['sub'](a, b)

  # return our own module instance that meets the expected interface
  return {
    'add': add,
    'sub': sub,
  }

# Inherit the mathModule by changing the module definition
# Overrides "add" to emit debug info
def chattyMathModule_load():
  module = mathModule_load() # the module instance we inherit

  original_add = module['add']
  def my_add(a, b):
    print("DEBUG: add(%d, %d)" % (a, b))
    return original_add(a, b)
  module['add'] = my_add

  return module
```

<p><strong>OK, can we now do that with built-in modules?</strong></p>

<p><em>*grumble*</em> Python may formally be multi-paradigm, but it very clearly favours OOP solutions to problems like this. We can rework the above example to use Python's built-in modules, but it isn't pretty. Note that Python's modules don't have a comparable concept of “instances”, as modules are global.</p>

<p>Instead of the explicit <code>dict</code> that stores the function of the module, we will use regular Python syntax to add symbols to the file scope.</p>

<p>The modules are organized in the following file hierarchy:</p>

```mathModule/
  __init__.py
  detail.py
checkedMathModule/
  __init__.py
  detail.py
chattyMathModule/
  __init__.py
  detail.py
```

<p><code>mathModule/__init__.py</code>:</p>

```from .detail import add, sub
del detail
```

<p><code>mathModule/detail.py</code>:</p>

```private_var = "secret"

def add(a, b):
  return a + b

def sub(a, b):
  return a - b

def private_function():
  return "very" + private_var
```

<p><code>checkedMathModule/__init__.py</code>:</p>

```# this module offers the same interface as mathModule
from .detail import add, sub
del detail
```

<p><code>checkedMathModule/detail.py</code>:</p>

```import mathModule as base

def add(a, b):
  if type(a) is not int or type(b) is not int:
    raise TypeError("give me ints!")
  return base.add(a, b)

def sub(a, b):
  return base.sub(a, b)
```

<p><code>chattyMathModule/__init__.py</code>:</p>

```from mathModule import *

# now import the function we want to override
from .detail import my_add as add
del detail
```

<p><code>chattyMathModule/detail.py</code>:</p>

```from mathModule import add as original_add

def my_add(a, b):
  print("DEBUG: add(%d, %d)" % (a, b))
  return original_add(a, b)
```

I am not sure that the del detail won't break anything, but without it users could do mathModule.detail.private_function() and get something 'verysecret', which completely breaks encapsulation.

These techniques kind of work, but are a lot of unnecessary effort for something that could be done much more easy with regular objects. Also, Python is special because modules are represented as module objects that can be passed around as values, whereas the module system of most languages is far more static. These techniques are not representative of modular programming, but rather of a “I want to do OOP without using the OOP parts of my language” mindset that is not constructive for anything except understanding OOP better.

Title: How to achieve inheritance when using just modules and vanilla functions in Python?

Body:
Python doesn't enforce any paradigm. It gives you freedom.
Python provides encapsulation at module level.

If I have a module A and have a module B with same interface. How do I sort of inherit B from A and override some functionality provided by B ?

Body:
What is the point of modules?

Modules are a mechanism to structure an application into distinct, reusable parts. E.g. a command line utility could factor out the code that does the argument parsing into a separate module that can then be used in other command line tools as well. Since a module has a clear public interface and can hide implementation details within the module, the overall application also becomes less tightly coupled.

Can I swap out a module for another module with the same interface?

Not necessarily, and that is not the point of modules. However, there are various techniques to implement modules. One is to define a structure of function pointers that defines the type of the whole module. When a module is loaded, it provides an instance of this module. This technique is frequently used to mimic modules in JavaScript:

// a mathModule may be anything that supplies "add" and "sub" functions
var mathModule = (function () {
  var privateVar = "secret";
  function add(a, b) { return a + b; }
  function sub(a, b) { return a - b; }
  function privateFunction() { return "very" + privateVar; }

  // return an “object” (Python: dict) that defines the public interface
  return {
    add: add,
    sub: sub,
  };
})();

This technique can also be adapted to C to provide real modules, and can be easily translated to Python. However, neither language has lambdas and C lacks closures, so the translated example would be more restricted.

Since we are dealing with function pointers here, we have an important level of indirection. In principle, we could have multiple instances of the same module interface at once, and we can easily switch to a different implementation if it offers the same interface.

This sounds very much like object-oriented programming, but a few important details are missing: for OOP, the instance structure must also contain data in addition to methods, and must pass the instance structure as an argument back into any method that was invoked. I discuss creating a JavaScript object system out of closures in a blog post in more depth.

Do Python's modules work like this?

Kind of. In fact, Python's modules act very much like a regular object except that we don't have a self argument. However, Python misses the part where we actually define a clear interface for our module. Where the above JavaScript example can explicitly choose whether to expose a function through the public interface, Python makes any symbol in file scope accessible when importing a module. There are tricks that limit this issue (such as defining functions in helper modules and then selectively importing the public interface into the module's __init__.py), but in Python we end up defining the interface through our documentation, not through the code.

So, long story short, Python has namespaces that it calls “modules”, but don't offer any encapsulation.

So, how can I inherit a module?

The concept of “inheritance” makes no sense when discussing modules, as it's more of an OOP term. There, “Subclass inherits from Base” means (a) that Subclass is a subtype of Base and (b) that Subclass instances can somehow use the implementation defined by Base. As you might know, reusing the implementation can be done via two mechanisms: implementation inheritance (where the method lookup mechanism for Subclass is initialized with the methods for Base) and composition (where Subclass delegates to a Base instance).

With the module-as-dict encoding, this can be illustrated as such:

# The original module.
# Can be instantiated like `mathModule = mathModule_load()`
def mathModule_load():
  private_var = "secret"
  def add(a, b): return a + b
  def sub(a, b): return a - b
  def private_function(): return "very" + private_var

  return {
    'add': add,
    'sub': sub,
  }

# Inherit the mathModule via composition
# Overrides "add" to type-check for int arguments
def checkedMathModule_load():
  base = mathModule_load() # the module instance we inherit

  def add(a, b):
    if type(a) is not int or type(b) is not int:
      raise TypeError("give me ints!")
    return base['add'](a, b)

  def sub(a, b):
    return base['sub'](a, b)

  # return our own module instance that meets the expected interface
  return {
    'add': add,
    'sub': sub,
  }

# Inherit the mathModule by changing the module definition
# Overrides "add" to emit debug info
def chattyMathModule_load():
  module = mathModule_load() # the module instance we inherit

  original_add = module['add']
  def my_add(a, b):
    print("DEBUG: add(%d, %d)" % (a, b))
    return original_add(a, b)
  module['add'] = my_add

  return module

OK, can we now do that with built-in modules?

*grumble* Python may formally be multi-paradigm, but it very clearly favours OOP solutions to problems like this. We can rework the above example to use Python's built-in modules, but it isn't pretty. Note that Python's modules don't have a comparable concept of “instances”, as modules are global.

Instead of the explicit dict that stores the function of the module, we will use regular Python syntax to add symbols to the file scope.

The modules are organized in the following file hierarchy:

mathModule/
  __init__.py
  detail.py
checkedMathModule/
  __init__.py
  detail.py
chattyMathModule/
  __init__.py
  detail.py

mathModule/__init__.py:

from .detail import add, sub
del detail

mathModule/detail.py:

private_var = "secret"

def add(a, b):
  return a + b

def sub(a, b):
  return a - b

def private_function():
  return "very" + private_var

checkedMathModule/__init__.py:

# this module offers the same interface as mathModule
from .detail import add, sub
del detail

checkedMathModule/detail.py:

import mathModule as base

def add(a, b):
  if type(a) is not int or type(b) is not int:
    raise TypeError("give me ints!")
  return base.add(a, b)

def sub(a, b):
  return base.sub(a, b)

chattyMathModule/__init__.py:

from mathModule import *

# now import the function we want to override
from .detail import my_add as add
del detail

chattyMathModule/detail.py:

from mathModule import add as original_add

def my_add(a, b):
  print("DEBUG: add(%d, %d)" % (a, b))
  return original_add(a, b)

I am not sure that the del detail won't break anything, but without it users could do mathModule.detail.private_function() and get something 'verysecret', which completely breaks encapsulation.

These techniques kind of work, but are a lot of unnecessary effort for something that could be done much more easy with regular objects. Also, Python is special because modules are represented as module objects that can be passed around as values, whereas the module system of most languages is far more static. These techniques are not representative of modular programming, but rather of a “I want to do OOP without using the OOP parts of my language” mindset that is not constructive for anything except understanding OOP better.


问:
How to structure a SaaS application?

The Problem

I need to develop a Software-as-a-Service application, that will be used from our clients. The application contains a lot of forms (Company Application) using a step-by-step forms. They users will fill these forms, and see some progress.

The Company (our client), can have a view of they dashboard, showing they users, products and other informations, including company information and some customizations.

One thing that I'm trying to solve, it's: I need a subdomain for each of my client, and each User in Company, need to have a subdomain in Company.

For example, using the first approach (above), for example, what I'll have:
API: .myapp.com/api/v1
Client Base Page (rendered by my application): .com (CNAME to somewhere)
User Base Page (rendered by my application): ..com (CNAME to somewhere)

The things I can't figure how to do are:

It's better to develop a REST API, use the standards for that, and create a separate Front-end application (using Angular, Ember or other frameworks). Then I deploy the API, get the link, and setup it on my Angular application. This is a good approach?

Develop a Standard Application, where the same application connects to database and render the views, where the logic will be on Models and Controllers.

Other approach? (I think using microservices in this stage, will be cumbersome.

Based on that approaches, I've some questions.

In 1st case:

I think the best way for the API is to use a subdomain based on my startup domain, like: .mycompany.com/api/. This way, I can buy a wildcard SSL and secure the endpoint of each client. But what I see in applications like Stripe, it's using single endpoint, like: api.stripe.com with an EV SSL. So, both approaches are good and secure?

What it's a good approach to render the Front-end? Based on fact that on the front-end will be wildcard subdomains for each user.

So, what it's a good way to develop that?

Background

I'm using Rails 4, and Postgres (for multi-tenancy database), and if needed, I can develop using Angular.js or "static views".

答:
For my current project I had similar requirements like you. I have decided to use a backend server exposing a REST API. And for the cleints I am using a nginx server, which handles the subdomains and hosting the AngularJS Application.

The server side checks which subdomain the client is using and sends the correct data to the client.

In my opinion the advantage of this approach is, that the communication could be easily encrypted with SSL (see Stripe).

Microsoft gives good information about SAAS architecture in following article: https://msdn.microsoft.com/en-us/library/aa479069.aspx

Title: How to structure a SaaS application?


答:
I don't have experience with mixed IDEs, unless you count a commercial IDE with occasional supplementing by a text editor "multiple IDEs," but I can think of a couple pros and cons.

Pros

Each developer can be most productive with what they know best

Some IDEs may provide an advantage over others (one might be better at refactoring, another might be better at providing coding aids, others might be better with data integration, whatever). Using a blend might allow your team to capitalize on that.

You'll have a bit of a hedge against the possibility that one of the IDEs goes defunct.

Cons

Licensing issues. If there are multiple commercial IDEs involved, maybe it's more expensive. At the least, it could be more to keep track of.

Licensing issues 2. If there are frameworks or plug-ins that are licensed by IDE or langauge, will this be a problem?

As Dszordan mentioned, certain plug ins may not be compatible with the different IDEs.

If the IDEs have code generation components or style formatting engines that do things differently, this might cause some confusion.

Title: Should every member of a team use the same IDE?

Body:
Do you think it makes sense to enforce that every member of a team must use the same IDE?

For instance all engineers that are already on the team use IDE X. Two new engineers come and want to use IDE Y instead because that's what they have been using for several years now.

Do you have any experience with "mixed IDE" teams? If so what is it?


问:
Best practise for databinding when a non-data object is included with the data
I'm using .NET with Windows Forms, but I believe there may be similar concerns with other toolkits.

Suppose we have a list of objects of a certain type. Using an example to make the following easier to read, suppose there is a Category class to represent them. We display a list of them to allow a user to filter articles by category. Binding the ListBox component to a data source of Category objects is a way to do so.

What would be the best way to add an entry labelled "All" in the same ListBox? Assume that it has to be in the list, and not as a separate option like a radio button.

I can think of the following approaches, but all of them seem to have a drawback.

Create a "dummy" Category instance named "All" and an invalid ID.

This is the easiest way but it feels wrong conceptually, as "All" is not actually a category (no article belongs to a category named that). Also, depending on the framework the UI may not be allowed to create Category objects.

Don't use data binding at all; populate the list box with strings and use the selection's index to get the object from the data source.

This may beat the point of having data bound controls, and adds potential problems: What if we also want to add a "None" entry in the future? We'll have to increment the list box's selected index by 2 instead of 1 to get the correct object from the data source.

Use an intermediate class, CategoryListItem, to populate the list box with. It has a reference/pointer to a Category which is null for dummy entries.

This one may be more elegant, but it adds the overhead of creating a new list of CategoryListItem instances for every list of Category instances we want to display.

Is one of the above a recommended way to data bind to such a component, or perhaps a way I haven't thought of?

答:
Normally, a single-selection listbox offers a list-of-values interface for setting up, and a single-value interface for querying its state. You give it a list of values to present, and it tells you which one of them is selected. (Regardless of whether it is always-open or drop-down.) It is the same as a group-of-radio buttons: only one of the radio buttons may have a bullet in it at any given time.

What you want instead, is a control which again offers a list-of-values interface for setting up, but a set-of-values interface for querying its state. The range of possible values is again fixed, but you may select as many of them as you want, including none of them, or all of them. So, clearly, this control is backed by a Set data type. The kind of control which is normally used for that sort of thing is a group of checkboxes, or a listbox with checkmarks, or, in the old days, a multi-selection listbox.  (That was before they realized that users can't be bothered with holding down the Ctrl key while clicking with the mouse.)

Now, for some reason you have decided to use a regular listbox for this job, which means that you do not care to give your user the ability to select two categories at the same time, all you want them to be able to do is select either one category, or all categories. (And perhaps no categories in the future.)  That's fine, as long as you realize that this choice of yours should only affect the appearance and the user experience that the control offers to the user, it should not affect the interfaces that the control provides to your application. From your application's point of view, this control should still implement a list-of-values interface for setting up, and a set-of-values interface for querying its value.  The question of whether it will contain a checkbox next to each choice, or special "select all" and "select none" entries, should be of absolutely no concern to your application.  It should be possible for you to replace it in the future with a group of checkboxes, without altering the way your application interacts with it.

So, what I would do if I was in your shoes is that I would sublcass the existing listbox control, (or I would create an entirely new control which aggregates the existing control, I do not remember right now which approach is recommended in WinForms,) to create a new multi-selection-listbox control which looks like a list, but offers a set-of-values interface for querying its value.

I would have the new control add to itself the one or two extra pseudo-items needed so that it can easily select all of its contents, or none of its contents.  That would most closely correspond to option #1 above, but it is irrelevant, because this approach is a lot more than doing option #1.  Note how, when describing this control, we are now talking about "items" and not "categories": this is a general purpose control which can be used for anything you can think of besides categories: reusable, and also replaceable with something better if the need arises in the future.

The point behind my recommendation is to avoid ruining your application logic with fine-grained user interaction considerations.  Keep things separate, and let the user experience be the sole responsibility of the GUI controls themselves. Let it be their problem. GUI controls should abstract the way they work behind nice, clean, and minimalistic interfaces that correspond to simple abstract data types, and the application logic should only have to interact with these abstract data type interfaces.


答:
You seem to be confusing the concept of a business model with a view model. If the Category class is used as a business model, then an "All" entry makes no sense. However, if you are databinding them directly to the UI, then what you have is actually a view model. An "All" entry makes perfect sense here, because a view model simply models the data you want to get onto the screen, regardless of what it might be.

Your options 1, 2 and 3 are all attempts to make a distinction between these two types of model. As for the best one to pick, well, that depends on how you want to architect the rest of your application. Personally, I would make it explicit, and have two classes, e.g.

Models.Category - the underlying business data

ViewModels.Category - the business data plus an "All" line

Your presentation code is then responsible for translating back and forth between the two classes. Your view code only knows about ViewModels.Category, and your repository/back-end code only knows about Models.Category.

Title: Best practise for databinding when a non-data object is included with the data

Body:
I'm using .NET with Windows Forms, but I believe there may be similar concerns with other toolkits.

Suppose we have a list of objects of a certain type. Using an example to make the following easier to read, suppose there is a Category class to represent them. We display a list of them to allow a user to filter articles by category. Binding the ListBox component to a data source of Category objects is a way to do so.

What would be the best way to add an entry labelled "All" in the same ListBox? Assume that it has to be in the list, and not as a separate option like a radio button.

I can think of the following approaches, but all of them seem to have a drawback.

Create a "dummy" Category instance named "All" and an invalid ID.

This is the easiest way but it feels wrong conceptually, as "All" is not actually a category (no article belongs to a category named that). Also, depending on the framework the UI may not be allowed to create Category objects.

Don't use data binding at all; populate the list box with strings and use the selection's index to get the object from the data source.

This may beat the point of having data bound controls, and adds potential problems: What if we also want to add a "None" entry in the future? We'll have to increment the list box's selected index by 2 instead of 1 to get the correct object from the data source.

Use an intermediate class, CategoryListItem, to populate the list box with. It has a reference/pointer to a Category which is null for dummy entries.

This one may be more elegant, but it adds the overhead of creating a new list of CategoryListItem instances for every list of Category instances we want to display.

Is one of the above a recommended way to data bind to such a component, or perhaps a way I haven't thought of?


答: Provided the 'official' build system (as used by the Continuous Build servers) is the same for all, I don't see any reason why each member of the team could not choose the tools he wants...</p>


答:
Surprisingly, the most obvious answer is missing: trailing whitespace can and will produce difficult to find bugs.

The most obvious situation is multiline strings. Python, JavaScript and Bash are few examples of the languages which can be affected by this:

```<code>print("Hello\·
····World")
</code>```

produces:

```<code>  File "demo.py", line 1
    print("Hello\
                 ^
SyntaxError: EOL while scanning string literal
</code>```

which is somehow cryptic and difficult to solve if the editor is not configured to display whitespace characters.

While syntax highlight can help avoiding such cases, it's even easier to not having the issue in the first place by not letting whitespace at the end of the lines. This is why some style checkers will raise a warning when encountering trailing whitespace, and some editors will trim them automatically.

Illustration: syntax highlight can help avoiding trailing whitespace in situations where it can lead to bugs, but don't rely just on it.

Another context, briefly mentioned in a previous answer, is data stored in files.

For instance, CSV files which contain trailing whitespace may cause data inconsistency which is also very difficult to detect: standards-compliant parsers will trim the whitespace (the standard indicates that leading or trailing whitespace is irrelevant, unless delimited with double-quotes), but some parsers may misbehave and keep the whitespace as a part of a value.

Other custom formats may specifically consider that whitespace is the part of the value, leading to consistent but still difficult to debug situations.

Title: Why is trailing whitespace a big deal?

Body:
Trailing whitespace is enough of a problem for programmers that editors like Emacs have special functions that highlight it or get rid of it automatically, and many coding standards require you to eliminate all instances of it. I'm not entirely sure why though. I can think of one practical reason of avoiding unnecessary whitespace, and it is that if people are not careful about avoiding it, then they might change it in between commits, and then we get diffs polluted with seemingly unchanged lines, just because someone removed or added a space.

This already sounds like a pretty good reason to avoid it, but I do want to see if there's more to it than that. So, why is trailing whitespace such a big deal?

Body:
Surprisingly, the most obvious answer is missing: trailing whitespace can and will produce difficult to find bugs.

The most obvious situation is multiline strings. Python, JavaScript and Bash are few examples of the languages which can be affected by this:

print("Hello\·
····World")

produces:

  File "demo.py", line 1
    print("Hello\
                 ^
SyntaxError: EOL while scanning string literal

which is somehow cryptic and difficult to solve if the editor is not configured to display whitespace characters.

While syntax highlight can help avoiding such cases, it's even easier to not having the issue in the first place by not letting whitespace at the end of the lines. This is why some style checkers will raise a warning when encountering trailing whitespace, and some editors will trim them automatically.

Illustration: syntax highlight can help avoiding trailing whitespace in situations where it can lead to bugs, but don't rely just on it.

Another context, briefly mentioned in a previous answer, is data stored in files.

For instance, CSV files which contain trailing whitespace may cause data inconsistency which is also very difficult to detect: standards-compliant parsers will trim the whitespace (the standard indicates that leading or trailing whitespace is irrelevant, unless delimited with double-quotes), but some parsers may misbehave and keep the whitespace as a part of a value.

Other custom formats may specifically consider that whitespace is the part of the value, leading to consistent but still difficult to debug situations.


问:
UML class diagram notations: Differences between Association, Aggregation and Composition
I'm confused about some of the notations of UML class diagrams.

Pretty sure I know what Association means. Any relationship between instances of two classes, where an instance of one class needs to know about an instance of the second class in order to perform it's work - is an Association relationship. An Association often means class A has a reference (field) to an instance of class B.

However, I'm having trouble understanding what the Aggregation and Composition arrows mean. Part of my confusion was caused by encountering different definitions of these notations.

Two definitions of the Aggregation notation:

Definition 1: An Aggregation notation between two classes is suitable whenever an instance of class A holds a collection of instances of class B (e.g. a List, Array, whatever).

Definition 2: An Aggregation link between two classes is suitable if an instance of class A holds a reference to an instance of class B, and the B instance is dependent on the lifecycle of the A instance. Meaning: When the instance of class A get's deleted, so will the instance of class B. The instance of class B is entirely contained by the instance of class A, as opposed to the instance of class A simply owning a reference to the instance of class B (which is regular Association).

Regarding what the Composition notation means and how it differs from the Aggregation notation, I'm not sure.

Please clarify the definitions and help me understand. Concrete examples would be welcome.

答:
In addition an excerpt of the current UML standard:

11.5.4 Associations – Semantics – Notation

[...] A binary Association may have one end with aggregation = AggregationKind::shared or aggregation = AggregationKind::composite. When one end has aggregation = AggregationKind::shared a hollow diamond is added as a terminal adornment at the end of the Association line opposite the end marked  with aggregation = AggregationKind::shared. The diamond shall be  noticeably smaller than the diamond notation for Associations. An Association with aggregation = AggregationKind::composite likewise has
a diamond at the corresponding end, but differs in having the diamond
filled in. […]

9.5.4 Classification – Properties – Notation

[…] Sometimes a Property is used to model circumstances in which one instance is used to group together a set of instances; this is called aggregation. To represent such circumstances, a Property has an aggregation property, of type AggregationKind; the instance representing the whole group is classified by the owner of the Property, and the instances representing the grouped individuals are classified by the type of the Property. AggregationKind is an enumeration with the following literal values:

none: Indicates that the Property has no aggregation semantics.

Shared: Indicates that the Property has shared aggregation semantics. Precise  semantics of shared aggregation varies by application area and modeler.

Composite: Indicates that the Property is aggregated compositely, i.e., the composite object has responsibility for the  existence and storage of the composed objects (see the definition of parts in 11.2.3). Composite aggregation is a strong form of  aggregation that requires a part object be included in at most one composite object at a time. If a composite object is deleted, all of its part instances that are objects are deleted with it.

[…]


问:
Change routing to comply with Law of Demeter
I have a Task, Owner and Plan. Charge values are kept in a plan, owner is on a particular plan and task knows its owner.

A task needs to setup its charges based on the knowledge the owner has. Owner however needs to consult a plan to get those done. According to the Law of Demeter I am not allowed to do:

```<code>class Task {

    /**
     * @var Owner
     */
    private $owner;

    public function prepareCharges() {
        $plan = $this->owner->getPlan();
        $plan->chargeFor(...);
    }
</code>```

So I am wondering if this sort of routing trick is a viable solution.

```<code>class Task {

    /**
     * @var Owner
     */
    private $owner;

    public function prepareCharges() {
        $this->owner->helpMeDoTheCharges($this);
    }

    public function doPlanCharges(Plan $plan) {
        $distanceCharge = new Money();
        $plan->chargeFor('distance', $distanceCharge);

        $fixedCharge = new Money();
        $plan->chargeFor('fixed', $fixedCharge);
    }

}
</code>```

Task basically tells its owner to push the plan to it so it can send it messages.

```<code>class Plan {

    public function chargeFor($type, Money $money) {

    }

}

class Owner {

    private $plan;

    public function helpTaskDoTheCharges(Task $task) {
        $task->doPlanCharges($this->plan);
    }

}
</code>```

答:
I would suggest that you do something like the following:

```<code>class Task {
   public function prepareCharges() {
      $charges = new Charges();
      $distanceCharge = new Money();
      $charges->add('distance', $distanceCharge);

      $fixedCharge = new Money();
      $charges->add('fixed', $fixedCharge);

      $this->owner->charge($charges);
   }
}

class Owner {
   public function charge(Charges $charges) {
       $this->plan->charge($charges);
   }
}
</code>```

Basically, instead of trying to awkwardly induce a situation where you have references to all those objects, put all of the charges inside a value object and pass it the owner.

The intention of the Law of Demeter is to minimize the knowledge that one part of your system has about another. Task shouldn't know about Plan. Your approach of having Owner call back into Task with a Plan may the follow the letter of the Law of Demeter, but it results in Task having in-depth knowledge of Owner, precisely what Demeter is trying to avoid. You'd be better off returning the plan because that code was easier to follow.

Body:
I would suggest that you do something like the following:

class Task {
   public function prepareCharges() {
      $charges = new Charges();
      $distanceCharge = new Money();
      $charges->add('distance', $distanceCharge);

      $fixedCharge = new Money();
      $charges->add('fixed', $fixedCharge);

      $this->owner->charge($charges);
   }
}

class Owner {
   public function charge(Charges $charges) {
       $this->plan->charge($charges);
   }
}

Basically, instead of trying to awkwardly induce a situation where you have references to all those objects, put all of the charges inside a value object and pass it the owner.

The intention of the Law of Demeter is to minimize the knowledge that one part of your system has about another. Task shouldn't know about Plan. Your approach of having Owner call back into Task with a Plan may the follow the letter of the Law of Demeter, but it results in Task having in-depth knowledge of Owner, precisely what Demeter is trying to avoid. You'd be better off returning the plan because that code was easier to follow.


答:
Usually you'd just use a layer of indirection...</p>

```<code>class Task {

    private $owner;

    public function prepareCharges() {
        $this->owner->chargeFor(...);
    }
...

class Owner {
    public chargeFor() {
        $plan = $this->getPlan();
        $plan.chargeFor(...)
        ...
</code>```

Title: Change routing to comply with Law of Demeter

Body:
I have a Task, Owner and Plan. Charge values are kept in a plan, owner is on a particular plan and task knows its owner.

A task needs to setup its charges based on the knowledge the owner has. Owner however needs to consult a plan to get those done. According to the Law of Demeter I am not allowed to do:

```<code>class Task {

    /**
     * @var Owner
     */
    private $owner;

    public function prepareCharges() {
        $plan = $this->owner->getPlan();
        $plan->chargeFor(...);
    }
</code>```

So I am wondering if this sort of routing trick is a viable solution.

```<code>class Task {

    /**
     * @var Owner
     */
    private $owner;

    public function prepareCharges() {
        $this->owner->helpMeDoTheCharges($this);
    }

    public function doPlanCharges(Plan $plan) {
        $distanceCharge = new Money();
        $plan->chargeFor('distance', $distanceCharge);

        $fixedCharge = new Money();
        $plan->chargeFor('fixed', $fixedCharge);
    }

}
</code>```

Task basically tells its owner to push the plan to it so it can send it messages.

```<code>class Plan {

    public function chargeFor($type, Money $money) {

    }

}

class Owner {

    private $plan;

    public function helpTaskDoTheCharges(Task $task) {
        $task->doPlanCharges($this->plan);
    }

}
</code>```

Body:
Usually you'd just use a layer of indirection...

class Task {

    private $owner;

    public function prepareCharges() {
        $this->owner->chargeFor(...);
    }
...

class Owner {
    public chargeFor() {
        $plan = $this->getPlan();
        $plan.chargeFor(...)
        ...


答:
Composition is when an object A contains object B and the object A is also responsible for creating the object B.

Composition relationship

We have a class A which will be used by class B.

```<code>final class A
{
}
</code>```

There are multiple options as how the composition may look.

Direct initialization composition:

```<code>final class B
{
    private $a = new A();
}
</code>```

Constructor initialization composition

```<code>final class B
{
    private $a;

    public function __construct()
    {
        $this->a = new A();
    }
}
</code>```

Lazy initialization composition

```<code>final class B
{
    private $a = null;

    public function useA()
    {
        if ($this->a === null) {
            $this->a = new A();
        }

        /* Use $this->a */
    }
}
</code>```

You see this creates a tight relationship between the classes A and B. Class B simply cannot exists without A. This is a huge violation of dependency injection principle, which says:

A dependency is an object that can be used (a service). An injection
  is the passing of a dependency to a dependent object (a client) that
  would use it. The service is made part of the client's state.
  Passing the service to the client, rather than allowing a client to
  build or find the service, is the fundamental requirement of the
  pattern.

Composition sometimes makes sense, such as calling new DateTime in php or new std::vector<int> in C++. But more often than not, it is a warning, that your code design is wrong.

In a case, where the class A would be a special object used to caching, the class B would always be cached using the implementation of class A, and you would have no control to dynamically change it, which is bad.

Also, if you used the lazy initialization composition, meaning you would have a working object B, called the useA() method and the creation of object A would fail, your object B is suddenly useless.

Aggregation, on the other hand, is a way of relationship, which follows the DI principle. object B needs to use object A, then you should pass already created instance of object A to object B, and should the creation of object A fail, nothing would be passed in the first place.

In short, Aggregation is UML representation for dependency injection principle, be it constructor injection, setter injection or public property injection.

These are all Aggregations

The tightest, constructor injection (object B cannot exists without object A).

```<code>final class B
{
    private $a;

    public function __construct(A $a)
    {
        $this->a = $a;
    }
}
</code>```

Looser (you may or may not use object A inside object B, but if you do, you should probably set it first).

Via setter:

```<code>final class B
{
    private $a;

    public function setA(A $a)
    {
        $this->a = $a;
    }
}
</code>```

Via public property:

```<code>final class B
{
    public $a;
}
</code>```

There isn't really a great way to justify the usage of Aggregation over Composition, if all you are using are concrete implementations of classes, but once you start injecting interfaces or in case of C++ abstract classes, suddenly Aggregation will be the only way to fulfill your contract.

Title: UML class diagram notations: Differences between Association, Aggregation and Composition

Body:
I'm confused about some of the notations of UML class diagrams.

Pretty sure I know what Association means. Any relationship between instances of two classes, where an instance of one class needs to know about an instance of the second class in order to perform it's work - is an Association relationship. An Association often means class A has a reference (field) to an instance of class B.

However, I'm having trouble understanding what the Aggregation and Composition arrows mean. Part of my confusion was caused by encountering different definitions of these notations.

Two definitions of the Aggregation notation:

Definition 1: An Aggregation notation between two classes is suitable whenever an instance of class A holds a collection of instances of class B (e.g. a List, Array, whatever).

Definition 2: An Aggregation link between two classes is suitable if an instance of class A holds a reference to an instance of class B, and the B instance is dependent on the lifecycle of the A instance. Meaning: When the instance of class A get's deleted, so will the instance of class B. The instance of class B is entirely contained by the instance of class A, as opposed to the instance of class A simply owning a reference to the instance of class B (which is regular Association).

Regarding what the Composition notation means and how it differs from the Aggregation notation, I'm not sure.

Please clarify the definitions and help me understand. Concrete examples would be welcome.

Body:
Composition is when an object A contains object B and the object A is also responsible for creating the object B.

Composition relationship

We have a class A which will be used by class B.

final class A
{
}

There are multiple options as how the composition may look.

Direct initialization composition:

final class B
{
    private $a = new A();
}

Constructor initialization composition

final class B
{
    private $a;

    public function __construct()
    {
        $this->a = new A();
    }
}

Lazy initialization composition

final class B
{
    private $a = null;

    public function useA()
    {
        if ($this->a === null) {
            $this->a = new A();
        }

        /* Use $this->a */
    }
}

You see this creates a tight relationship between the classes A and B. Class B simply cannot exists without A. This is a huge violation of dependency injection principle, which says:

A dependency is an object that can be used (a service). An injection
  is the passing of a dependency to a dependent object (a client) that
  would use it. The service is made part of the client's state.
  Passing the service to the client, rather than allowing a client to
  build or find the service, is the fundamental requirement of the
  pattern.

Composition sometimes makes sense, such as calling new DateTime in php or new std::vector<int> in C++. But more often than not, it is a warning, that your code design is wrong.

In a case, where the class A would be a special object used to caching, the class B would always be cached using the implementation of class A, and you would have no control to dynamically change it, which is bad.

Also, if you used the lazy initialization composition, meaning you would have a working object B, called the useA() method and the creation of object A would fail, your object B is suddenly useless.

Aggregation, on the other hand, is a way of relationship, which follows the DI principle. object B needs to use object A, then you should pass already created instance of object A to object B, and should the creation of object A fail, nothing would be passed in the first place.

In short, Aggregation is UML representation for dependency injection principle, be it constructor injection, setter injection or public property injection.

These are all Aggregations

The tightest, constructor injection (object B cannot exists without object A).

final class B
{
    private $a;

    public function __construct(A $a)
    {
        $this->a = $a;
    }
}

Looser (you may or may not use object A inside object B, but if you do, you should probably set it first).

Via setter:

final class B
{
    private $a;

    public function setA(A $a)
    {
        $this->a = $a;
    }
}

Via public property:

final class B
{
    public $a;
}

There isn't really a great way to justify the usage of Aggregation over Composition, if all you are using are concrete implementations of classes, but once you start injecting interfaces or in case of C++ abstract classes, suddenly Aggregation will be the only way to fulfill your contract.


问:
How should I handle the fetching of cached data in iOS
I'm developing an app at work, this is my first big application and in my smaller projects I didn't use caching at all.

What's currently happening

When the user logs on for their very first time they have to pull in all of the news article data, their website account information and a few other things. Once I have the data I cache it.

When the user navigates to a screen where the data is required, I attempt to fetch and parse it into a Model Class Object before I attempt to display. But as you may have guessed the fetching / parsing process is too slow and my TableViewController is empty.

What I've Tried

I've tried using a completion handler to fetch the data but the TableViewController is still empty on load. I feel like the data needs to be parsed and ready for the TableViewController. But I'm not sure where / what the best practice is for doing this.

Options I'm considering

I've thought about trying to parse immediately after I download it so that I'm fetching ready-made objects at run-time.

I've considered fetching all cashed data and parsing them when the application first loads and storing them all in AppDelegate at the class level (probably not the best idea).

I'm not really sure what my other options are, I guess that's why I'm here.

My Question

How should I handle the fetching of cached data in iOS?

答:
If you have one set of data that you need to access in multiple places, I would recommend using a singleton.

Create a model for the data, download the data from the backend, parse it and store it in the singleton to access later on from where ever it needs to be. It makes no sense to waste all that time parsing multiple times.

The issue with the tableview is a separate issue. No matter what strategy you choose, accessing a lot of data will take time. If it takes too long you simply need to implement a loading screen of some sort. Even place a semi transparent UIView over your screen with an activity indicator spinning.

Once the data has been retrieved, dismiss the loading screen and reload the tableview. This is a standard approach to take. Pausing the UI or expecting all the data to have 0 access time are not reasonable assumptions / actions to take.


答:
I largely agree with Froome's answer and would do something similar in most cases, but I think there are some other things to consider:

For values that only exist in the current method, don't pull the out into a field without thinking. Keep data close to where it used and extract things when it's needed to prevent duplication. the Single Responsibility Principle tells us to keep things together that change for the same reason and to separate things that change for different reasons. This makes it easier to extract behaviors from this class into new classes as the complexity of your system grows.

To me it all depends on what kind of string "Hello" is. If it's a greeting to be output to a user in a GUI it should be pulled out into an external resource. If it's some default value returned by the method used by other methods inside the class, I'd say leave it in the method until you find a compelling reason to move it out of there.

In short, don't assume too much before you know how the value will be used. See where your design takes you and constantly evaluate if you're going in the right direction.

EDIT:

Another thought, if we consider the Open/Closed principle something like this might be appropriate:

```<code>public class A
{
    internal void CallMe()
    {
        Console.Out.WriteLine(GetGreeting());
    }

    protected virtual string GetGreeting()
    {
        return "Hello";
    }
}
</code>```

This allows the behavior to be changed by extending the class but keeping this version closed for modifications.

Again, whether or not this is the way to go depends on what type of system you are building and how it will be used/changed in the future.

Body:
I largely agree with Froome's answer and would do something similar in most cases, but I think there are some other things to consider:

For values that only exist in the current method, don't pull the out into a field without thinking. Keep data close to where it used and extract things when it's needed to prevent duplication. the Single Responsibility Principle tells us to keep things together that change for the same reason and to separate things that change for different reasons. This makes it easier to extract behaviors from this class into new classes as the complexity of your system grows.

To me it all depends on what kind of string "Hello" is. If it's a greeting to be output to a user in a GUI it should be pulled out into an external resource. If it's some default value returned by the method used by other methods inside the class, I'd say leave it in the method until you find a compelling reason to move it out of there.

In short, don't assume too much before you know how the value will be used. See where your design takes you and constantly evaluate if you're going in the right direction.

EDIT:

Another thought, if we consider the Open/Closed principle something like this might be appropriate:

public class A
{
    internal void CallMe()
    {
        Console.Out.WriteLine(GetGreeting());
    }

    protected virtual string GetGreeting()
    {
        return "Hello";
    }
}

This allows the behavior to be changed by extending the class but keeping this version closed for modifications.

Again, whether or not this is the way to go depends on what type of system you are building and how it will be used/changed in the future.


问:
The present and future of programming in local languages
Can programming become language-independent? Will we always program in English? Will we ever be able to program in our local languages? Is there any research that addresses the matter? Are there any such developments?</p>

答:
Answer to philosophical part of your question:

You think and you program in abstract categories and ideas, neither in English, nor in Java or C++. All those are just mediators. English, as Jas mentioined is his answer, is a the most convenient because most programmers speak or understand it.

Answer to technical part of your question:

Classic compiler consists of language-specific frontend, language-agnostic optimizer, and hardware-specific backend. Once you create a consistent and efficient natural language frontend (say, for GCC), the compiler will be able to generate the code. The neuance is, once such parser is developed, programmers won't be needed any longer. Only managers (to manage computers). But the complexity of natural language recognition domain is so high that I hope the problem won't be solved any time soon.


问:
Best possible way to comment?
My question is simple, how should I comment during development so that it can be beneficial in the following cases:

Understandable for my seniors while code reviewing.

Should be able to search my work after sometime.

Can be made in pseudo code form.

Should be able to help juniors or other developers when they work on it.

Any real world examples will highly be appreciated.

PS: I am not debating whether we should write comments or not.

答:
In general, you should not comment. Instead, you should strive to write simple, straight-forward, consistent, readable code. Comments invariably get out of date. If your code is good, they are a duplication of effort at best, and add noise to the signal at worst.

But that is not always possible, since we are human and stuff happens. In cases where you do your best, but there is a good reason that the code cannot be simple, straight-forward, or consistent, then add a brief comment there explaining why it isn't.

"Doing things this way, because of a potential race condition between X and Y."

"Cannot do this the normal way because of limitations of XYZ library."

"This code was ugly when I got here, leaving as is for now."

Title: Best possible way to comment?