问:
What principle of OOAD is this pattern breaking?
I'm trying to make a case for not putting the structure in the parent BaseModule class I've shown below.  I'm more for a Strategy Pattern, and minimizing inheritance in favor of has-a relationships, but I am not really sure of what principle of OOAD this pattern is breaking.

What principle of OOAD is this pattern breaking?

Potential Pattern:

```<code>public interface IStringRenderer
{
    string Render();
}

public class BaseModel : IRequestor
{
    public abstract void  Init();
    public abstract void Load();
}

public class BaseModule<TModel> : IStringRenderer where TModel : BaseModel
{
    public TModel Model { get; set; }

    public override string Render()
    {
        return
        string.Join(
            "",
            new string[]
            {
                "<header/>",
                "<main-container>",
                    "<side-nav>",
                        "<side-navigation/>",
                    "</side-nav>",
                    "<main-content>",
                        RenderMainContent(),
                    "</main-content>"
            });
    }

    public abstract string RenderMainContent();
}

public class MyModuleModel : BaseModel
{
    public List<int> Ints { get; set; }

            ...
}

public class MyModule : BaseModule<MyModuleModel>
{
    public override string RenderMainContent()
    {
        return
        string.Join(",", Model.Ints.Select(s => s.ToString()).ToArray());
    }
}
</code>```

Preferred Pattern (duplicated some code to be clear):

```<code>public interface IStringRenderer
{
    string Render();
}

public class BaseModel : IRequestor
{
    public abstract void Init();
    public abstract void Load();
}

public class MyModuleModel : BaseModel
{
    public List<int> Ints { get; set; }

    ...
}

public class MyModule : IStringRenderer
{
    public MyModuleModel Model { get; set; }

    public MyModule(MyModuleModel model)
    {
        this.Model = model;
    }

    public override string Render()
    {
        return
        string.Join(
            "",
            new string[]
            {
                "<header/>",
                "<main-container>",
                    "<side-nav>",
                        "<side-navigation/>",
                    "</side-nav>",
                    "<main-content>",
                        RenderMainContent(),
                    "</main-content>"
            });
    }

    public string RenderMainContent()
    {
        return
        string.Join(",", Model.Ints.Select(s => s.ToString()).ToArray());
    }
}
</code>```

There are parts of this pattern that I'm not trying to focus on, but instead I am thinking about where the 'structure', or the 'tags' are living.  In the first example they live in the parent, but in the second example they have been pushed into the derived class.

Right now, the examples are pretty simple, but something like 'side-nav' could potentially get complicated, and may need to be controlled by the child anyway.

I feel the principle here is that I don't feel like the 'tag' structure shouldn't be in the parent class as in the first example.  There are other things I've removed in my 'preferred version' -- namely the generics.  (Any suggested reading on good/bad for that choice is welcome).  Proponents of the first example's embedded structure like the fact that they can wield changes to large amounts of child classes.  I feel offering the flexibility to derived classes is the way to go, and if there needs to be a parent that parent only offers functionality and cross-cutting features, but does not bottle up canned structure.

答:
Overview

It sounds similar to CommonClosurePrinciple, but happens on a class-and-methods level instead of a package-and-classes level. Namely,

--Classes-- (methods) within a released --component-- (a class) should share common closure. If one (method) needs to be changed, they all (methods) are likely to need to be changed. What affects one, affects all.

(I added the words in brackets.)

Also, the principle that can be gleaned from this code example is a weak one, meaning that it is not universally applicable. There are obviously cases where changes don't / shouldn't need to be concentrated into a single class!

In this particular question, the validity of this principle depends on whether the (1) HTML tags and (2) the model-to-string code are typically changed together when there is a change in model.

The Code

In both versions, MyModule is the place for the glue logic that exists between Model and IStringRenderer.Render().

In the first version, the HTML tags (...</>) is a service provided by BaseModule.

If the same wrapping code is reused many times for many different models, this is a correct choice.

If each model ended up having to customize its HTML tags, then the BaseModule class in the first version will only get used once.

In the second version, both pieces of glue logic are contained in the leaf class (MyModule):

The conversion of integers (model) to a string, and

The HTML tags

Thus, the second version allow the model rendering and the HTML wrapping code to be changed together.

Opinion:

If it occurs to you that each model require different HTML tags, then I'd say that the first version is not sufficient, while the second version is. Otherwise, both versions are fine.

If one must look for a name for the principle, it would be along the line of "... methods that need to be changed together for the same reason (changing the model), would be nice to be placed into the same class."

(I emphasize "would be nice" because it is a weak principle, or, a rule-of-thumb and not a true principle.)

It sounds similar to CommonClosurePrinciple, but applied to a class-and-methods level instead of a package-and-classes level.

Body:
Overview

It sounds similar to CommonClosurePrinciple, but happens on a class-and-methods level instead of a package-and-classes level. Namely,

--Classes-- (methods) within a released --component-- (a class) should share common closure. If one (method) needs to be changed, they all (methods) are likely to need to be changed. What affects one, affects all.

(I added the words in brackets.)

Also, the principle that can be gleaned from this code example is a weak one, meaning that it is not universally applicable. There are obviously cases where changes don't / shouldn't need to be concentrated into a single class!

In this particular question, the validity of this principle depends on whether the (1) HTML tags and (2) the model-to-string code are typically changed together when there is a change in model.

The Code

In both versions, MyModule is the place for the glue logic that exists between Model and IStringRenderer.Render().

In the first version, the HTML tags (<main-content>...</>) is a service provided by BaseModule.

If the same wrapping code is reused many times for many different models, this is a correct choice.

If each model ended up having to customize its HTML tags, then the BaseModule class in the first version will only get used once.

In the second version, both pieces of glue logic are contained in the leaf class (MyModule):

The conversion of integers (model) to a string, and

The HTML tags

Thus, the second version allow the model rendering and the HTML wrapping code to be changed together.

Opinion:

If it occurs to you that each model require different HTML tags, then I'd say that the first version is not sufficient, while the second version is. Otherwise, both versions are fine.

If one must look for a name for the principle, it would be along the line of "... methods that need to be changed together for the same reason (changing the model), would be nice to be placed into the same class."

(I emphasize "would be nice" because it is a weak principle, or, a rule-of-thumb and not a true principle.)

It sounds similar to CommonClosurePrinciple, but applied to a class-and-methods level instead of a package-and-classes level.


问:
How do purely functional languages handle modularity?
I come from an object oriented background where I've learned that classes are or at least can be used to make a layer of abstraction that allows for easy recycling of code which can then either be used to make objects or be used in inheritance.

Like for example I can have an animal class and then from that inherit cats and dogs and such that all inherit many of the same traits, and from those sub-classes I can then make objects that can specify a breed of animal or even the name of it.

Or I can use classes to specify multiple instances of the same code that handles or contains slightly different things; like nodes in a search-tree or multiple different database connections and what not.

I'm recently moving into functional programming, so I was starting to wonder:

How do purely functional languages handle things like that? That is, languages without any concept of classes and objects.

答:
Many functional languages have a module system. (Many object-oriented languages do too, by the way.) But even in the absence of one, you can use functions as modules.

JavaScript is a good example. In JavaScript, functions are used both to implement modules and even object-oriented encapsulation. In Scheme, which was the major inspiration for JavaScript, there are only functions. Functions are used to implement almost everything: objects, modules (called units in Racket), even data structures.

OTOH, Haskell and the ML family have an explicit module system.

Object Orientation is about data abstraction. That's it. Modularity, Inheritance, Polymorphism, even mutable state are orthogonal concerns.

ContentLicense: CC BY-SA 3.0


问:
Could I have a real-world example of using the Spring scripting module in your Java application?
The Spring framework supports the use of scripting languages (specifically JRuby, Groovy and BeanShell) whereby a script in any of these can call Java code and vice versa.

I have read that a possible use of this feature is when some modules require frequent changes and it would allow to modify your application without having to redeploy it. I have been trying to visualize a possible usage but this sounds too vague to me. I tend to associate things that can change with configuration, data or rolling a new feature in an application, but not with an existing module whose behavior can change frequently.

In summary: when did you benefit from using Spring scripting or at least what would be a realistic, concrete example?

答:
Not a real world example (from my own experience anyway) and I don't use Spring but I think a place where I would consider using something like this.

Think you have some kind of shop software and want a function to calculate shipping costs. Those can depend on quite a lot of factors: free shipping above some order value, national shipping, international shipping, different kinds of faster processing etc, size of order (especially if you are a retailer and shipping may include whole trucks or containers).

You can't fully express those with data, but it's simple enough that the guys in the orders department could handle it themselves instead of asking a developer and having to wait for the next version (or at least the developer can drop in the change without going through the whole QA process required for a full update)

You could come up with a lot of rules that can be expressed with rather simple code in areas that may change very frequently with any kind of new contract made.


问:
Are you allowed to "copy" the GUI/Features of another application
I'm making a app which is based heavily on another application that serves a similar purpose. I'm not actually planning on selling it, but I'm wondering whether it would even be legal for me to sell it.

I don't borrow graphics from the other application, but I have a very similar color scheme, virtually the same features (I added a few, but not really significant), and a very similar interface layout. Obviously, I'm not borrowing any code (It's written in Objective-C and mines written in Java).

Again, I'm not actually planning on selling it, I was just wondering in the hypothetical. I'm not sure whether it's just the code that's copyrighted or the actually design itself.

答:
As usual: IANAL, but I'd say that...

Yes: you can copy UI elements and color-schemes

Elements of UI Design are NOT Generally Viewed as IP

While You can patent functionalities and behaviors, you cannot patent or copyright or trademark a design, except if it's the design of a brand or logo for a registered trademark. Similarly, you can't copyright a color charter: it's too generic.

However, you can patent GUI-related functionalities, unfortunately, because the patent system is clueless (in the US and some other countries). e.g., double-clicking, swiping, and things like that...

In the case of a complete clone, as far as I know (which isn't much, let's make that clear again), this could be ground for legal issues. Meaning if you'd have copied the screen's content, mode of navigation AND color schemes, some people would find it legitimate to sue you. Doesn't mean they would succeed, but that could a risk. They'd be unlikely to succeed as they can't own the IP for the design, and you'd have re-implemented it entirely.

For additional confirmation and what it's worth:

OnStartups answer on "is it legal to copy a user interface?"

"Why the look and Feel of Software User Interfaces Should not be Protected by Copyright Law" by Pamela Samuelson

Counter Point

However, note that there's literature covering the other hangle as well, such as the "Appendix L - What Can You Borrow" to "Task-Centered User Interface Design":

Things you can probably not copy -- again, watch the news and check with your attorney.

Sequences or arrangements of menu items, commands, screens, etc., if you're only copying the sequence order because it will make it easier for users of someone else's existing program to use your new program.

Icons, commands, menu items, or other words that are not an obvious choice to describe their function, even if they would make your program more usable for users of the original program. An example might be a database print command labelled "DataDump," or a mouse-options icon showing a cute little mouse with a checklist.

Things you can certainly not copy (unless you get permission).

Things you've written earlier for a different company.

An entire interface from another company's program, even if you implement it with all new code.

An entire detailed screen from another company's program.
  [...]

Trademarks from other companies. If you need to use someone else's trademark, such as "Unix" in documentation, be sure you credit the owner: "Unix is a trademark of Unix Systems Laboratories, Inc."

Patented features. Unfortunately, there's no easy way to discover what's patented.

Exact bitmaps of icons, words, or fonts.

Graphic details that define an interface's aesthetic look.

Note that:

this leaves room for interpretation,

this isn't legal advice either.

Bottom Line? Get a Lawyer... or Don't Copy!!!


问:
Software design vs physical products design
I got a bunch of questions to answer to prepare for an exam and this one I'm actually not sure what's the clear difference :

"Explain the difference between designing software and designing physical products"

I have an opinion on this, but the more I think about it the more it feels like there's no real difference except that the tools and formula's used when making physical items has been established hundreds of years ago and the heuristics/models have been in place since forever.

I also thought that, once you design a spoon and make it, it doesn't evolve with time, it fulfills it's requirements and that's that, while for software new requirements come in all the time so you have to consider certain quality attributes in that regard.

This is from my software architecture class if you guys need a context.

What are the differences between software design and physical design, and am I off the mark with my answer?

答:
No real difference? The differences are enormous.

The main aspect is that software has essentially no manufacturing costs to it. The marginal cost of software production is quite nearly nothing, with virtually all the cost going to by design work.

When designing physical process, a lot of your design constraints are dominated by difficulties in actually producing your design. The process of taking a design and planning out how to actually manufacture it is an engineering discipline all by itself, and the costs of manufacturing can often exceed design costs. And because physical devices have to exist in the real world, and be constructed out of real materials, differences in design can result in greatly increased manufactured costs. If you can design your part to be made from stamped sheet metal instead of requiring a machinist to mill it, you can slice the cost per part from several dollars to a few cents.

When you are making copies of software, it is trivial to make copies. You want to fill your hard drive with several billion copies of some software? No problem, and each one will be a perfect copy. But you want to make a billion copies of a physical good? That isn't so easy, even if you have the material laying around. Every single one of those produced parts is going to be slightly different.

In the realm of physical products, there are no exact dimensions, everything has tolerances, everything has elements of variability that must be accounted for. If you are making a software product, you can test your software, and then you can copy it as many times as you want. When we make physical products, we not only have to test some design-representative parts to verify our design, but we have to test each and every single device that rolls off the factory floor.

When you buy a car, something like 1/4 of the cost of the car is represented by the cost to actually produce the raw materials of the car, and the rest is the cost of producing the tooling. If an automobile maker could remove a single screw from an engine design, they would save enough in manufacturing costs that they could pay two engineers for an entire year just to do that.

A cheap injection mold for plastic parts can cost $50,000. Imagine how much different software development would be if it cost $50 grand every time you hit F5 in your IDE to try and run your software.

Read more in From Craft to Science


问:
Is it worthwhile to create a knowledge map for software?
Basically, the objective is to create a visual representation of the software specification document. This visual representation would capture various scenarios involved in the software.

Benefits:

Picture speaks louder than words

Catch scenarios so that they need to be handled by the developer

Becomes a knowledge map for others

Can be used as a reference

Can be used for knowledge transfer as well.

Ideas:

If possible, we can dynamically modify the visual representation to add scenarios when
site issues are found and they were not identified initially.

I do not know how to do this. But I would like to invest time to find out how to do this.
But is it worth the effort?

答:
We ordinary use Google drawings or alike to chart rather complex structures -

like this one can collaborate in-sync ... and things get way more obvious.

This is pretty much the same like so called "paper tests" were once.

Sometimes it might be even required to revision the chart while the implementation,

just because things not always work out as imagined - this is like a visual documentation.

Also, when added new developers to a project, it's more easy for them to understand.

Sometimes I chart things with "Connected Mind", especially when I'm on the train.

Sorry, I'm not allowed to show off anything :)


问:
How would I make a compiler in C++?
This probably been asked for but I can't google "How to make a  compiler in C++" because I will just get "How to compile C++" as the results. Anyway, for my question, I'd like to make a simple programming language in C++. Now I understand basic file IO stuff but what I don't get is how to build a EXE. The problem here is I don't know how EXEs exactly are "planned out", granted that most people don't. I was going to simply parse the language into assembly and assemble it using an assembler. But I don't want to do that, I want to actually compile it directly into a EXE. Does anyone know how  this would be done? PS: To all you people who say making a compiler is virtually impossible, it's a fairly fast process, it's just implementing OOP features that's hard</p>

答:
I think you're asking the wrong question:

How you make I compiler in C++?

As in with any other language, actually. You'll need to write something that takes an input (likely from files) and compiles this input into something that's machine-readable and follows a specific format (in your case, C++).

So your question isn't correct and relevant. The questions you should be asking are:

What are the specifications for an executable (.exe) file on the Windows platform?

Look into the specs of the PE format. More details available here:

Microsoft PE and COFF Specification

An In-Depth Look at the PE File Format

How to write a compiler for C++ in C++?

That is, of course, assuming that you want to compile c++ files, but I'm just guessing here as you don't clearly state what you want to compile...

And from the way you formulate your answer, you already know how to do that, though you raise points about the OO model.

Please clarify your question if you need more.

Title: How would I make a compiler in C++?


问:
Is test coverage an adequate measure of code quality?
If I have some code that has 80% test coverage (all tests pass), is it fair to say that it's of higher quality than code with no test coverage?

Or is it fair to say it's more maintainable?

答:
By one definition it's more maintainable, as any breaking change is more likely to be caught by the tests.

However, the fact that code passes the unit tests doesn't mean it's intrinsically of higher quality. The code might still be badly formatted with irrelevant comments and inappropriate data structures, but it can still pass the tests.

I know which code I'd prefer to maintain and extend.

ContentLicense: CC BY-SA 2.5


问:
What are non-programming mistakes that a programmer should avoid?
People make mistakes, even in the real life... Which should we, geeky programmers, avoid?</p>

答:
Geeky programmers and developers should avoid saying what they really think about project managers, QA testers, DBAs, and other non-programmers to their face.

In essence, be nice.


问:
How do I convince my company to contribute towards Open-Source?
I'm trying to convince the company I work for to contribute towards open-source software, specifically building a library/component for ASP.NET web apps. We have an 'Innovation Day' coming up where we can work on our own personal pet projects at work, similar to Google's one day a week policy, except ours is once a month :-), and I have an idea that I want to open-source.

Other companies do this, eg. Headspring Systems (http://automapper.codeplex.com - see banner at top).

What do I tell them? What benefits can I convey to them that would be beneficial to the company? I've already mentioned possible exposure for our company and reputation etc. as well as attracting top software developers when we next go on a hiring spree. But what other arguments could I make?

Update: The company I work for is a software company that mainly builds web applications in ASP.NET and the MS Stack. Our clients are mainly the NHS (public health sector of the UK).

答:
Well one of the biggest arguments for open source is that others can contribute to it, idea being that one programmer can't possibly hope to spot and fix 1000 bugs in his program but 1000 programmers can.  So in addition to all the benefits you've listed, it's clearly the choice for developing bootstrap software which helps your own business in some fashion.

It also puts you in a position of authority.  I might be stretching it a bit, but if your idea is innovative enough, you could create a new standard by which others must meet.  It means anyone who wants to do anything with your software for commercial use has to ask you first, meaning you could throw in a couple curve balls which say that while the code is open, usage of your standard for commercial use requires a small contribution which is not at all unreasonable, so it's got potential in later stages as well.


问:
Is copy & paste programming bad?
With plain Google as well as Google Code search tools it is easy to find how to program using some resource or solve certain problems (such as create a Java class, or an FTP block in Perl, etc.). So developers are tempted to just purely copy & paste the code (in a way re-use). Is this an incompetency? I have done this myself, though I think I am a better programmer than many others I have seen. Who has the time to RTFM? In this age of information abundance, I do not think that copy & paste programming is bad.

Isn't that what sites like Stack Overflow do anyway? People ask - OK, here is my problem - how to solve it? Now someone will post complete code and the person who asked the question would simply copy & paste the most voted answer. No matter how small the problem is.

I am working with a bunch of young coders who heavily rely on the Internet to get their job done. I see convenience in copy/pasting and modifying code to get the job done. For example, you may be quite good with algorithms and such, but you may not know how to use a BufferedReader in Java - would you read complete the Javadoc for BufferedReader or look up some example of using it somewhere?

What are the real dangers of copy & paste coding that can impact their competency?

答:
By copy-pasting code, I would assume that it is a code snippet that get copied/pasted. Code snippets are mostly for demonstration of the idea or the algorithm, not for real production because it might not align to your context. Worse than that, it might contain bug because the author of code snippet might have never tested the code itself at all.

Real life example? Yes there are plenty and I ran into one like last year. My colleague was trying to do Base64 encode/decode in iOS, and he got this answer

https://stackoverflow.com/a/3411653/397807

which I later found out that it got a nasty bug here:

```<code>char *outputBuffer = malloc(outLength);
outputBuffer[outLength] = 0;
</code>```

Well, if you know C well, you might be able to spot the error. The author just malloc the buffer short by 1 (yet he still managed to get 8 votes..). My colleague just naively use this code for Base64 and it worked fine most of the time. This cause tremendous headache to all the team as we were very beginners of iOS development and the app just got crash out of nowhere. Everyone checks their code again and again, including myself, but we never found what was going wrong. Until one day, I think the bug decide itself that it should show up. The app crash itself in the simulator and I got some hint from stack trace that it's there. I spotted the bug, fixed it and case closed. That was after a lot of complaints from end users that our app always crashed for no reason. The damage has been done.

So where's the merit of the story, you ask? The merit is that the coder is responsible for any code submitting to the codebase, and one bad coder can cause wasted hours for the whole team. Copy-pasting the code is not a bad idea per se, but many programmers just blindly believe what internet says and put the code there without validating it and without understanding what it really does. When bugs show up, the very last thing they would think is the bug is in their pasted code because they always think internet codes better than himself. If you got many programmers colleague doing copy-pasta code most of the time, then be warned.

Title: Is copy & paste programming bad?

Body:
By copy-pasting code, I would assume that it is a code snippet that get copied/pasted. Code snippets are mostly for demonstration of the idea or the algorithm, not for real production because it might not align to your context. Worse than that, it might contain bug because the author of code snippet might have never tested the code itself at all.

Real life example? Yes there are plenty and I ran into one like last year. My colleague was trying to do Base64 encode/decode in iOS, and he got this answer

https://stackoverflow.com/a/3411653/397807

which I later found out that it got a nasty bug here:

char *outputBuffer = malloc(outLength);
outputBuffer[outLength] = 0;

Well, if you know C well, you might be able to spot the error. The author just malloc the buffer short by 1 (yet he still managed to get 8 votes..). My colleague just naively use this code for Base64 and it worked fine most of the time. This cause tremendous headache to all the team as we were very beginners of iOS development and the app just got crash out of nowhere. Everyone checks their code again and again, including myself, but we never found what was going wrong. Until one day, I think the bug decide itself that it should show up. The app crash itself in the simulator and I got some hint from stack trace that it's there. I spotted the bug, fixed it and case closed. That was after a lot of complaints from end users that our app always crashed for no reason. The damage has been done.

So where's the merit of the story, you ask? The merit is that the coder is responsible for any code submitting to the codebase, and one bad coder can cause wasted hours for the whole team. Copy-pasting the code is not a bad idea per se, but many programmers just blindly believe what internet says and put the code there without validating it and without understanding what it really does. When bugs show up, the very last thing they would think is the bug is in their pasted code because they always think internet codes better than himself. If you got many programmers colleague doing copy-pasta code most of the time, then be warned.


问:
Better server to client communication mechanism over HTTP
I have a single server with several clients. I want to push messages to a particular client at a given time. Clients should not polling to the server. what are good patterns and practices to solve this problem?</p>

Body:
You can use a technique often referred to long-polling or comet, which allows to implement a "push"-based event/update system.

Principle

The principle is rather simple:

client sends a request to server and keeps connections alive;

server keeps a handle on the connection and waits;

when updates are available, server sends back data to client;

(depending on client-side tech) client may need to send a new request.

This way the clients don't poll regularly. However, that implies that a significant number of connections might be kept alive at any single given time, so make sure you understand
the implications of this approach for your server.

How to Implement It?

So, the underlying principle remains the same no matter what your platform is: as long as you can send an HTTP request and wait for the response synchronously or asynchronously, you have a way to implement long-polling.

Heavy Clients

With most programming languages aimed at developing desktop solutions (or "heavy" clients), you'd usually resort to your usual network tools: sockets.

Lightweight/Rich Clients

If we're talking about a rich web-client to build in a browser-based solution, you have the option to:

use your usual XMLHttpRequest object (the server will only reply once it's got something to send back, at which point the client will either re-initiate another connection or use a spare one if it opened multiple ones to ensure there's always multiple channels opened at hand),

or to use <script> tags that query a URL sending back a payload wrapped in a call to function defined in the client's context (see JSONP),

or to use WebSocket API introduced with HTML5,

or a variation of the above or using an external tool (Java Applet, Flash, etc...) to achieve the same effect.

Beware that, as is often the case with web techs, cross-browser support is going to require extensive testing, and you may be forced to use a combination of the above techniques if you target hostile browser market shares...

ContentLicense: CC BY-SA 4.0


问:
Equating multiple new variables with an old one
Sometimes I run into a situation where I need to equate two new variables with an old one. Which of the following (if any) is a good practice (w.r.t. code readability or any other factor), under what conditions?

```<code>a=b;
c=b;
</code>```

or

```<code>a=b;
c=a;
</code>```

Note, a,b and c are just the names chosen in this example.

答:
Humans are Parsers Too! Encourage Maximum Readability!

Given your 2 choices, I'd favor the first one:

```<code>a = b;
c = b;
</code>```

It's easier to visually parse and to figure out that both a and c now have the same value as b. Or at least you quickly see that 2 separate things get the same value.

In the second example, none of this is immediately obvious.

Discourage Ambiguity

I'd also discourage one-liners (a = b = c;) for similar reasons, and because they hide multiple expressions in a single statement. This facilitates the introduction of fly-by errors* and leads to developing a (bad) habit of cramming too much in too little space for a false sense of expressiveness.

* For instance, I've often come across things like:

a = b = b; (when obviously a c was intended somewhere),

and then quickly you'll see things like if (a == (b = c)) {}... and now you're one typo away from if (a = (b = c)) and then you've got absolutely no clue what the intended behavior was. Ah, and use descriptive variable names, obviously.

Body:
Humans are Parsers Too! Encourage Maximum Readability!

Given your 2 choices, I'd favor the first one:

a = b;
c = b;

It's easier to visually parse and to figure out that both a and c now have the same value as b. Or at least you quickly see that 2 separate things get the same value.

In the second example, none of this is immediately obvious.

Discourage Ambiguity

I'd also discourage one-liners (a = b = c;) for similar reasons, and because they hide multiple expressions in a single statement. This facilitates the introduction of fly-by errors* and leads to developing a (bad) habit of cramming too much in too little space for a false sense of expressiveness.

* For instance, I've often come across things like:

a = b = b; (when obviously a c was intended somewhere),

and then quickly you'll see things like if (a == (b = c)) {}... and now you're one typo away from if (a = (b = c)) and then you've got absolutely no clue what the intended behavior was. Ah, and use descriptive variable names, obviously.


答:
If the language allows for this syntax (and most do), I'd highly prefer this:</p>

```<code>a = c = b;
</code>```

Title: Equating multiple new variables with an old one

Body:
Sometimes I run into a situation where I need to equate two new variables with an old one. Which of the following (if any) is a good practice (w.r.t. code readability or any other factor), under what conditions?

```<code>a=b;
c=b;
</code>```

or

```<code>a=b;
c=a;
</code>```

Note, a,b and c are just the names chosen in this example.

Body:
If the language allows for this syntax (and most do), I'd highly prefer this:

a = c = b;


问:
Class design with bi-directional relationships
This is a purely design question.

I want to port a nice educational "game" Bug Brain to Java. In this game you design neural networks which consist of three elements: neurons, nodes and synapses.
Neuron is used to perform some kind of processing on its input signals to produce the desired output; it can be connected with other neurons/nodes (connections are uni-directional and weighted). We can think about nodes can as of junctions - they can also be connected with other neurons/nodes (and these connections are also uni-directional and weighted), but the weight of we cannot change weights of input connections. Synapse is a connection between these two elements.
To sum up: neurons and nodes have both inputs and outputs (to other neurons/nodes) and they do some inputs->outputs processing.

Q: Now, how would you design this class structure?
This is a sketch I "produced" so far:
screenshot of the design

Because the operation "connect two joins (i.e. neuron/node)" has three responsibilities (add synapse, add output to join A, add input to join B) I've decided to put it as a static methid in a controller class.
Of course I could avoid such two-directional relationships between elements: I don't have to keep track of outputs, only inputs but there are some other limitations eg. there can be only 8 I/Os per join so then I'd have to iterate over all synapses every time I add a connection to see if there is still some place to add it. In this case (this game) you won't have too many connections so it would not hit performance, but I'd like to know how to deal with such situations in general.

As it's the foundation of this whole logic of this project I'd like to have it properly made. All suggestions are warmly welcome ;)

答:
Bi-directional associations in a class design are possible, but they always come at a hefty price, which you should know and must be willing to pay.

Generally, I like to avoid bi-directional associations with the only exception being performance. As you have mentioned, without knowing the other directions, you may have to loop through all the other objects to find the right one (or count them in your case). This may be costly, but it can also be worked around in other ways than creating a bi-directional relationship (f.ex. association classes with caches).

As you may well get hundreds of synapses, it certainly isn't good to loop over them to be able to check if something is connectable, so I think your bi-directional association may be a valid option here. It depends on what exactly you mean with this game

won't have too many connections.

If you can afford the looping, then I suggest you do so. If you do keep the bi-directional relationship, you will have to be extremely careful to keep your model consistent. Each time you touch one of these associations, you must ensure that you atomically update the whole model to become consistent again.

It's hard enough to ensure that each and every modification is correctly mirrored for all involved objects / associations, but once you add concurrency to that it gets even more ugly, because you do not ever want another thread to see the model in an intermediate state, where just one direction has been added/removed yet.

Even if you use tools like Hibernate, which support the bi-directional relationships out of the box, you get other trade-offs. For example, if you combine Hibernate with eager fetching you may well end up reading your whole neural network from the database, whenever you just call for one join. That's all part of the price to be payed.

Also note that omitting the bi-directional relationship and adding some helper class which keeps track of the number of inputs/outputs instead is not a good idea. For one, you split up the responsibility for consistent model updates to something outside of your main model, and second, the involved logic to keep things consistent needs to be added either way. You may accept the poor looping performance, or you may reasonably improve it by some cached lookup that is easier to update and need not necessarily be complete.

As a summary: Bi-directional relationships are possible, but should only be considered, when you cannot work around their absence in a feasible way.


问:
What's with Delphi's support cycle?

This is a chart I whipped together showing the length of active (meaning ongoing bug fixes and service packs) support offered for each version of Delphi. It is based on the published support data obtained from Embarcadero's website. Delphi 2010 and XE are excluded because their active support is still ongoing so they can't really be compared accurately.

Ironically, Delphi 7, which was regarded by many to be the most stable until the release of Delphi 2009, had a support cycle three times as long as Delphi 2009. Granted, this chart spans three different companies with three different agendas. My question is why is Delphi 2009's support cycle so short? I understand Embarcadero has a business to run and they don't make money with service packs but really, 12 months? I would expect that of a $10 shareware title with low profit margins not a $900-$3500 world class development tool.

答:
Your graph shows pretty clearly the differences in priority between the policies of Emabarcadero vs. Codegear vs. Borland.  They would have different priorities and different expectations from their users.  That might explain your graph.  It's pretty clear from Embarcadero "All Access" that their intention is to make an MSDN style Embarcadero empire and sell their software as a service more than as a $900-$3500 dollar a seat behemoth.

They're really hybridizing the software as a service model though and I'm thinking they're trying to strike a balance between a steady release cycle and a steady stream of income. For my part, I hope we start using Delphi 2009 before they pull the plug on rebates for it.

Title: What's with Delphi's support cycle?


答:
I'd be inclined to agree with deceze. Yes, this example is clear(ish):

```<code>a = b;
c = b;
</code>```

But introduce more variables and it just becomes horrible:

```<code>a = z;

b = z;

c = z;

.

.

.

w = z;

x = z;

y = z;
</code>```

At which point would you draw the line and go for the single assignment statement? 3 variables? 4? 5?

Setting some arbitrary limit would seem to be daft (and in contravention of the Zero One Infinity Rule).

Body:
I'd be inclined to agree with deceze. Yes, this example is clear(ish):

a = b;
c = b;

But introduce more variables and it just becomes horrible:

a = z;

b = z;

c = z;

.

.

.

w = z;

x = z;

y = z;

At which point would you draw the line and go for the single assignment statement? 3 variables? 4? 5?

Setting some arbitrary limit would seem to be daft (and in contravention of the Zero One Infinity Rule).


答:
Although "functional programming" does not convey far reaching implications for issues of modularity, particular languages address programming-in-the-large in different ways. Code reuse and abstraction interact in that the less you expose the harder it is to reuse the code. Putting abstraction aside, I'll address two issues of reusability.

Statically typed OOP languages traditionally used nominal subtyping, which means that a code designed for class/module/interface A can only deal with class/module/interface B when B explicitly mentions A. Languages in functional programming family mainly use structural subtyping, which means that code designed for A can handle B whenever B has all the methods and/or fields of A. B could have been created by a different team before there was need for a more general class/interface A. For example in OCaml, structural subtyping applies to the module system, the OOP-like object system, and its quite unique polymorphic variant types.

The most prominent difference between OOP and FP wrt. modularity is that the default "unit" in OOP bundles together as an object various operations on the same case of values, while the default "unit" in FP bundles together as a function the same operation for various cases of values. In FP it is still very easy to bundle operations together, for example as modules. (BTW, neither Haskell nor F# have a full-fledged ML-family module system.) The Expression Problem is the task of incrementally adding both new operations working on all values (e.g. attaching a new method to existing objects), and new cases of values which all operations should support (e.g. adding a new class with the same interface). As discussed in the first Ralf Laemmel lecture below (which has extensive examples in C#), adding new operations is problematic in OOP languages.

The combination of OOP and FP in Scala might make it one of the most powerful languages wrt. modularity. But OCaml is still my favorite language and in my personal, subjective opinion it doesn't fall short of Scala. The two Ralf Laemmel lectures below discuss the solution to the expression problem in Haskell. I think this solution, although perfectly working, makes it difficult to use the resulting data with parametric polymorphism. Solving the expression problem with polymorphic variants in OCaml, explained in Jaques Garrigue article linked below, does not have this shortcoming. I also link to textbook chapters that compare the uses of non-OOP and OOP modularity in OCaml.

Below are Haskell- and OCaml-specific links expanding on the Expression Problem:

Wikipedia: Expression Problem

MSDN Channel 9 Lectures

Dr. Ralf Lämmel - Advanced Functional Programming - The Expression Problem

Dr. Ralf Lämmel - Advanced Functional Programming - Type Classes

Code reuse through polymorphic variants (postscript file)

Developing Applications With Objective Caml

Comparison of Modules and Objects

Extending Components

Title: How do purely functional languages handle modularity?

Body:
I come from an object oriented background where I've learned that classes are or at least can be used to make a layer of abstraction that allows for easy recycling of code which can then either be used to make objects or be used in inheritance.

Like for example I can have an animal class and then from that inherit cats and dogs and such that all inherit many of the same traits, and from those sub-classes I can then make objects that can specify a breed of animal or even the name of it.

Or I can use classes to specify multiple instances of the same code that handles or contains slightly different things; like nodes in a search-tree or multiple different database connections and what not.

I'm recently moving into functional programming, so I was starting to wonder:

How do purely functional languages handle things like that? That is, languages without any concept of classes and objects.


问:
Why do many PHP Devs hate using isset() and/or any of PHP's similarly defensive functions like empty()?
Over on stackoverflow, I see this issue crop up all the time:

E_NOTICE ?== E_DEBUG, avoiding isset() and @ with more sophisticated error_handler

How to set PHP not to check undefind index for $_GET when E_NOTICE is on?

How to stop PHP from logging PHP Notice errors

How do I turn off such PHP 5.3 Notices ?

Even Pekka (who offers a lot of solid PHP advice) has bumped against the dreaded E_NOTICE monster and hoped for a better solution than using isset(): isset() and empty() make code ugly

Personally, I use isset() and empty() in many places to manage the flow of my applications.  For example:

```<code>public function do_something($optional_parameter = NULL) {
    if (!empty($optional_parameter)) {
        // do optional stuff with the contents of $optional_parameter
    }
    // do mandatory stuff
}
</code>```

Even a simple snippet like this:

```<code>if (!isset($_REQUEST['form_var'])) {
    // something's missing, do something about it.
}
</code>```

seems very logical to me.  It doesn't look like bloat, it looks like stable code.  But a lot of developers fire up their applications with E_NOTICE's enabled, discover a lot of frustrating "uninitialized array index" notices, and then grimace at the prospect of checking for defined variables and "littering" their code with isset().

I assume other languages handle things differently.  Speaking from experience, JavaScript isn't as polite as PHP.  An undefined variable will typically halt the execution of the script.  Also, (speaking from inexperience) I'm sure languages like C/C++ would simply refuse to compile.

So, are PHP devs just lazy?  (not talking about you, Pekka, I know you were refactoring an old application.)  Or do other languages handle undefined variables more gracefully than requiring the programmer to first check if they are defined?

(I know there are other E_NOTICE messages besides undefined variables, but those seem to be the ones that cause the most chagrin)

Addendum

From the answers so far, I'm not the only one who thinks isset() is not code bloat.  So, I'm wondering now, are there issues with programmers in other languages that echo this one?  Or is this solely a PHP culture issue?

答:
Yes, they are lazy. A lot of them anyway...

Unfortunately the mentality of many PHP coders is "There is no point coding defensively if you can get the same end result quicker by relying on the language to handle errors caused by missing variables etc etc." I know, I've worked with several of them.

They tend to also be the ones who mysteriously head for an early lunch when their lack of correct error handling and reporting takes out the live servers for several hours...


问:
Responsibility to reproduce bugs
I'm developing a program using a library made by another programmer (he works in the same company). Recently I discovered a leak in the library, which happens under certain network conditions  after a few hours of running. I filed a bug with description of conditions to make this leak happen. That developer answered that "this is not enough", "it's not his responsibility to reproduce bugs" and I have to create unit test to reproduce this bug, otherwise he doesn't do anything.

Is he right?

What I can do in this situation? Creating unit test is impossible, because it depends on some random network timings.

答:
Is he right is probably a question that can't really be answered without knowing your company. However, he certainly isn't being very helpful.

I would raise the bug with him (which you've done), if it is causing an issue with your project then I would raise it as a blocker with your project manager and make it very clear that you've raised the bug with appropriate person but it's going to impact your project if it isn't fixed promptly.

I would also go over and talk to the developer and explain why it's infeasible to create unit tests but you'd be happy to show him it on your machine (assuming that's feasible?).

Title: Responsibility to reproduce bugs


答:
He is 100% right that you must provide enough information to make the bug reproducible - otherwise there is no chance to find out if any fix he provides will really work. </p>

<p>But - he is IMHO 100% wrong that this must be in form of a unit test. If you can describe a test scenario in a way so he can reproduce the failure (at least with a high probability in a reasonable amount of time, or by manual testing), you have a proof that the problem exists - which should set your colleague in the responsibility to fix it. Of course, if you are able to create a scenario which reproduces the bug quicker, that would be helpful for him. Ideally, one would make an automated test out of that, and it depends on your organization who has the responsibility for this. </p>

Title: Responsibility to reproduce bugs

Body:
I'm developing a program using a library made by another programmer (he works in the same company). Recently I discovered a leak in the library, which happens under certain network conditions  after a few hours of running. I filed a bug with description of conditions to make this leak happen. That developer answered that "this is not enough", "it's not his responsibility to reproduce bugs" and I have to create unit test to reproduce this bug, otherwise he doesn't do anything.

Is he right?

What I can do in this situation? Creating unit test is impossible, because it depends on some random network timings.

Body:
He is 100% right that you must provide enough information to make the bug reproducible - otherwise there is no chance to find out if any fix he provides will really work.

But - he is IMHO 100% wrong that this must be in form of a unit test. If you can describe a test scenario in a way so he can reproduce the failure (at least with a high probability in a reasonable amount of time, or by manual testing), you have a proof that the problem exists - which should set your colleague in the responsibility to fix it. Of course, if you are able to create a scenario which reproduces the bug quicker, that would be helpful for him. Ideally, one would make an automated test out of that, and it depends on your organization who has the responsibility for this.


答:
Both sides should put some effort.

Library developer should put some additional effort even without unit-tests, because some issues cannot be reproduced with unit tests. Sometimes it's hardware, sometimes it's some specific sequence of correct actions from the rest of program which makes the library producing bad results.

You should put some additional effort, because after all this my not be a bug in the library, but result of incorrect actions from the rest of program (e.g. corrupted heap may make any library behaving weirdly). So it makes sense to reduce as much as possible non-library code involved into bug reproducing. And you will likely do this faster and cleaner than a person unfamiliar with code of your application.

Title: Responsibility to reproduce bugs


答:
I'd be inclined to let sleeping dogs lie for now - you've raised the issue and it is assigned to him. Presumably there are processes in place to track outstanding bugs and chase these up?

If you wish to actively progress this further, I'd suggest talking to your manager to see if there are any test tools available that can reliably reproduce the issue.

From the developer's side - it would be seriously inert of them to do nothing given that you've provided the required information. It may be possible however that they have a massive workload so can't devote the time required to track the issue through.

Title: Responsibility to reproduce bugs


问:
Why the current enthusiasm for Functional Programming?
I've been hearing a lot of enthusiasm about functional programming languages lately, with regards to Scala, Clojure, and F#.  I've recently started studying Haskell, to learn the FP paradigm.

I love it, it's really fun, and fits my math background.

But will it ever really matter?  Obviously, it's hardly a new idea.

Here's my questions:

What has contributed to the recent FP enthusiasm?  Is is merely boredom with OO, or has something changed to make FP more needed than before?

Is this indicative of a FP future?  Or is this a fad, like object orient databases?

In other words, can anyone help me understand where this comes from and where it might be going?

答:
It used to be that people were writing programs to run on the desktop using the operating system's native APIs, and those APIs were (generally) written in C, so for the most part if you wanted to write a program for the native APIs, you wrote that program in C.

I think the new innovation in the last 10 years or so is for a diversity of APIs to catch on, particularly for things like web development where the platform APIs are irrelevant (since constructing a web page basically involves string manipulation). Since you're not coding directly to the Win32 API or the POSIX API, that gives people the freedom to try out functional languages.


问:
Extend the class or create an instance?
I'm reading Pro PHP and jQuery and want to rebuild the example. The author is creating a database connection class:

```<code>class DB_Connect {

protected $db;

protected function __construct($dbo = NULL){
     if (is_object($db)) {
          $this->db = $db;
     }
     else {
          // Constants are defined in /sys/config/db-cred.inc.php
          $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;
          try {
              $this->db = new PDO($dsn, DB_USER, DB_PASS);
          }
          catch (Exception $e) {
              die ($e->getMessage());
          }
     }
}
</code>```

This class is then extended by the application's main class, in order to get access to the database object.

Why is this done that way? Couldn't we rather create an instance of DB_Connect in the main class? What are the benefits of that approach?

答:
I wouldn't say that it's a good design to extend the Main application class from DB_Connect for the following reasons:

Inheritance should only be used, if the subclass can be used behaviorally equal to the Superclass, which is not the case in your example (See Liskov substitution principle)

Since LSP is violated and a DB is from a behavioral point of view used by the Main class, it's a classical use case for Composition, i.e. creating an instance of DB_Connect in the Main class as you suggested.

Your problem is a common design issue and is dealed with in the design principle "Composition over Inheritance".

Title: Extend the class or create an instance?


答:
What you see there is a classic rookie mistake, establishing an is-a relationship (creating a subclass) between two classes when the actual relationship is has-a (instantiating a class as a member).  It's unfortunate that this mistake made it into print.

If the as-stated purpose of Main holds true, its purpose is to be a central module for an application.  It is not, in and of itself, something that establishes a database connection and you wouldn't instantiate a Main to do that.  The easy test for this is to say the two alternatives aloud and see which rings true.  For example:

"A Car is a Wheel" (subclassing) doesn't make sense, because cars aren't wheels.  If you had to model four- and three-wheeled cars, you'd draw a complete blank on how to do that with subclassing.

"A Car has a Wheel" (instantiation) works because cars are composed of (among other things) one or more wheels.  Envisioning a FourWheeledCar and a ThreeWheeledCar containing multiple instances of Wheel would be easy: one class has four instances of Wheel and the other has three.

Title: Extend the class or create an instance?

Body:
I'm reading Pro PHP and jQuery and want to rebuild the example. The author is creating a database connection class:

```<code>class DB_Connect {

protected $db;

protected function __construct($dbo = NULL){
     if (is_object($db)) {
          $this->db = $db;
     }
     else {
          // Constants are defined in /sys/config/db-cred.inc.php
          $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;
          try {
              $this->db = new PDO($dsn, DB_USER, DB_PASS);
          }
          catch (Exception $e) {
              die ($e->getMessage());
          }
     }
}
</code>```

This class is then extended by the application's main class, in order to get access to the database object.

Why is this done that way? Couldn't we rather create an instance of DB_Connect in the main class? What are the benefits of that approach?


问:
Should I provide client libraries in some select languages along with the APIs themselves?
Say I have created a web service based on RESTful APIs. Does it make sense to also provide users with a client library for the API in some select languages which are likely to be the most used ones? By client library, I mean a thin wrapper around all the API calls, so that the users can call methods in their language and get objects in their language, which they can manipulate easily.

If I do not provide a client, users will create their own versions of the clients, and will have to bother with creating their own versions of the data model objects, and also have to deal with decisions like which HTTP library to use.

If I do provide a client, there is first the question of which languages do I support. Moreover, it might become difficult to maintain consistency between the API and the client libs. Also, there is the argument that the API is redundant if I provide a client library. I can simply provide the client library alone. Then I need to maintain the API contract at only one place instead of two.

I am a bit under pressure to provide the client library because many of the users are apprehensive about using the API (most likely because they'll have to write this library themselves if they are to use the API). Which is the best way to go? Are there other pros and cons I am missing? Appreciate any advice/anecdotes.

答:
Many of the organisations offering RESTful APIs also offer up some client code, but they also provide the full API separately. I think there's only a few sensible combinations:

API and client

API only

Client-only

I've ordered those in terms of preference, with API plus client being the most favoured. This is because, unless your API documentation is perfect, it probably won't be completely clear how you would string certain operations together to do something useful. This is where your client code comes in handy.

In general, support the most common languages as clients. Personally, I'd want to be creating libraries for (not in any particular order):

PHP

Ruby

Python

.NET

Java

Node.JS

Anything else is probably superfluous, or could be built by inspecting the code of your existing clients. It's probably wise to open-source the clients, even if not the rest of your code, so that the community can provide bug fixes and extra features. You've not told us a great deal about your exact scenario so it's difficult to say with any certainty whether that would be appropriate in this case.


答:
I often use that distinction between software and physical things when describing why building software is difficult.

Users just think it's this woolly thing inside the computer, you can't touch "it", they don't understand why it breaks etc.

Salesmen think they can just promise the world to a client and you the developer(s) will be be able to throw it together without too much thought (or too much change to the timescale!)

So I'd say a major difference is the people involved. In software it can be very difficult to tie people down to agreeing a specification, or simply not deviating from that specification over time.

Ideally, their would be not much difference between the two, but because your software just lives behind the monitor, they don't realise how big a change something is if you were having to, for example, saw the legs off a table to replace with new awesome legs 2.0

Title: Software design vs physical products design

Body:
I got a bunch of questions to answer to prepare for an exam and this one I'm actually not sure what's the clear difference :

"Explain the difference between designing software and designing physical products"

I have an opinion on this, but the more I think about it the more it feels like there's no real difference except that the tools and formula's used when making physical items has been established hundreds of years ago and the heuristics/models have been in place since forever.

I also thought that, once you design a spoon and make it, it doesn't evolve with time, it fulfills it's requirements and that's that, while for software new requirements come in all the time so you have to consider certain quality attributes in that regard.

This is from my software architecture class if you guys need a context.

What are the differences between software design and physical design, and am I off the mark with my answer?


问:
How do purely functional languages handle modularity?
I come from an object oriented background where I've learned that classes are or at least can be used to make a layer of abstraction that allows for easy recycling of code which can then either be used to make objects or be used in inheritance.

Like for example I can have an animal class and then from that inherit cats and dogs and such that all inherit many of the same traits, and from those sub-classes I can then make objects that can specify a breed of animal or even the name of it.

Or I can use classes to specify multiple instances of the same code that handles or contains slightly different things; like nodes in a search-tree or multiple different database connections and what not.

I'm recently moving into functional programming, so I was starting to wonder:

How do purely functional languages handle things like that? That is, languages without any concept of classes and objects.

答:
One of popular solutions, is to break code into modules, here is how it's done in JavaScript:

```<code>    media.podcast = (function(name) {
    var fileExtension = 'mp3';

     function determineFileExtension() {
         console.log('File extension is of type ' + fileExtension);
     }

     return {
         download: function(episode) {
            console.log('Downloading ' + episode + ' of ' + name);
            determineFileExtension();
        }
    }
}('Astronomy podcast'));
</code>```

The full article explaining this pattern in JavaScript, apart from that there is number of other ways to define a module, such as RequireJS, CommonJS, Google Closure. Another example is Erlang, where you have both modules and behaviours that enforce API and pattern, playing similar role as Interfaces in OOP.

Body:
One of popular solutions, is to break code into modules, here is how it's done in JavaScript:

    media.podcast = (function(name) {
    var fileExtension = 'mp3';

     function determineFileExtension() {
         console.log('File extension is of type ' + fileExtension);
     }

     return {
         download: function(episode) {
            console.log('Downloading ' + episode + ' of ' + name);
            determineFileExtension();
        }
    }
}('Astronomy podcast'));

The full article explaining this pattern in JavaScript, apart from that there is number of other ways to define a module, such as RequireJS, CommonJS, Google Closure. Another example is Erlang, where you have both modules and behaviours that enforce API and pattern, playing similar role as Interfaces in OOP.


答:
Open Source a component makes sense if - and only if - you nurture the project and build a community.  Accept bug reports, fix bugs, and make new releases on a regular basis.  If you do that, like Eclipse and Mozilla have done, you can harvest the benefits.

If you don't do that, the experienced people can smell a mile away that you just dumped off the code base hoping others would do the work for you.

Title: How do I convince my company to contribute towards Open-Source?

Body:
I'm trying to convince the company I work for to contribute towards open-source software, specifically building a library/component for ASP.NET web apps. We have an 'Innovation Day' coming up where we can work on our own personal pet projects at work, similar to Google's one day a week policy, except ours is once a month :-), and I have an idea that I want to open-source.

Other companies do this, eg. Headspring Systems (http://automapper.codeplex.com - see banner at top).

What do I tell them? What benefits can I convey to them that would be beneficial to the company? I've already mentioned possible exposure for our company and reputation etc. as well as attracting top software developers when we next go on a hiring spree. But what other arguments could I make?

Update: The company I work for is a software company that mainly builds web applications in ASP.NET and the MS Stack. Our clients are mainly the NHS (public health sector of the UK).


答:
It looks like you're asking two questions: "How can you achieve modularity in functional languages?" which has been dealt with in other answers and "how can you create abstractions in functional languages?" which I'll answer.

In OO languages, you tend to concentrate on the noun, "an animal", "the mailserver", "his garden fork", etc. Functional languages, by contrast, emphasise the verb, "to walk", "to fetch mail", "to prod", etc.

It's no surprise, then, that abstractions in functional languages tend be over verbs or operations rather than over things. One example that I always reach for when I'm trying to explain this is parsing. In functional languages, a good way to write parsers is by specifying a grammar and then interpreting it. The interpreter creates an abstraction over the process of parsing.

Another concrete example of this is a project I was working on not long ago. I was writing a database in Haskell. I had one 'embedded language' for specifying operations at the lowest level; for example, it allowed me to write and read things from the storage medium. I had another, separate, 'embedded language' for specifying operations at the highest level. Then I had, what is essentially an interpreter, for converting operations from the higher level to the lower level.

This is a remarkably general form of abstraction, but it is not the only one available in functional languages.


问:
Class Naming Conundrum
I am working on a personal project that works with databases, and in this project I have a set of classes that are similar, so they inherit from a common base class. The problem I am faced with is that I have this nagging feeling that the names of the classes that derive from the base class do not really reflect what they actually are.

Caveat: Please ignore the fact that this looks like a reinvention of the wheel. That's the point of the project.

The common base class is called Entity. Its purpose is to serve as the base for:

Classes that describe the data returned by a SQL query or stored procedure, or

Classes that describe a SQL query or stored procedure and their parameters.

Both of these classes are created by consumers of the assembly to describe the stored procedures and queries in their database, and the data they will retrieve from it.

For example, these are designed to work against the Northwind database:

```<code>public class Employee : DataEntity
{
    public int EmployeeId { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
}

[Sql(@"SELECT [EmployeeId], [LastName], [FirstName]
       FROM [Employees]
       ORDER BY [LastName], [FirstName]")
public class SelectEmployee : SqlEntity
{
    public int EmployeeId { get; set; }
}
</code>```

As it stands, I am currently calling the first of these Data Entities, and the second SQL Entities. However, I am not entirely sure that these are fitting terms. For instance, are they actually models? Is there a better term that I am not considering?

The assembly only considers public properties that have both a getter and a setter. The developer can add anything else to it if he or she needs to. So a Data Entity can be extended to include additional functionality.

Any advice would be greatly appreciated.

EDIT

It's worth noting that you can also model stored procedures with this stuff (again, using a Northwind database stored procedure):

```<code>[Sql()]
public class CustOrderHist
{
    [Parameter("@CustomerId", SqlDbType = SqlDbType.NChar, MaxLength = 5)]
    public string CustomerId { get; set; }
}
</code>```

The assembly automatically binds classes to stored procedures, and properties to parameters.

答:
When naming classes it's often tempting to include words that describe usage in programming terms. These words might include abstract, entity, and/or base. So you end up creating classes like AbstractOffice or BaseOffice. The name of the class implies two meanings what it does Office and how it's used Abstract. I don't recommend doing this. It adds extra details in the name that it doesn't need.

KISS (Keep It Simple Stupid)

I recently refactored a project I did a year ago to use simple names, and it became much easier to read the code. Give it a try and see if it helps. You can always rename the classes later.

```<code>public class Employee : Data
{
    public int Id { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
}

[Sql(@"SELECT [EmployeeId], [LastName], [FirstName]
   FROM [Employees]
   ORDER BY [LastName], [FirstName]")
public class Employees : Query
{
    public int Id { get; set; }
}
</code>```

When you remove programming specific terms (i.e. I removed Select, Entity and renamed Sql to Query). The classes become more readable. Now their names infer only specific information (i.e. this is about an employee). The implementation that it uses SQL or represents an entity pattern is irrelevant. That information should go into the class comments not it's name.

In the future, you will have a bug. Which description is easier to understand, and a result easier to find in the source code.

Employee John Smith is not an active member of Employees.

or

EmployeeEntry John is not an active member of SelectEmployee

That's just an example, but later when you're using those classes the code becomes difficult to read. A sea of terms that aren't relevant to what the code is doing.

Title: Class Naming Conundrum

Body:
When naming classes it's often tempting to include words that describe usage in programming terms. These words might include abstract, entity, and/or base. So you end up creating classes like AbstractOffice or BaseOffice. The name of the class implies two meanings what it does Office and how it's used Abstract. I don't recommend doing this. It adds extra details in the name that it doesn't need.

KISS (Keep It Simple Stupid)

I recently refactored a project I did a year ago to use simple names, and it became much easier to read the code. Give it a try and see if it helps. You can always rename the classes later.

public class Employee : Data
{
    public int Id { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
}

[Sql(@"SELECT [EmployeeId], [LastName], [FirstName]
   FROM [Employees]
   ORDER BY [LastName], [FirstName]")
public class Employees : Query
{
    public int Id { get; set; }
}

When you remove programming specific terms (i.e. I removed Select, Entity and renamed Sql to Query). The classes become more readable. Now their names infer only specific information (i.e. this is about an employee). The implementation that it uses SQL or represents an entity pattern is irrelevant. That information should go into the class comments not it's name.

In the future, you will have a bug. Which description is easier to understand, and a result easier to find in the source code.

Employee John Smith is not an active member of Employees.

or

EmployeeEntry John is not an active member of SelectEmployee

That's just an example, but later when you're using those classes the code becomes difficult to read. A sea of terms that aren't relevant to what the code is doing.


问:
Using GPLv3 software in a open source project licensed BSD (3-Clause)

Preamble

If I say "BSD" I mean the 3-Clause BSD license

If I say "GPL" I mean the GPLv3 license

I am not the author of the GPL project

I am the author of the BSD project

Simple Task

I want to use a 3rd party software (GPL) in (or better 'with') my open source project (BSD).

Situation

I won't change any of the GPL project code (using it AS IS).

I want to use it as kind of a library (I know about LGPL but it's not available).

I will use the GPL software as bulk, not only parts of the code.

I will indicate the use of the GPL project with the license, homepage and where and why it is used in my BSD project (in README file).

I will not take the credits for the functionality of the GPL project.

I will take the credits for my project and the "Adapter" connecting my BSD project to the GPL project.

I don't want to re-license the GPL project as BSD

I won't charge any fees or something like that.

To gain insight, you can find the BSD project at

GitHub: MOC-Framework (see /Extension/FlowPlayer and /Module/Office/Video)

and the GPL project here:

Flowplayer (free flash-version)

Simple Question

Is this possible?

Closing Words

I found some discussions, stating "it is possible", others say "no". Most of the "no" were for commercial projects. Most of the "yes" are referring to: "include BSD in GPLv3", but that's not what I mean. I want GPLv3 along with BSD.

I simply can't figure it out.

答:
Disclaimer: I'm just a software developer sharing personal opinions and not your lawyer.

Well, I don't know where your problem is, however next to keeping your code under BSD you could also dual-license it under GPL which will help you to keep headaches out on your end if licensing causes you some and you don't want to consult a lawyer on your behalf.

That done you can keep all your code under BSD (next to having it GPL) to also full-fill requirements to distribute GPL'ed parts with it. You can do that by making clear to users who contribute code that they contribute it under both licenses.

That done its clearly your users choice. All you need to do when accepting patches is to take care that the BSD of your library code is preserved.

This would be similarly the situation when the GPL component would not be part of your library and a user would integrate GPL components with it. Because of the BSD, nobody is hindered doing that.

Users who don't want to have a GPL'ed package can just remove any GPL'ed parts and only use the parts under BSD. Just make clear with your dual licensing model is not conjunctive (GPL and BSD) but disjunctive (GPL or BSD) for the files you keep under dual licensing.

This would also help you with the problem offering a software package on Github containing GPL'ed software not under the GPL - which is what I see you right now doing with the Github hosting platform (it has automatic packaging).


问:
Can/should the Single Responsibility Principle be applied to new code?
The principle is defined as modules having one reason to change. My question is, surely these reasons to change are not known until the code actually starts to change?? Pretty much every piece of code has numerous reasons why it could possibly change but surely attempting to anticipate all of these and design your code with this in mind would end up with very poor code. Isn't it a better idea to only really start to apply SRP when requests to change the code start coming in? More specifically, when a piece of code has changed more than once for more than one reason, thus proving it has more than one reason to change. It sounds very anti-Agile to attempt to guess reasons for change.

An example would be a piece of code which prints a document. A request comes in to change it to print to PDF and then a second request is made to change it to apply some different formatting to the document. At this point you have proof of more than a single reason to change (and violation of SRP) and should make the appropriate refactoring.

答:
An example would be a piece of code which prints a document. A request comes in to change it to print to PDF and then a second request is made to change it to apply some different formatting to the document. At this point you have proof of more than a single reason to change (and violation of SRP) and should make the appropriate refactoring.

I have so many times shot myself in the foot by spending too much time adapting the code to accommodating those changes. Instead of just printing the damn stupid PDF.

Refactor To Reduce Code

The single use pattern can create code bloat. Where packages are polluted with small specific classes that create a garbage pile of code that doesn't make sense individually. You have to open dozens of source files just to understand how it gets to the printing part. On top of that there can be hundreds if not thousands of lines of code that are in place just to execute 10 lines of code that does the actual printing.

Create A Bullseye

The single use pattern was intended to reduce source code and improve code reuse. It was meant to create specialization and specific implementations. A sort of bullseye in the source code for you to go to specific tasks. When there was a problem with printing you knew exactly where to go to fix it.

Single Use Does Not Mean Ambiguous Fracturing

Yes, you have code that already prints a document. Yes, you must now change the code to also print PDFs. Yes, you must now change the formatting of the document.

Are you sure the usage has changed significantly?

If refactoring causes sections of the source code to become overly generalized. To the point that the original intent of printing stuff is no longer explicit, then you have created ambiguous fracturing in the source code.

Will the new guy be able to figure this out quickly?

Always maintain your source code in the easiest to understand organization.

Don't Be A WatchMaker

Far too many times I've seen developers put on an eyepiece, and focus on the small details to the point that no one else could put the pieces back together again should it fall apart.


问:
Should a software company have a dedicated team for research and/or utility libraries?
I work in a company that does web applications for various banks and some smaller e-shops
We employ about 20 developers and have 4-5 projects in development at any one time.
Our development teams don't interact much and a lot of the same problems are done in varied ways(good to bad).

I was wondering if it would be a good idea for a company to have a team of programmers that do research on current frameworks and continually improve a common library of functions and a common framework to build current and future projects much faster and more efficiently.

How large should a team like this be?

Also should it have permanent members that train others or should it rotate people?

Update: I was thinking about a common project that people can work on for fun that might spark some interest. It seems that when people have job pressures the solutions they come up with are not the best.

答:
At the one company I worked at that really had a similar thing, it didn't seem to work well.  The people in the inner team would come up with a neat idea and come up with a prototype that mostly worked, then it went over the wall and we were expected to turn it into a product.

What I'd expect to have happen is that the tool group would wind up going on its own little program, producing functions that weren't really all that useful, but which cluttered the API and got used enough so they couldn't easily be removed.  They wouldn't document adequately.

If the tool group was sufficiently under a system architect who was in continuous contact with the people actually using the tools, it might work.  If the tool group rotated frequently (which would hinder doing a lot of exterior research) it might work.  However, I'd be afraid of losing contact with the people doing the paying work.


问:
Programming against a protocol in Objective-C
I stumbled accross the SOLID principles. There is one burning question. Should I always use protocols? I never saw someone using them in the way that a Java developer would use them.

I tried it in a demo project and ended up with a .h file for the protocol, another .h for the header. A .m file for the implementation and sometimes a .xib for the UI.

Is there a reason why an ObjC developer would only use protocols for delegates? I never saw ObjC code with a test first approach. Does SOLID programming apply for ObjC?

答:
TDD isn't hugely popular in the ObjC world.  Look at some of the official Apple SDK libraries and you'll find patterns that would make TDD advocates give up in disgust (there are a lot of singletons in the iOS SDK, and it's a pattern that works very well with ObjC).  Unit tests in general aren't that popular, either, which explains why the official unit test suite is a relatively recent edition to Xcode and why it's still third-rate.  The ObjC philosophy seems to be:

"Don't make your code more complicated in order to write tests: simple code is easier to debug."

That'll undoubtedly rattle the TDD guys, but it's the approach I've noted in ObjC developers.

ObjC takes a more pragmatic approach to protocols than Java devs do to interfaces ("every class must have an interface and an implementation, just in case!"):

If you know that you'll need multiple classes with the same interface and want the compiler's help, you can create a protocol.

If you know that you'll need multiple classes with the same interface but don't care about support from the compiler, you can use "informal protocols" (take a look at how to handle data from a GKSession object: you implement a method, not a protocol).

If you're probably only going to use one class, just use the class and forget about protocols.

This is why you only tend to see protocols used in conjunction with delegates: they tend to be the only places that you'll create more than one class to implement the necessary functionality, especially as the delegate pattern is so pervasive.  Other languages tend to require you to either subclass and override or implement an interface to provide additional functionality; ObjC tends to use delegates instead.

The fact that ObjC is dynamic removes a lot of the need for protocols/interfaces.  Java, C++ and C# developers spend a lot of time trying to categorize and type everything as accurately as they can, resulting in multitudes of interfaces and classes.  That simply isn't necessary in a dynamic language (and it's one of the reasons I'm so happy to have switched from C# to ObjC: I can spend my time solving problems instead of describing type hierarchies).

ObjC is dynamic and supports duck typing, so if an object implements a method "quack" you can call that method without explicitly conforming to the "Duck" protocol; you can even identify if the object implements the method before calling it thanks to ObjC's excellent metaprogramming capabilities.


问:
GPL and OpenJDK: Questions regarding source headers
I have some legal questions regarding OpenJDKs source header:

```<code>/*
 * Copyright (c) 1997, 2008, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
(...)
</code>```

Is it GPL-conform to define a comment-part of a source-file (in this case the header) as "must not be modified"?

Do other GPL-licensed open-source projects derived from this sources need to obey this "statement"?

Does Oracle really have a Copyright on these GPL-sources?

Is it GPL-conform to state that it's only allowed to modify [the software] under the terms of the GNU General Public License version 2?

What does this mean for GPLv3 open-source projects which are using these (possibly modified) sources?

Do I have to fear editing (and publishing) this file (and maybe adding something to the file header) in my own GPLv3 open-source project?

答:
I can't answer all of those questions, so I'll just pick some ;-):

Does Oracle really have a Copyright on these GPL-sources?

Yes, they probably do. Most of the code was written (or bought) by Sun which was bought by Oracle. And Sun was/Oracle is pretty stringent with regard to copyright tracking, so in general you can assume that if they claim copyright, they probably have it.

Is it GPL-conform to state that it's only allowed to modify [the software] under the terms of the GNU General Public License version 2?

Well, yes. That's what the GPL does: it grants you the permission to modify the code, provided you conform to the GPL.

And no, the common "version 2 or greater" is not required.

What does this mean for GPLv3 open-source projects which are using these (possibly modified) sources?

Since this doesn't allow usage under GPLv3, they will have to keep this part GPLv2.

Default disclaimer: this is not legal advice. As usual: contact a lawyer and pay them money if it's really important to you.


问:
In what situations will Windows-based authentication for my ASP.NET MVC web application fail to allow users from accessing the web application?
My requirements are:

To build an ASP.NET MVC web application to use Windows-based authentication, since all the users which will be accessing the application are our internal employees, and they have username and password on our company's Active Directory.

So, as I understand, the Windows authentication inside ASP.NET MVC is valid:

If an employee accesses the web application inside our company intranet then he will be able to login to the MVC application automatically (without the need to enter a username and password).

If the user logs in to the application using VPN from outside the company intranet, then he still can access the application automatically without the need to enter username and password.

But what happens if the user accesses the ASP.NET MVC web application using an operating system other than Windows such as Linux? Will Windows-based authentication work from inside or outside the company intranet?

What will happen if a user accesses the web application from outside the company network using his personal PC using Windows operating system?

答:
In both parts 3 and 4 of your question, the user will be prompted with a username/password window, into which they would enter their Active Directory credentials.

Internet explorer will only automatically log the user in when the site is in the intranet zone in the security settings (you can manually add sites to this zone if they are not automatically picked up.

If exposing this site externally, it would be wide to only expose the site through https


问:
How to store data for Windows Store apps?
I have a application which requires me to save data to a database not located on the users computer. Which approach is the best to save and access data for this scenario? Normally I would use Entity Framework and MS Sql Server but this seems not to a options for me with windows store apps. </p>

答:
I think using some kind of web-API proxy would be your best guess if you are concerned about the security of the app.

It has been proven that Windows 8 apps can be decompiled easily when they are not obfuscated (just like any other Java or .NET based program without obfuscation), and even with obfuscation, one could argue that an eventual hacker would be able to find your connection string anyway.

You can have a server-side web-application language such as PHP, ASP .NET or ASP .NET MVC handle the input from your app, and then make that web application post its data further to the SQL server.

For reading data, the app could pass some ID along with the request in the URL, and the web application could then fetch the information needed from the SQL server, and write the data in the response for your app to read.

This could all work just like a RESTful API, or something similar.

Here's a short example.

The app requests the URI http://www.example.com/api/get-customer?id=38, assuming that you own the domain example.com, and that this is where you host your server-side web-application.

The website internally connects to the database, fetches all information regarding the customer with ID 38, and writes it to the HTTP response through a deserializable format (JSON or XML would do).

The app gets the response, parses it, and uses it visually in the GUI.

This is for fetching data though, but I am sure it demonstrates the concept. You can use it to insert data as well, and so forth.

I realize that a solution like this requires a server or some form of hosting, but at least it helps you move on.


答:
I am not a lawyer.  If you need legal advice, consult a lawyer.

Is it GPL-conform to define a comment-part of a source-file (in this case the header) as "must not be modified"?

AFAIK, it is not incompatible.  I believe that the "conditions" of a license are additive.  And as the owners of the copyright, Oracle have a right to tailor the license agreement to their own ends.  (The GPL section that forbids  placing extra license restrictions on a downstream derived product applies to direct and indirect licensees ... not to the original licensor.)

Do other GPL-licensed open-source projects derived from this sources need to obey this "statement"?

Yes.

Does Oracle really have a Copyright on these GPL-sources?

Yes.  Sun wrote the code, and Oracle took over Sun.  Oracle owns the copyrights.

Is it GPL-conform to state that it's only allowed to modify [the software] under the terms of the GNU General Public License version 2?

Yes.  Indeed, this is pretty common.  The Linux source code says the same thing, AFAIK.

What does this mean for GPLv3 open-source projects which are using these (possibly modified) sources?

It depends.

If the usage is governed by the "Classpath Exception", then there are no implications.  (The "Classpath Exception" basically allows you to use the Java class libraries in any project, commercial or non-commercial without any of the GPL limitations on redistribution ... of your code.)

The Oracle binary distribution license allows you to embed JRE / JDK binaries in your product ... provided that you don't tinker with them.

Otherwise your usage is covered by the GPL2, and according to this FAQ the terms of GPL2 and GPL3 are incompatible.

Do I have to fear editing (and publishing) this file (and maybe adding something to the file header) in my own GPLv3 open-source project?

If you publish / redistribute it, (apart from under the Binary License terms), then: Yes, you need to obey the rules.  And rules say NO MODIFICATION of the header.

Otherwise No.

Title: GPL and OpenJDK: Questions regarding source headers

Body:
I have some legal questions regarding OpenJDKs source header:

```<code>/*
 * Copyright (c) 1997, 2008, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
(...)
</code>```

Is it GPL-conform to define a comment-part of a source-file (in this case the header) as "must not be modified"?

Do other GPL-licensed open-source projects derived from this sources need to obey this "statement"?

Does Oracle really have a Copyright on these GPL-sources?

Is it GPL-conform to state that it's only allowed to modify [the software] under the terms of the GNU General Public License version 2?

What does this mean for GPLv3 open-source projects which are using these (possibly modified) sources?

Do I have to fear editing (and publishing) this file (and maybe adding something to the file header) in my own GPLv3 open-source project?


答:
You have mentioned that ' I filed a bug with description of conditions to make this leak happen.'

If you are sure that description is really enough to reproduce bug then you already know exact conditions. Now, if you cannot write unit test after knowing conditions, then that clearly means that you cannot mock some of the components involved or some parts of code are too tightly coupled to allow to create practical unit test.

You should ask library owner to refactor code to allow you to create unit test. You will have to explain clearly what is in library that is stopping you to create unit test. He will have to refactor code otherwise concede that unit test is not possible with current code. Both ways, you win.

If this does not work, following are options you have:

You can reproduce bug with more evidences.

Try involving higher authority and ask him/her to evaluate your evidences.

Try using library in prototype application with mock environment to be coded only to reproduce bug. That way, you will be able to prove at least that bug exists.

Title: Responsibility to reproduce bugs


问:
What source control do I need for a large project in an average company?
I know Git is great for open source projects. But I was wondering: for a company with 20 programmers working on a 1 year project, which source control system is desirable? From what I heard Git uses pulling; wouldn't it be less than desirable to need to go through someone else to get your changes in the main trunk? Especially when everyone is working at the same time?

That's just of an example I was wondering about. I know how to use SVN but even at my last job we didn't use it on our projects, since everything was done in PHP and those were typically standalone 1 week projects. I just had SVN for my local code and didn't need to use it with others.

So what are good source controls, and specifically why is it good for this?

答:
While I think that this question is broad and should be addresses on a per-company basis, based on your IT framework and network/development structures, I think that the most important aspect of choosing source/version control is not which application you use, but whether it's use is practically structured and enforced.

Structure and enforcement of usage are the most important aspects of version control.

Plan ahead and get everyone on board.  Enforce usage. Not just with programmers, but with everything related to projects (documents, images, etc.).

SVN is a fine application, and can be integrated with many add-ons (including bug/task tracking), doesn't need a separate server and is free!

There are other good source control applications also, as @EricBoersma said:

Use whatever your team is comfortable with.

Just have processes and best practices in place, and buy off from those that can enforce it.


问:
How to handle flag in multiple if-else's
I seem to see this often enough in my code and others. There's nothing about it that seems horribly wrong, but it annoys me as it looks like it can be done better. I suppose a case statement, might make a little more sense, but often variable is a type that does not work well or at all with case statements (depending on language)

```<code>If variable == A
    if (Flag == true)
        doFooA()
    else
        doFooA2

else if variable == B
    if (Flag == true)
        doFooB()
    else
        doFooB2
else if variable == C
    if (Flag == true)
        doFooC()
    else
        doFooC2
</code>```

It seems there's multiple ways to "factor" this, such as 2 sets of if-elses, where one set handles when Flag == true.

Is there a "good way" to factor this, or perhaps when this if-else algorithm happens it usually means you  are doing something wrong?

答:
It could be handled with polymorphism.

```<code>factory(var, flag).doFoo();
</code>```

Whenever you have a bunch of if/else checks on the type of something, you might consider centralizing the if/else check in a factory method, then calling doFoo() polymorphically. But this could be over-kill for a 1-off solution.

Maybe you could create a key/value map where the key is var/flag, and the value is the function itself.

```<code>do[var, flag]();
</code>```

Body:
It could be handled with polymorphism.

factory(var, flag).doFoo();

Whenever you have a bunch of if/else checks on the type of something, you might consider centralizing the if/else check in a factory method, then calling doFoo() polymorphically. But this could be over-kill for a 1-off solution.

Maybe you could create a key/value map where the key is var/flag, and the value is the function itself.

do[var, flag]();