答:
For introducing a new technology, you will want to get some buy-in.  It should help the entire team in its implementation.  Shoving it down people's throats will cause them to keep it from being successful.

Is that too big of an ask, just to make me slightly more productive?

So you become slightly more productive, what are the benefits for the other members?  Will they become more productive?  Will the quality of the product that they are producing be better?

Do you have buy-in for implementing this from your customers/management?  Will they accept a slow down in productivity while the team learns a new technology?  What are the benefits for them?  If you just implemented Backbone, they might not be as patient for another change.


问:
Writing Clean, Elegant Procedural Code (BASIC): Is There Such a Thing?
I learned to code in OO languages. I've always been interested in design patterns, clean code, etc., etc. - you know the type.

Now at work I'm using a BASIC dialect. Given modern programming values, should we try to carry over these same principles to new procedural code?

I'm pondering the following issues, and I wondering if I'm on the right lines.

Variable Names

Variables are not strongly typed (nightmare!), they're given short names and written in ALL CAPS (why?!) - basically I find them hard to read and they could be anything. Once upon a time, I'm sure XCNT = 1 would have offered performance gains over int_EXISTINGCUSTOMERCOUNT = 1, but we're past that now - surely? I choose the verbose name here.

GOSUB

I want to break down long blocks of code down into multiple smaller blocks. Internally, GOSUB is used (over a FUNCTION) if the helper is not re-usable by other programs / functions. Given its ability to add / modify variables without the safety of scoping (as we know it in the OO world) GOSUB scares me.

This is typical:

```<code>GOSUB GET_BEST_CUSTOMER
IF RC = 0 THEN CRT CNAME
</code>```

But I would write:

```<code>rc_GETBESTCUSTOMER = 1 ; !Default exception
str_CUSTOMERNAME = ""
GOSUB GET_BEST_CUSTOMER ; !set rc_GETBESTCUSTOMER, populate str_CUSTOMERNAME
IF(rc_GETBESTCUSTOMER = 0) THEN
    CRT str_CUSTOMERNAME
END
</code>```

With the caveat that GET_BEST_CUSTOMER would only modify rc_GETBESTCUSTOMER and str_CUSTOMERNAME in 'global' scope.

There's more, but it's all along the same lines. Given the editor of choice (Notepad++), I'd say my coding style makes the code easier to read and understand - therefore easier to maintain. But I'm sure some BASIC die-hard would readily tell me I'm doing it all wrong.

答:
GOSUB

GOSUB was a more disciplined version of GOTO.  This is a particularly horrible example of  the sort of misuse of GOTO that was once popular.  GOSUB is an enormous step up from that, and it looks like your codebase is using labels instead of line numbers for the GOSUB targets, so it really could be a lot worse.

I don't know what dialect of BASIC you're using, and I hadn't ever used FUNCTION in the little bit of BASIC programming I did a long time ago, but if FUNCTION in your dialect of BASIC is anything like a modern language function call, I'd prefer it over GOSUB for new code.  In your example code, the proposed replacement was 3 times longer than the 2 line original, so I can't really agree that it's more readable, but I'm guessing that a rewrite of the original using FUNCTION would end up having about the same length and clarity as the original.

Naming

I don't see the point in attaching the type to the front of the variable name.  Your long names are an improvement over XCNT, but EXISTING_CUSTOMER_COUNT is more readable (IMO) than running them together and sticking a type prefix on it.  You may be running them together due to being used to camelCase, but you can't do camel case in all caps.

ContentLicense: CC BY-SA 3.0


问:
Is it fair to ask a team to start using CoffeeScript?
I started my new job as a JS developer in November and starting implementing Backbone pretty soon after. This was a big enough learning curve for the team (me included), however I'm thinking about looking at CoffeeScript, which I'm guessing would require everyone on the team to know it? Is that too big of an ask, just to make me slightly more productive?</p>

答: How will introducing Coffeescript save/earn your employer money? If you can come up with a realistic answer to that then suggest it to your team. Your CV skills do not appear on the company balance sheet.</p>


问:
Context class in Strategy pattern
I'm trying to understand the strategy pattern and asking myself: is the context class must-have or can I leave it out without compromising pattern's purpose ?

I was under the impression I needed some kind of switch for reading different types of files but didn't want to just hack something and later deal with refactoring (although, of course it always happens that code can be refactored but the idea was: try to be as smart as possible in the design beforehand...):

Image taken from wikimedia

Can the client delegate directly to the Strategy interface or is there something I just missed to understand about the context class?

```<code>interface Reader {
    // read information from file and fill data list field of Client
    readFile();
}
class ExcelReader implements Reader{ /* */ }
class PdfReader implements Reader{ /* */}

class Client{
    // strategic choice
    Reader r;

    // data list field
    List<Data> data;

    // Client Constructor
    public Client(){
        if(<file ends in .xls>)
            r = new ExcelReader();
        else
            r = new PdfReader();
        r.readFile();
    }
}
</code>```

So, above depicted is the context class missing. Does the code adhere to the strategy pattern?

答:
In your example, the code calling readFile is part of the Client constructor. That method is the "context" you are looking for. The strategy pattern does not need a "context class" literally, and at the first version of your code the strategy object (the "Reader" in your case) may reside just in a local variable. Especially when there is just one "strategic method" ("readFile") to be called.

However, if your codebase grows from one version to the next, it is not unlikely getting more and more "strategic" methods to be called, and the decision which strategy to apply and the performing of the "strategic methods" will happen at different times and at different places in your code. So you start to refactor them to keep the logic in one place. This will lead straightforward to an implementation looking similar to the diagram in your question.

Title: Context class in Strategy pattern

ContentLicense: CC BY-SA 4.0


问:
Workflow for building a RESTful API
I am building a RESTful API, and so far, to make sure that my resources work as I need them to, I am using a REST client called Postman. This makes it easy for me to store routes and quickly make requests to them for testing. My current collection of routes in Postman looks like this:

The trouble with testing the API is this way is I have to manually change resource IDs. For example, if I want to test the PUT method on my posts resource, I have to first create a resource, find the ID, and then paste it into the PUT URI. This is long!

What is considered professional practice for building a RESTful API? Should I be writing unit tests for each route, dynamically creating the post before testing methods like update?

答:
Testing any kind of API is very difficult to do manually, especially without a UI that uses it. As soon as you find manual testing is getting tricky or tedious, that's a sure sign that you need some automated tests.

You could write integration tests from the HTTP level which first call the API to setup the data appropriately. But writing true unit tests might be preferable if you have multiple layers of code under your API. You can stub and mock the calls to the data service to avoid having to call the API several times per test.

Title: Workflow for building a RESTful API


问:
How to convince my teammates to follow some basic rules
I have a problem with my teammates. Long story short: We are three students working at a project for a competition. The project consists of 2 separate applications: one for Windows (that I develop) and one for Android (my colleagues are responsible for developing it). Our code bases will never intersect, the apps will communicate via third party tools.

The problem is as follows: I have some experience working in teams as I made an internship at a big company last year, and I try to enforce some coding standards for our code. I also set up a git repository / wiki / collaboration software that we can use to push code / write ideas, document protocols and so on, but it seems that I am the only one that uses these tools.

I tried to tell them that writing quality code and documenting every step will benefit us in the long run, but they don't seem to see the advantage of it. Also I was thinking to add some integration tests but from what I can see, as long as they don't use current tools to make their life easier, I don't think I can convince them the usefulness of integration tests.

Most of the peer's code resides on their computers, they don't share a common code base and as I found out, they integrated their pieces by meeting and sharing code via usb stick.

My question is: am I too harsh on this matter? Do I enforce some absurd rules? Keep in mind that this is a small project, the requirements are very clear(I created documents specifying what should the applications do), three skilled developers could do this in 3-4 days, so they might not see the added complexity of writing quality code as long as their current method just works.

Is there any way that I can show them the benefit of documenting code, using git and so on?

答:
I've found this very problem at university. Many people simply are not willing to learn a different (and maybe more professional approach) way of working. </p>

<p>I'f you have systems in place however and explain how to use the system then many people are willing to give it a try. I also think that repositories are very under used tools and people will commonly just use a something like dropbox. </p>

Body:
I've found this very problem at university. Many people simply are not willing to learn a different (and maybe more professional approach) way of working.

I'f you have systems in place however and explain how to use the system then many people are willing to give it a try. I also think that repositories are very under used tools and people will commonly just use a something like dropbox.


问:
Cheap programmable, portable device
Since a long time I have thrived for being able to program something I can take with me - a very small computer like a programmable calculator, gameboy, pocket PC or cellphone.
However, I didn't find anything fitting yet!

The thing I'm looking at is the price, because I can't afford to spend too much money on it.

What are some cheap portable programmable devices?

All I'd need is support for uploading assembler code from my computer. I don't care about the display, a simple LCD would be sufficient. Same goes for the buttons

I have looked at programmable calculators, portable gaming consoles such as the PSP and more, however didn't find anything that fit :(

答:
The ultimate hobby boards/processors if you are at all interested in embedded development comes from Microchip. In particular, they manufacture PIC controllers.  www.microchip.com.

The processors are dirt cheap (many less than $2) but are very powerful. The apps/devices can be as simple and/or complex as your imagination will take you. They have oodles of libraries and specialized chips to add to boards so you can build whatever device you desire. The form factor goes from computer sized boards down to downright small, so a mobile programming device is quite doable.

As a side benefit, many companies use PIC Controllers in their products (even if just for proof of concept/prototypes). So you will gain some expertise that could land you a job. Good embedded developers are hard to find.

OwnerDisplayName: Ars

ContentLicense: CC BY-SA 2.5

Title: Cheap programmable, portable device


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答: Many people tend to think that JavaScript is similar to C++ and don't understand that it actually uses prototype inheritance.</p>


问:
Is it possible to use a "non-commercial" REST API in a for-pay app?
I am interested in integrating the results of 3rd-party news API's into my for-pay application. The APIs would be a very small part of the app (e. g. the app is not just reselling the APIs). I have found that many APIs such as Yahoo have "non-commercial" conditions like the following:

YOU SHALL NOT: Sell, lease, share, transfer, or sublicense the Yahoo!
  APIs or access or access codes thereto or derive income from the use
  or provision of the Yahoo! APIs, whether for direct commercial or
  monetary gain or otherwise, unless the API Documents specifically
  permit otherwise or Yahoo! gives prior, express, written permission...

(from Yahoo Local Search API page)

Does this prevent the API from being used as part of any app which costs money to use? For example, if I charge you to get into my site, and then display some content from this API, is that OK? If I let you see the content from the API for free, but then charge you to do something else on the site, is that OK?

I'm obviously not expecting specific legal advice. Instead, I'd like to know about either:
(1) a good reference on this topic that can answer my question
(2) an "answer by example", i. e. an example of a real-world app that does something similar

答:
Seems pretty straightforward that they don't want you using their news for commercial purposes.  It's up to you and your lawyers to decide if you want to take the risk.

There is the bit about "prior, express, written permission" that you may wish to pursue.  You could argue that a properly branded Yahoo! news feed would be beneficial to them.


问:
Setting up a development standardization guide for in-house/vendor programmers
I was recently hired by a large multi-national corporation to head up mobile development for their sales operation/support team. In a company of close to 10,000 people I am, at least in the America's, the only mobile developer. They are testing the waters and phase 1 (temp-to-hire) went well enough for them.

Now they are considering expanding to other developers for their other sales operations/support teams and I've been tasked with assisting/leading the writing of a standardization guide for iOS programming.

I am a big believer in giving people the freedom to work in the manner they most feel comfortable in but at the same time, I have been the creator of and on the receiving ends of big balls of mud applications. Having learned through experience I have several standards that I follow religiously such as commenting, at times almost every line - just short things but enough to let someone else know what is going on and using #pragma mark - DESCRIPTION to block off like minded methods, indentation, naming classes with a prefix to avoid name space conflicts, etc. etc.

So I guess what I am looking for is not to tell another programmer how they should iterate through an array but rather some basic standardization so anyone can jump into anyone else's project and find their way around with little learning curve. I'd love to see what other means people use to maintain control over a software development group.

答:
A standardization guide is all well and good, but it needs to be accompanied by more - anyone can ignore a document. People often start with good intentions to follow a document, but they can often fall by the wayside.

Implementing things like peer code reviews, or a tool like FXCop for checking code design as part of your build process can help this type of thing.


问:
Naming for a class that consumes an iterator pattern
The iterator pattern is very clearly defined. What would you call the consumer of an iterator?</p>

答:
One reason you may need to ask is that the original Gang of Four book describing the iterator pattern refers to the consumer of an iterator with the highly distinctive name of "client" (and in fact later on it doesn't show the client as one of the participants in the pattern at all).

I don't know of any specific jargon for the consumer of an iterator, and would guess that no standard name has been settled on.

Iteratoror comes to mind, but I don't expect it to catch on.


答:
You just said it - the consumer of an iterator (or the client).  :)  This is the language used in this reference and elsewhere.

In agreement with Erik's answer, the way to name the consumer (IMO) is to imply iteration with a term like aggregate / sum / iterate or even just use a plural (e.g. GetCustomers). Yet describing its business purpose is probably more important than calling out the fact that it is iterating (again IMO).

Title: Naming for a class that consumes an iterator pattern

Body: The iterator pattern is very clearly defined. What would you call the consumer of an iterator?</p>


答:
The approach has problems:

Your approach is not symmetric. Your other team members needs to change, but you're not learning their good practices. Enforcing rules in situation like this is difficult. Better approach would be to collect good rules and practices from all members of the team and then everyone just reads the resulting document.

Learning is difficult. Other people's rules just do not make sense because those rules do not have the logical structure your programmers are expecting. Enforcing rules that do not make sense is not useful activity.

Everyone learned different things. It's natural that programmers coming from different backgrounds have learned different things. Their strengths are different, and styles of writing code different. The tools they use are different. Enforcing one set of rules/tools/styles are going to be nightmare because the limitations are losing the strength those developers have spent years learning.

Change takes time. While the person who invented the rules you're enforcing have pretty easy time following the rules, everyone else is suffering, and spending time learning the new rules. This is one reason why everyone on the team should be able to change the rules.

Choosing tools/coding conventions or styles for a whole team is difficult activity. It can only be done slowly over time, testing what stuff works and what is not working. Giving a team 2 weeks to start following 50 rules is not going to work.

Title: How to convince my teammates to follow some basic rules

Body:
I have a problem with my teammates. Long story short: We are three students working at a project for a competition. The project consists of 2 separate applications: one for Windows (that I develop) and one for Android (my colleagues are responsible for developing it). Our code bases will never intersect, the apps will communicate via third party tools.

The problem is as follows: I have some experience working in teams as I made an internship at a big company last year, and I try to enforce some coding standards for our code. I also set up a git repository / wiki / collaboration software that we can use to push code / write ideas, document protocols and so on, but it seems that I am the only one that uses these tools.

I tried to tell them that writing quality code and documenting every step will benefit us in the long run, but they don't seem to see the advantage of it. Also I was thinking to add some integration tests but from what I can see, as long as they don't use current tools to make their life easier, I don't think I can convince them the usefulness of integration tests.

Most of the peer's code resides on their computers, they don't share a common code base and as I found out, they integrated their pieces by meeting and sharing code via usb stick.

My question is: am I too harsh on this matter? Do I enforce some absurd rules? Keep in mind that this is a small project, the requirements are very clear(I created documents specifying what should the applications do), three skilled developers could do this in 3-4 days, so they might not see the added complexity of writing quality code as long as their current method just works.

Is there any way that I can show them the benefit of documenting code, using git and so on?


答: Iterable. An Iterable uses an Iterator to iterate its elements. Hence it is consuming the iterator .


问:
Great Lunch and Learn Topics
We recently revived the lunch in learns for the programming department in the company I work for. We were all asked if we had any ideas for a session, and if we would be interested in doing a presentation. I've had a few ideas ranging from various topics such as:

How to think like a user when designing UI

or Differences in HTML5

A few coworkers I tossed these ideas around to seem to like them. However, I'd like some more ideas before I dig too far into creating a presentation.

What are some great lunch and learn topics?

答:
You could play "Spot the Defect".

Go through your bug tracking logs and find some places where people wrote code that was plausible but horribly wrong in some subtle way.  Rewrite the code to disguise where it came from but preserve the bug, put it up on the whiteboard, and have people:

see if they can find the bug

figure out what the fix is

describe how the bug could have been found during code review

propose changes to the language or tool that would have prevented the bug

and so on.

Neal Gafter and I put together a series of six "spot the defect" problems and presented them to the audience at the last Norwegian Developers Conference; it was a lot of fun, and I think people learned a lot.

Title: Great Lunch and Learn Topics


答:
I've been in this position. I evaluated a lot of different things, but didn't really find something that suited me. Here are some things I've looked at though and pros/cons

Gameboy Color/Advance

Pros:

Fairly cheap

The actual programming work isn't too bad

Strong community

Fairly easy to write graphically intense applications (since it's designed for it

Cons:

The hardest part is actually getting a program onto the thing. Persisting it without your computer beside it is even harder

Not "officially" supported for creating your own programs

Beginning to become archaic

TI-84

Pros:

Easy to program using TI-BASIC on-the-go

Graphing applications are trivial

Easy to load programs from a computer (in assembly or basic)

Dependendable and very good battery life

Strong community around it due to the proliferation of high schoolers creating games and other time wasters on them

Cons:

Really weak hardware. Slow processor, black and white low-res screen, less than 1M of memory

Programming it in assembly language is not too easy

C compilers doesn't appear to be too popular as a replacement for assembly

Rather pricey for such weak hardware (~$100)

Arduino

Pros:

Cheap

Easy to come by(I think even Radio Shack sells them now)

Can interface to just about anything

Extremely strong community

Extremely low power (if you program it right)

C compilers galore!

Cons:

No built in screen or input device

Program memory is read-only for the most part, making programming on the go nearly impossible

Comes as a bare-board. You have to supply a lot to make it something useful

Programming it to hook up all of the hardware you need could be daunting depending on component choice

Relatively weak as far as hardware. 8 bit micro at 20MHz, less than 1M of RAM/ROM

Raspberry PI

Pros:

A strong and growing community

Fairly powerful hardware (1080p capable, 512M of RAM)

USB support (means you could have wifi support, external HD, etc)

Can run Linux and therefore run high level languages like Python or C# with ease

Cheap

Cons:

Doesn't come with anything. You must supply screen, input device, power supply, even a case.

Fairly new device. Community is still growing and finding all of the best practices

Kind of hard to get your hands on. Don't expect to get one shipped to your doorstep sooner than a month in advance

USB support can be a pain because it doesn't really provide enough power for it. A powered hub is basically required

Drivers are still being ported and developed for USB devices (the basics will work, but when you buy a wifi adapter you have to make sure to get the right one, etc)

also, I have seen at least one custom RaspberryPi Laptop. Maybe one day you can just buy a kit (that'd be my choice)

Smartphone/Tablet running Android

Pros:

If you don't mind used, can be found fairly cheap

Very fragmented, but usually a fair amount of power compared to the other options

Wifi connectivity

Very large community for developing android apps

Trivial to download apps off the internet

Many phones can be easily rooted(especially older ones)

Cons:

Learning to make apps can have a bit of a learning curve

Difficult to program on-the-go

Possible, but not extremely common to make apps in something other than Java

Most phones don't include a keyboard

Most phones don't ship already rooted

Usually have to deal with carrier bloatware crippling your battery and being a general annoyance

Not a full list of course, but tried to cover everything I've looked at in the past for this purpose

Title: Cheap programmable, portable device

Body:
Since a long time I have thrived for being able to program something I can take with me - a very small computer like a programmable calculator, gameboy, pocket PC or cellphone.
However, I didn't find anything fitting yet!

The thing I'm looking at is the price, because I can't afford to spend too much money on it.

What are some cheap portable programmable devices?

All I'd need is support for uploading assembler code from my computer. I don't care about the display, a simple LCD would be sufficient. Same goes for the buttons

I have looked at programmable calculators, portable gaming consoles such as the PSP and more, however didn't find anything that fit :(


问:
Count true array elements
In my code (Python+numpy or Matlab, but issue can apply to any array programming language), I often need to count the number of elements in an array where the elements are true. Usually, I implement this as sum(x>0.5), but this may be considered improper. See Is it correct to add booleans in order to count the number of true values in a vector?. Numpy has count_nonzero, but if there is no special-purpose function, what would be the proper way to write this?

For example, in Matlab, I can either write sum(x>.5) or length(find(x>0.5)). The former is slightly faster but may be considered improper (see above). Are there any other alternatives for counting the number of true values in an array, and what should be my criteria for selecting one?

(In a low-level language, one would write an explicit for-loop, but that is an extremely inefficient way to implement this in a high-level array programming language)

答:
In Python you can use generator expressions with many builtin functions.  sum(x for x in vec if x > 0.5) and len(x for x in vec if abs(x) > 1.0) are perfectly valuable.  They're equivalent to using a list comprehension like sum([x for x in vec if x > 0.5]) but doesn't have the overhead of needing to building a temporary list.

You can extend this idea by looking into map, filter & reduce (as well as the itertools versions that more efficiently handle iterators).

Title: Count true array elements


答:
I actually like Joel Spolsky's own thoughts on it, as he laid out in Getting Things Done When You're Only a Grunt. To summarize:

Just do it - Write makefiles, create a daily build server etc.

Nobody uses source control or bug databases? Start using them yourself. If someone reports a bug against your work, ask them politely to use the bug database to report bugs to you so you can keep track of them; otherwise you won't be able to keep them straight in your head and fix them. On any non-trivial project, there'll be a situation that's only solvable with source control: use source control for the code by yourself and swoop heroically in to save the day when such a situation occurs. Once this happens a few times, they'll become convinced

Create a Pocket of Excellence - Do the right things for yourself: speccing, scheduling etc. Since this doesn't seem like a work project, it doesn't look like you can take this advice all the way, since you can't hire new team members who believe in your message

Become Invaluable - Demonstrate that you're a great contributor to cement your influence in the team. Otherwise you run the risk of becoming known as a person who values process and tools over results


问:
Is it a good idea to include Installer Project within single solution?
I have pretty large code base for the client product I am working on. I am using Visual Studio 2010 for my development and it's hectically slow. I can get rid off this by disabling the installer project within the solution file.

Is it a good idea to include setup projects within the same solution?

How can I increase the performance of Visual Studio when working with large projects (including installer?)

How about a different build configuration separately for installer? Will that help?

答:
If you're really sure that the slowness you notice is due to the time spent by Visual Studio packaging the application in an MSI file, then you can:

either turn off the building of the setup every time you compile the solution,

or simply unload, like you already do, the installer project. This is perfectly fine and is not limited to installer projects; you can unload anything you're not using right now, and reload those projects later when you need them. Note that you can even unload the projects which are referenced in other projects, as far as they were built successfully.

For example I'm currently working on a project which has 35 small projects. Most of the time, only two of them (the code I'm working on and the corresponding unit tests) are available, every other being unloaded.

Unloading projects you're not using right now has also a benefit on time spent by Visual Studio when loading the solution.

Note that companies working on large projects are using nightly builds, which may often take hours. If you're feeling that you're waiting for too long while the code is compiling, consider using nightly builds (and/or continuous integration in general; it's never too soon to start using it).

Once you have continuous integration, you may heavily optimize Visual Studio performance by loading from the version control only the projects you need.


问:
How does strengthening of preconditions and weakening of postconditions violate Liskov substitution principle?
I read that Liskov's substitution principle is violated if :

Preconditions are strengthened, or

Postconditions are weakened

But I don't get fully yet how these two points would violate Liskov substitution principle. Can some one please explain with an example. Specifically, how would any one of the above conditions cause a situation where a subclass object can not be substituted for a superclass object?

答:
Assume your baseclass works with a member int. Now your subtype requires that int to be positive. This is strengthened pre-conditions, and now any code that worked perfectly fine before with negative ints is broken.

Likewise, assume the same scenario, but the base class used to guarantee that the member would be positive after being called. Then the subtype changes the behavior to allow negative ints. Code that works on the object (and assumes that the post-condition is a positive int) is now broken since the post-condition is not upheld.

These are of course trivial examples, but the concept holds. Stuff like leaving a file/database connection open is an example of an eased post-condition that leads to issues.


答:
This example is pretty much beaten to death, but consider the Square/Rectangle or Circle/Ellipse possibility. Suppose you have a base class Rectangle that defines an object with a length and width. If you have a Square class that inherits the Rectangle class, it would have a rule in its setter/getter that would require that any change to length or width would alter its counterpart. These dimensional requirements strengthen pre-conditions because a rectangle substituted for a square would be missing these dimensional requirements. Suppose you reverse the inheritance so that a Rectangle inherits a Square, you would be weakening post conditions by relaxing the dimensional requirements to allow the Rectangle to behave independently.

However, if you were to remove the dimensional change capability, the substitution principle holds because if neither a Rectangle nor a Square may change dimensions, then they have equal pre and post conditions regardless of inheritance. Both have a length, both have a width, and neither can alter those values.

ref: Wikipedia - http://en.wikipedia.org/wiki/Liskov_substitution_principle

Title: How does strengthening of preconditions and weakening of postconditions violate Liskov substitution principle?

Body:
I read that Liskov's substitution principle is violated if :

Preconditions are strengthened, or

Postconditions are weakened

But I don't get fully yet how these two points would violate Liskov substitution principle. Can some one please explain with an example. Specifically, how would any one of the above conditions cause a situation where a subclass object can not be substituted for a superclass object?


问:
Should I create a new open project to replace an existing one?
Recently I was looking at an open source project to contribute to however after going through the ugly code base (which seems to break quite a bit) and reading some things about the current maintainer I decided it would be a good fit for me.

Right now my thinking is to just start a new project with the same goal but using a different set of technologies that I think fit the problem better, the only reason stopping me is avoiding second system effect given the fact the system is live and works.

I could contribute to the other project and in doing so avoid essentially creating two different solutions to the same problem or I could solve the problem the way I think it should be solved and then see which system gets more traction. Is there some prior art to these circumstances that I should be aware of when considering this decision?

答:
Have the best of both worlds. Fork the project. As long as you're not wanting to switch to a more permissive license(such as GPL to BSD), it's all legal. This is what open source is all about!

By forking:

You'll have the existing project as a starting point

You have complete control over the project

You can "contribute back" your changes to the existing project if they'll accep tthem

You can brand it the way you want


答:
I don't know if this will fit your purpose, because you mention uploading from a PC to the device, however, one of the most fun and compelling environments I have used fully portably was the Palm family of devices running Quartus Forth.

Written by a former colleague of mine (but having no personal stake in the company myself), Quartus provides a complete on-the-go programming environment on the Palm system.  I used to run it on a IIIx quite some time ago, and given Forth's power and expressiveness, it made many things possible even when running fully-hosted on the device with no outside PC support.

You could pick up a Palm device from a local flea market or perhaps Craigslist and live the 90's all over again.

Good Luck

Title: Cheap programmable, portable device


答:
My comment was to say that I'd call the class an "aggregator," and I'm putting it here as requested.  I'd also like to respond to the comment suggesting that the results aren't always aggregated, presumably in the sense of totaling up some kind of value.

What I mean with "aggregate" is the qualitative dictionary definition of the term: "taking all units as a whole."  This doesn't necessarily mean that each record has some integer property and the total of that property is the aggregate.  Rather, I'd consider the "aggregate" to be the interpretation of the the big picture.  You're considering a sequence of these things as part of some larger gestalt (i.e. "as a whole," in whatever sense that means to you.)


问:
Identifying Domain Services & Application Services when doing DDD
-I'm trying to figure out how to identify Application Services in my application. I think I can identify a Domain service by 2 things:

It acts as a facade to the repository.

It holds business logic that can't be encapsulated in a single entity.

So I thought about this simple use case that I'm currently working on:

An admin should be able to ban a certain user. The operation must be logged and an email must be sent to the banned user.

I have a UserRepository which has a function getUserById(). I have a User entity which has a ban() function.

I'll create a UserService like this:

```<code>class UserService{
    static void banUser(int userId){
          User user= UserRepository.getUserById(userId);
          user.ban();
          UserRepository.update(user);
    }
}
</code>```

The userId is a POST variable that I'll be receiving in my Controller from a web form.

Now where does the logging go? I need to log the ban process twice before and after the operation ex:

```<code>Logger.log("Attempting to ban user with id:"+userId);
//user gets banned
Logger.log("user banned successfully.");
</code>```

Second, I need to send a mail to the user. where should the call go?

I thought about putting the logging and email  is the UserService class itself, but I think there are better solutions.

Third, where do Application Services fit in all of this?

答:
```<code>class UserService{
    public public UserService(IUserRepository repo, INotificationService notification)
    {
      this.UserRepository = repo;
      this.Notification = notification;
    }
    public void BanUser(int userId){
          User user= UserRepository.getUserById(userId);
          user.ban();
          Notification.NotifyBanned(user);
    }
}```</code>
When it comes to logging then you may choose a lot of solutions. Just log in BanUser method. Create logger per class (like log4j/log4net users do). Or you can inject ILogger in ctor. Or maybe it is some kind of Audit trail. Then maybe IUserAuditTrail would be better?
```<code>
public interface IUserAuditTrail
{
    void UserBanned(User user)
    void AccountCreated(User user)
}
```</code>
or sth like that.
Or you can add loggin AOP style. Decorate UserService with attribute and use PostSharp or use IoC container and configure interceptor to handle logging for you. Unless logging operations isn't business function and instead it's just for programmers I would go for interceptors. Otherwise IAuditTrail or sth like that.</p>

Body:
class UserService{
    public public UserService(IUserRepository repo, INotificationService notification)
    {
      this.UserRepository = repo;
      this.Notification = notification;
    }
    public void BanUser(int userId){
          User user= UserRepository.getUserById(userId);
          user.ban();
          Notification.NotifyBanned(user);
    }
}

When it comes to logging then you may choose a lot of solutions. Just log in BanUser method. Create logger per class (like log4j/log4net users do). Or you can inject ILogger in ctor. Or maybe it is some kind of Audit trail. Then maybe IUserAuditTrail would be better?

public interface IUserAuditTrail
{
    void UserBanned(User user)
    void AccountCreated(User user)
}

or sth like that.
Or you can add loggin AOP style. Decorate UserService with attribute and use PostSharp or use IoC container and configure interceptor to handle logging for you. Unless logging operations isn't business function and instead it's just for programmers I would go for interceptors. Otherwise IAuditTrail or sth like that.


Body:
Despite that "aggregator", "IteratorClient" & "IteratorConsumer" seems to match the idea, I suggest to "highlight" the goal of your class, as your class identifier.

.............................
..+-----------------------+..
..|     ArrayListClass    |..
..+------*----------------+..
.........*...................
..........*..................
...........*.................
............*................
............*................
..+----------*--------+......
..|                   /......
..| Has Iterators    /.......
..|                 / |......
..+----------------/--+......
.............................

One exception, that I have to deal with, is that you have a class, without iterators, and you make a subclass, with the only goal of adding iterators, and you cannot or do not want to add the iterators to the original class.

.............................
..+-----------------------+..
..|     TreeViewClass     |..
..+-----------*-----------+..
..............|..............
..............|..............
..............|..............
..............^..............
............./.\.............
............/...\............
.........../--*--\...........
..............|..............
..............|..............
..............|..............
..+-----------*-----------+..
..| IterableTreeViewClass |..
..+-----------------------+..
.............................

Cheers


问:
Changing behaviour of abstract class without modifying subclasses
I am facing a problem with changing behaviour of a library (thus cannot or don't want to change its internals because of future updates, etc.).

In this library there is an abstract class which shares few methods with all its subclasses. Now I need to change few methods in this abstract super class without changing the subclasses. I was wondering what pattern I should apply to this without rewriting the whole thing.

I use PHP, so I could use a trait to override these methods in my own sub-subclasses which I will then use in my client code. This would result in creating the sub-subclasses and adding a trait (which is a one-liner). But I need to run PHP 5.3 which doesn't support traits.

Is there a pattern that solves this problem?

EDIT 2: the point is I don't want to change the library code, I can extend the subclasses and use them in client code but I don't want to change the code in the library itself (so I can update the library easily).

EDIT: see simplified code below

```<code>abstract class SuperClass {
    protected function doMagic() {
        ... I need to change this ...
    }

    abstract public function execute();
}

class SubClass1 extends SuperClass {
    protected public execute() {
        $this->doMagic();
        ... some other code ...
    }
}

class SubClass2 extends SuperClass {
    protected public execute() {
        $this->doMagic();
        ... some different code ...
    }
}
</code>```

答: Abstract classes should be written without considering their subclasses in order to avoid tight coupling. I don't know what your specific situation is, but usually abstract classes are meant to be used for polymorphism, with each subclass implementing a specific behavior through an abstract method. If you find yourself changing code inside the base class which will break the subclasses, you have a coupling problem. Base classes should make calls to abtract methods which the subclasses will implement. Moreover, a subclass should limit the number of calls to parent methods.</p>


答:
I see no design pattern, but, an algorithm.

Original Code:

```<code> abstract class SuperClass {
     protected function doMagic() {
         ... I need to change this ...
     }

     abstract public function execute();
 } // class

 class SubClass1 extends SuperClass {
     protected public execute() {
         $this->doMagic();
         ... some other code ...
     }
 } // class

 class SubClass2 extends SuperClass {
     protected public execute() {
         $this->doMagic();
         ... some different code ...
     }
 } // class
</code>```

New Code:

```<code> abstract class SuperClass {
     protected $UseNewSpell = false;

     protected function OldSpell() {
        // put previous code here
     }

     protected function NewSpell() {
        // put new code here
     }

     protected function doMagic() {
         if ($this->UseNewSpell) {
            $this->NewSpell();
         }
         else {
            $this->OldSpell();
         }
     }

     abstract public function execute();
 } // class

 class SubClass1 extends SuperClass {
     protected public execute() {
         $this->UseNewSpell = false;

         $this->doMagic();
         ... some other code ...
     }
 } // class

 class SubClass2 extends SuperClass {
     protected public execute() {
         $this->UseNewSpell = false;

         $this->doMagic();
         ... some different code ...
     }
 } // class
</code>```

Title: Changing behaviour of abstract class without modifying subclasses

Body:
I am facing a problem with changing behaviour of a library (thus cannot or don't want to change its internals because of future updates, etc.).

In this library there is an abstract class which shares few methods with all its subclasses. Now I need to change few methods in this abstract super class without changing the subclasses. I was wondering what pattern I should apply to this without rewriting the whole thing.

I use PHP, so I could use a trait to override these methods in my own sub-subclasses which I will then use in my client code. This would result in creating the sub-subclasses and adding a trait (which is a one-liner). But I need to run PHP 5.3 which doesn't support traits.

Is there a pattern that solves this problem?

EDIT 2: the point is I don't want to change the library code, I can extend the subclasses and use them in client code but I don't want to change the code in the library itself (so I can update the library easily).

EDIT: see simplified code below

```<code>abstract class SuperClass {
    protected function doMagic() {
        ... I need to change this ...
    }

    abstract public function execute();
}

class SubClass1 extends SuperClass {
    protected public execute() {
        $this->doMagic();
        ... some other code ...
    }
}

class SubClass2 extends SuperClass {
    protected public execute() {
        $this->doMagic();
        ... some different code ...
    }
}
</code>```

Body:
I see no design pattern, but, an algorithm.

Original Code:

 abstract class SuperClass {
     protected function doMagic() {
         ... I need to change this ...
     }

     abstract public function execute();
 } // class

 class SubClass1 extends SuperClass {
     protected public execute() {
         $this->doMagic();
         ... some other code ...
     }
 } // class

 class SubClass2 extends SuperClass {
     protected public execute() {
         $this->doMagic();
         ... some different code ...
     }
 } // class

New Code:

 abstract class SuperClass {
     protected $UseNewSpell = false;

     protected function OldSpell() {
        // put previous code here
     }

     protected function NewSpell() {
        // put new code here
     }

     protected function doMagic() {
         if ($this->UseNewSpell) {
            $this->NewSpell();
         }
         else {
            $this->OldSpell();
         }
     }

     abstract public function execute();
 } // class

 class SubClass1 extends SuperClass {
     protected public execute() {
         $this->UseNewSpell = false;

         $this->doMagic();
         ... some other code ...
     }
 } // class

 class SubClass2 extends SuperClass {
     protected public execute() {
         $this->UseNewSpell = false;

         $this->doMagic();
         ... some different code ...
     }
 } // class


问:
Should I use a parser generator or should I roll my own custom lexer and parser code?
What specific advantages and disadvantages of each way to working on a programming language grammar?

Why/When should I roll my own? Why/When should I use a generator?

答:
Why not fork an open-source parser generator and make it your own?
If you don't use parser generators, you code will be very hard to maintain, if you made big changes the syntax of your language.

In my parsers, I used regular expressions (I mean, Perl-style) to tokenize, and use some convenience functions to increase code readability. However, a parser-generated code can be faster by making state tables and long switch-cases, which may increase source code size unless you .gitignore them.

Here are two example of my custom-written parsers:

https://github.com/SHiNKiROU/DesignScript - a BASIC dialect, because I was too lazy to write lookaheads in array notation, I sacrificed error message quality
https://github.com/SHiNKiROU/ExprParser - A formula calculator. Notice the weird metaprogramming tricks


答:
First question--why do you need to change the logic of the abstract class?  You seem to indicate that you don't want any of its current subclasses to inherit the changes, so I have to assume you want to write new subclasses which will.  Given that the new subclasses don't exist yet, add a little indirection first:

```<code>abstract class SuperClass {
    protected function doMagic() {
        ... I need to change this ...
    }

    abstract public function execute();
}

abstract class ExtendedSuperClass extends SuperClass {
    protected function doMagic() {
        ... NEW CODE ...
    }
}

class SubClass1 extends SuperClass {
    protected public execute() {
        $this->doMagic();
        ... some other code ...
    }
}

class SubClass2 extends SuperClass {
    protected public execute() {
        $this->doMagic();
        ... some different code ...
    }
}

class SubClass3 extends ExtendedSuperClass {
    protected public execute() {
        $this->doMagic();
        ... yet more different code ...
    }
}
</code>```

That is, extend the abstract class with a new abstract class, and have the classes needing the new logic extend THAT.

Body:
First question--why do you need to change the logic of the abstract class?  You seem to indicate that you don't want any of its current subclasses to inherit the changes, so I have to assume you want to write new subclasses which will.  Given that the new subclasses don't exist yet, add a little indirection first:

abstract class SuperClass {
    protected function doMagic() {
        ... I need to change this ...
    }

    abstract public function execute();
}

abstract class ExtendedSuperClass extends SuperClass {
    protected function doMagic() {
        ... NEW CODE ...
    }
}

class SubClass1 extends SuperClass {
    protected public execute() {
        $this->doMagic();
        ... some other code ...
    }
}

class SubClass2 extends SuperClass {
    protected public execute() {
        $this->doMagic();
        ... some different code ...
    }
}

class SubClass3 extends ExtendedSuperClass {
    protected public execute() {
        $this->doMagic();
        ... yet more different code ...
    }
}

That is, extend the abstract class with a new abstract class, and have the classes needing the new logic extend THAT.


问:
Software for prioritising issues / tasks in an ordered list/queue (ideally in Github)?
It seems to me that the best way to manage priority for programming tasks in a backlog is to simply put them in order. Do the top task first, second one next. If priority changes, re-order the queue. I thought this was exactly how things were supposed to work in Agile.

I have yet to find an online open-source team task manager that supports custom ordering of tasks this way - although I might be out of date. Assembla definitely doesn't. Jira doesn't seem to. When we used Agilo in my previous company, it didn't seem to either. The only service I've found that implements this simple concept well is Google Tasks, but that's hardly suitable for managing software projects.

I don't understand why this isn't the standard way to manage priority.

My ideal way to track issues would be through Github. As far as I can tell Github Issues also doesn't support custom ordering of tasks. Does anyone know if there's any way to implement this on top of Github Issues somehow? Is there any way I can suggest it as a feature?

答:
I actually just had a similar challenge I wanted to solve just a few minutes ago. I downloaded Task Coach, which is open source and written in Python. It's a very detailed task manager.

http://taskcoach.org/

The reasons I think it might help you is that it supports ordering based on priority, so you can simply list your tasks in order and change the priority which will re-order the list.

Hope that helps!


问:
Can a neural network provide more than "yes" or "no" answers?
Every example neural network for image recognition I've read about produces a simple "yes" or "no" answer.  One exit node corresponds to "Yes, this is a human face," and one corresponds to "No, this is not a human face."

I understand that this is likely for simplicity of explanation, but I'm wondering how such a neural network could be programmed to give a more specific output.  For example, let's say I was classifying animals.  Instead of it saying "Animal" or "Not an animal", I would want responses like "Dog", "Fish", "Bird", "Snake", etc., with one final exit node being "Not an animal/I don't recognize this".

I'm sure this must be possible, but I'm having trouble understanding how.  It seems like due to the training algorithm of backpropogation of error, as you train up one exit node (i.e., "This is a dog") and the weights of the neurons are changed, then the ideal state for another exit node that you previously trained (i.e., "This is a bird") will begin to deviate, and vice versa.  So training the network to recognize one category would sabotage any training done for another category, thus limiting us to a simple "Yes" or "No" design.

Does this make such a recognizer impossible?  Or am I misunderstanding the algorithm?  The only two things I can think of are that:

Either we could train one neural network for each thing we want classified and somehow use those to construct a greater, super-network (so for example, a network for "dog", a network for "bird", etc., which we somehow add together to create the super-network for "animals"); or,

Create some kind of ridiculously complicated training methodology which would require incredibly advanced mathematics and would somehow produce an ideal neuron-weight-state for all possible outputs (in other words, insert math magic here).

(Side note 1: I am specifically looking at multilayer perceptrons as a kind of neural network.)

(Side note 2: For the first bulleted "possible solution", having each specific neural network and iterating through them until we receive a "Yes" response is not good enough.  I know this could be done fairly easily, but that is simple functional programming rather than machine learning.  I want to know if it's possible to have one neural network to feed the information to and receive the appropriate response.)

答:
To answer just your title, yes. Neural nets can give non-boolean answers. For example, neural nets have been used to predict stock market values, which is a numeric answer and thus more than just yes/no. Neural nets are also used in handwriting recognition, in which the output can be one of a whole range of characters - the whole alphabet, the numbers, and punctuation.

To focus more on your example - recognising animals - I'd say it's possible. It's mostly an extension of the handwriting recognition example; you're recognising features of a shape and comparing them to "ideal" shapes to see which matches. The issues are technical, rather than theoretical. Handwriting, when run through recognition software, is usually mapped down to a set of lines and curves - nice and simple. Animal faces are harder to recognise, so you'd need image processing logic to extract features like eyes, nose, mouth, rough skull outline etc. Still, you only asked if it's possible, not how, so the answer is yes.

Your best bet is probably to take a look at things like Adaptive Resonance Theory. The general principle is that the sensory input (in this case, metrics on the relative size, shape and spacing of the various facial features) is compared to a "prototype" or template which defines that class of thing. If the difference between the sensory input and the remembered template is below a certain threshold (as defined by a "vigilance parameter"), then the object being observed is assumed to be a member of the group represented by the template; if no match can be found then the system declares it to be a previously unseen type. The nice thing about this sort of net is that when it recognises that an object is, say, a horse, it can learn more about recognising horses so that it can tell the difference between, say, a standing horse and a sleeping horse, but when it sees something new, it can start learning about the new thing until it can say "I don't know what this is, but I know it's the same thing as this other thing I saw previously".

EDIT:

(In the interest of full disclosure: I'm still researching this myself for a project, so my knowledge is still incomplete and possibly a little off in places.)

how does this tie in with backpropogation setting weights for one output node ruining the weights for another, previously-trained node?

From what I've read so far, the ART paradigm is slightly different; it's split into two sections - one that learns the inputs, and one that learns the outputs for them. This means that when it comes across an input set that doesn't match, an uncommitted neuron is activated and adjusted to match the input, so that that neuron will trigger a match next time. The neurons in this layer are only for recognition. Once this layer finds a match, the inputs are handed to the layer beneath, which is the one that calculates the response. For your situation, this layer would likely be very simple. The system I'm looking at is learning to drive. This is actually two types of learning; one is learning to drive in a variety of situations, and the other is learning to recognise the situation. For example, you have to learn how to drive on a slippery road, but you also have to learn to feel when the road you're driving on is slippery.

This idea of learning new inputs without ruining previously-learned behaviours is known as the stability/plasticity dilemma. A net needs to be stable enough to keep learned behaviour, but plastic enough that it can be taught new things when circumstances change. This is exactly what ART nets are intended to solve.

OwnerDisplayName: Jeff

OwnerDisplayName: anaximander


问:
What parts of your coding standard contribute to quality code?
In response to This Question, I ask:   What are the best parts of your coding standard?

What are the best practices that help with code quality, reliability, maintainability, readability, etc.

Please include the language, the item from the standard, and the reason it improves your code.

答: Never use Hungarian Notation. In statically types languages it's unnecessary, and in dynamically typed languages it's almost always harmful. Also, Hungarian Notation is the tactical nuclear weapon of source code obfuscation techniques.</p>


答:
Short and not very rigid answer: yes every NN can provide more info than just yes, or no. It is due to threshold. If weights are higher than some threshold the answer is one of the classification classes, if it is lower the answer is the second classification class. Basically:

```<code>    0..threshold
    threshold..1
</code>```

Neuron's output is in the interval [0..1] (or [-1,1] it depends), and you don't want to get answer whether the output is lower or higher than the threshold but the output (the output you can easily convert into 0..1 interval and that means %)

Title: Can a neural network provide more than "yes" or "no" answers?

Body:
Every example neural network for image recognition I've read about produces a simple "yes" or "no" answer.  One exit node corresponds to "Yes, this is a human face," and one corresponds to "No, this is not a human face."

I understand that this is likely for simplicity of explanation, but I'm wondering how such a neural network could be programmed to give a more specific output.  For example, let's say I was classifying animals.  Instead of it saying "Animal" or "Not an animal", I would want responses like "Dog", "Fish", "Bird", "Snake", etc., with one final exit node being "Not an animal/I don't recognize this".

I'm sure this must be possible, but I'm having trouble understanding how.  It seems like due to the training algorithm of backpropogation of error, as you train up one exit node (i.e., "This is a dog") and the weights of the neurons are changed, then the ideal state for another exit node that you previously trained (i.e., "This is a bird") will begin to deviate, and vice versa.  So training the network to recognize one category would sabotage any training done for another category, thus limiting us to a simple "Yes" or "No" design.

Does this make such a recognizer impossible?  Or am I misunderstanding the algorithm?  The only two things I can think of are that:

Either we could train one neural network for each thing we want classified and somehow use those to construct a greater, super-network (so for example, a network for "dog", a network for "bird", etc., which we somehow add together to create the super-network for "animals"); or,

Create some kind of ridiculously complicated training methodology which would require incredibly advanced mathematics and would somehow produce an ideal neuron-weight-state for all possible outputs (in other words, insert math magic here).

(Side note 1: I am specifically looking at multilayer perceptrons as a kind of neural network.)

(Side note 2: For the first bulleted "possible solution", having each specific neural network and iterating through them until we receive a "Yes" response is not good enough.  I know this could be done fairly easily, but that is simple functional programming rather than machine learning.  I want to know if it's possible to have one neural network to feed the information to and receive the appropriate response.)

Body:
Short and not very rigid answer: yes every NN can provide more info than just yes, or no. It is due to threshold. If weights are higher than some threshold the answer is one of the classification classes, if it is lower the answer is the second classification class. Basically:

    0..threshold
    threshold..1

Neuron's output is in the interval [0..1] (or [-1,1] it depends), and you don't want to get answer whether the output is lower or higher than the threshold but the output (the output you can easily convert into 0..1 interval and that means %)

OwnerDisplayName: xhudik


答:
"Process Standards" is WAY beyond the scope of any possible answer here. The final outcome really depends on the industry and the customers you support. CMMI is necessary if you want to do government work. At the other extreme, look into Agile. Most likely, you'll fall somewhere in between the 2 approaches.  However, keep in mind that no matter how meticulous you define your development process, your big ball of mud will only be avoided if you have quality developers. And your quality developers will avoid that big ball of mud even without a process.  However, having a defined process is still valuable because at least having a plan and steps to follow will at least get people to attempt to do things properly and consistently; even if they aren't capable of doing it with any quality.

"Coding Standards" can be found on the internet for just about any language of choice. The only words of caution I'll add is that the more rules you have the less likely the standard will be followed. So pick the most important rules and leave it at that. Also, you really need a tool to help enforce the coding standards. And I don't mean one that will simply give warnings.  Get one that will help to automatically correct the problems (e.g. ReSharper is great) then you can have more rules because the developer doesn't need to remember all of them and it is fairly easy to adhere to the rules with a couple of mouse clicks. If you use a tool that just spits out warnings, then people will stop using the tool because they won't think the effort to correct the warnings is worth the gain.

Title: Setting up a development standardization guide for in-house/vendor programmers

Body:
I was recently hired by a large multi-national corporation to head up mobile development for their sales operation/support team. In a company of close to 10,000 people I am, at least in the America's, the only mobile developer. They are testing the waters and phase 1 (temp-to-hire) went well enough for them.

Now they are considering expanding to other developers for their other sales operations/support teams and I've been tasked with assisting/leading the writing of a standardization guide for iOS programming.

I am a big believer in giving people the freedom to work in the manner they most feel comfortable in but at the same time, I have been the creator of and on the receiving ends of big balls of mud applications. Having learned through experience I have several standards that I follow religiously such as commenting, at times almost every line - just short things but enough to let someone else know what is going on and using #pragma mark - DESCRIPTION to block off like minded methods, indentation, naming classes with a prefix to avoid name space conflicts, etc. etc.

So I guess what I am looking for is not to tell another programmer how they should iterate through an array but rather some basic standardization so anyone can jump into anyone else's project and find their way around with little learning curve. I'd love to see what other means people use to maintain control over a software development group.


问:
What is the common approach to component template databases?
My Project:

I have employees who are required to go through a checklist when they encounter a duck, a cat, and a human. In our business, we have a set number of ducks, cats, and humans that come in and out of our doors. When they come in, we have to check that all of these features are present.

The features:

Here is our current database design:

Current Approach:

When an animal enters our building, we get their ID.

Their ID gives us their animal record.

We create a new "check_in" record for the animal

Under the check_in record, we use the template given by the animal_type->feature_type relationship

For example: Sam the duck will have a new check_in created with separate feathers, wings, beak, feet, and eyes check_in_feature entries.

We go through the process and set feature_is_present to true or false for each of the features

When done, we check them out and the check_in entry is complete

My Question:

In practice, this relational schema is very hard to work with. We've used it for years and are constantly slowed down when looking up information because of the weird joins this design tends to require. I have no doubt that this is a known problem with a more elegant solution than using this naive approach. Anyone know a better way to structure this, or better approach that will be easier and more efficient to work with?

EDIT:
Just realized there are artifacts from our actual system in the navigation properties sections, just ignore those. I don't want to recreate the images if I can avoid it

答:
If the mere fact that you have multiple joins are slowing down your queries, then either your db needs tuning or you need to move to a better RDBMS that can handle your joins better.  I don't see anything wrong with your schema.

Assuming your DB supports this, my suggestion is to look carefully at query plans for your queries and look for cases where new indexes may solve your problems.  This feature is extremely db-dependent.

Finally something missing from the discussion is reporting needs.  This is something which can and frequently does rule out any non-relational solution.


问:
How to best distribute client specific configuration settings
I'm writing a WinForms desktop application which will be shipped out to several different clients and am wondering what the best way to implement a user configuration file is. Normally I would use the built in Settings.settings or app.config to store user settings but in this case what I want to store is unique for every client, I want it to be configured before sending it out and I want to avoid recompiling every time we ship to a new client.

What I want my config file to do is to store some information about the client specific graphics used in the program and some (hashed) passwords.

We don't suspect that the users would be hacking into anything in the program; we're just trying to avoid regular 'tech' level users from making changes or accessing certain modules that a manager should change. Up until now the password has been hardcoded and over a few years of use everyone has gotten to know what it is. We'd like to be in more control of what passwords go where but not necessarily give the clients control of the password changes.

I wrote a separate program that (de)serializes a configuration class to an XML file that would be put in the appropriate directory upon installation so that all people need to do (after I'm out of the picture) is have the .msi of the program, create an xml config file using this separate program, include the graphics they want in a sub folder and zip it all up. Then when the user unzips and installs, everything is put in the right place. When my program loads it looks for my config file to finish loading. If it can't find it it gives the user a change to locate it otherwise the program doesn't open.

I've been reading about the ConfigurationManager class but can't figure out how I could best use it. I haven't found much on people using outside configuration files and am not sure if my situation truly is unique or I'm not thinking inside the box enough. Is this a good design? Should I be doing this differently? If you have had a similar situation how have you solved it?

答:
We had a similar situation where I work and used pretty much your solution.  We pushed any client specific configuration into external json configuration files and load them in on program start.  What we did do was to make sure that an installer would install a working default set in case the configuration files hadn't been installed on the system yet.

I'm not sure if the ConfigurationManager class would give you any benefit either as in my experience it pretty much just gives you a nice was of serializing a configuration file.  Json/Xml/Whatever serialization is fairly well known and easy these days that it really comes down to personal choice.

The only addition that I've thought of is to store the configuration files on a webserver and retrieve them during install or first boot.  You could specify the address during install or again on first boot.  That way you don't have to supply as many files with the installer and gives you a central way to administer change to the configuration in the future.


问:
Round Table - Minimum Cost Algorithm
Problem Link - http://www.iarcs.org.in/zco2013/index.php/problems/ROUNDTABLE

It's dinner time in Castle Camelot, and the fearsome Knights of the Round Table are clamouring for dessert. You, the chef, are in a soup. There are N knights, including King Arthur, each with a different preference for dessert, but you cannot afford to make desserts for all of them.

You are given the cost of manufacturing each Knight's preferred dessert-since it is a round table, the list starts with the cost of King Arthur's dessert, and goes counter-clockwise.

You decide to pick the cheapest desserts to make, such that for every pair of adjacent Knights, at least one gets his dessert. This will ensure that the Knights do not protest.
  What is the minimum cost of tonight's dinner, given this condition?

I used the Dynamic Programming approach, considering the smallest of i-1 & i-2, & came up with the following code -

```<code>#include<cstdio>
#include<algorithm>
using namespace std;

int main() {
int n,i,j,c,f;
scanf("%d",&n);
int k[n],m[n][2];
for(i=0;i<n;++i) scanf("%d",&k[i]);
m[0][0]=k[0]; m[0][1]=0;
m[1][0]=k[1]; m[1][1]=1;
for(i=2;i<n;++i) {
                 c=1000;
                 for(j=i-2;j<i;++j) {
                                    if(m[j][0]<c) { c=m[j][0]; f=m[j][1];}
                 }
                 m[i][0]=c+k[i]; m[i][1]=f;
}
if(m[n-2][0]<m[n-1][0] && m[n-2][1]==0) printf("%d\n",m[n-2][0]);
else printf("%d\n",m[n-1][0]);
}
</code>```

I used the second dimension of the m array to store from which knight the given sequence started (1st or 2nd). I had to do this because of the case when m[n-2]<m[n-1] but the sequence started from knight 2, since that would create two adjacent knights without dessert. The problem arises because of the table's round shape.

Now an anomaly arises when I consider the case - 2 1 1 2 1 2. The program gives an answer 5 when the answer should be 4, by picking the 1st, 3rd & 5th knight. At this point, I started to doubt my initial algorithm (approach) itself!

Where did I go wrong?

答:
I think your algorithm does not work because the table is circular. But we can solve this using a different dynamic programming approach.

Let array 'C[]' store the costs of the desserts of each knights. We have to consider two things:

W[i], The cost of including the ith knight

_W[i], The cost of not including the ith knight, in this case we have to include its neighbours.

Let us forget about the table being circular for a while. As we are moving forward in each iteration _W[i] stores only the cost of including the left neighbour of 'i'.

For a particular knight 'k', we can compute W[k] and _W[k] in constant time by using the already computed values of W[k-1] and _W[k-1].

If we dont include knight 'k', we have to include knight 'k-1' so that at least one of them gets his dessert. Therefore _W[k] will be equal to the cost of including knight 'k-1', which is W[k-1].

If we choose to include knight 'k', we have two choices, either include 'k' and 'k-1' both, or include 'k' and not 'k-1'. We take the minimum of the two.

Now we have:

_W[k] = W[k-1]

W[k] = C[k] + min(W[k-1],_W[k-1])

So, if we know the value of _W[0] and W[0] then we can compute the W, and _W values for all knights upto N.

We know W[0] will be equal to C[0]. _W[0], the cost of not including knight 0, will be the cost of including its left neighbour which, if we come back to the original problem is C[N-1].

But what will happen if W[1] is chosen as _W[0] + C[1] where _W[0] is C[N-1]? We might consider knight N-1 twice.

To overcome this problem we check if C[N-1] < C[0], if it is then we know that knight N-1 will be chosen so we decrease N by one and therefore delete the last knight.

The final answer will be the minimum of W[N-1] and _W[N-1]

If you need the pseudocode:

```<code> W[0] = C[0]
_W[0] = C[N-1]

   if C[N-1] < C[0]:
         then N = N-1

   for i from 1 to N-1:
       W[i] = C[i] + min(W[i-1],_W[i-1])
       _W[i] = W[i-1]

   return min(W[N-1],_W[N-1])
</code>```

As you do constant amount of time in each iteration the time complexity is O(N), which will run well within the time limits of your problem.

Title: Round Table - Minimum Cost Algorithm

Body:
I think your algorithm does not work because the table is circular. But we can solve this using a different dynamic programming approach.

Let array 'C[]' store the costs of the desserts of each knights. We have to consider two things:

W[i], The cost of including the ith knight

_W[i], The cost of not including the ith knight, in this case we have to include its neighbours.

Let us forget about the table being circular for a while. As we are moving forward in each iteration _W[i] stores only the cost of including the left neighbour of 'i'.

For a particular knight 'k', we can compute W[k] and _W[k] in constant time by using the already computed values of W[k-1] and _W[k-1].

If we dont include knight 'k', we have to include knight 'k-1' so that at least one of them gets his dessert. Therefore _W[k] will be equal to the cost of including knight 'k-1', which is W[k-1].

If we choose to include knight 'k', we have two choices, either include 'k' and 'k-1' both, or include 'k' and not 'k-1'. We take the minimum of the two.

Now we have:

_W[k] = W[k-1]

W[k] = C[k] + min(W[k-1],_W[k-1])

So, if we know the value of _W[0] and W[0] then we can compute the W, and _W values for all knights upto N.

We know W[0] will be equal to C[0]. _W[0], the cost of not including knight 0, will be the cost of including its left neighbour which, if we come back to the original problem is C[N-1].

But what will happen if W[1] is chosen as _W[0] + C[1] where _W[0] is C[N-1]? We might consider knight N-1 twice.

To overcome this problem we check if C[N-1] < C[0], if it is then we know that knight N-1 will be chosen so we decrease N by one and therefore delete the last knight.

The final answer will be the minimum of W[N-1] and _W[N-1]

If you need the pseudocode:

 W[0] = C[0]
_W[0] = C[N-1]

   if C[N-1] < C[0]:
         then N = N-1

   for i from 1 to N-1:
       W[i] = C[i] + min(W[i-1],_W[i-1])
       _W[i] = W[i-1]

   return min(W[N-1],_W[N-1])

As you do constant amount of time in each iteration the time complexity is O(N), which will run well within the time limits of your problem.


问:
Why do some programmers keep values in global variables or member variables but not reused?
I am talking about normal PC applications, memory should be sufficient.

They declare global or member variables.

In each function/method, they use the same global/member variables.

At the beginning of each method, the variables are re-initialized so the old value is never used.

Why do they keep the variables but no chance to reuse the old value?

```<code>class A
{
    List<Car> carList;
    public List<Car> M()
    {
        // always re-init variable
        this.carList = new List<Car>();
        // ...
        // fetch from DB
        return this.carList;
    }

    public List<Car> N(string id)
    {
        // always re-init variable
        this.carList = new List<Car>();
        // ...
        // fetch from DB
        return this.carList;
    }
}
</code>```

答:
They think that they are escaping declaring variable every time in each function. But this is not good programming habit to keep global variable if you every time initialize value.
Life cycle of global variable may lead to bad memory management in this case


问:
Software Requirement Specification documentation by professionals
I just wanted to know what is the significance of SRS(Software Requirement Specification) in programming? and what are the techniques used in preparation of an SRS .. also who writes the SRS.. is it the programmers?</p>

答:
It is a prefect detailed decription of the behaviour of the system to be developed.
SRS docuent is an agreement between the developer and the customer covering the functionak and non functional requirements of the software to be developed.</p>


问:
'import module' vs. 'from module import function'
I have always been using this method:

```<code>from sys import argv
</code>```

and use argv with just argv. But there is a convention of using this:

```<code>import sys
</code>```

and using the argv by sys.argv

The second method makes the code self documented and I (really) adhere to it. But the reason I prefer first method is it is fast because we are importing only the function that is needed rather than import the whole module (which contains more useless functions which python will waste time importing them). Note that I need just argv and all other functions from sys are useless to me.

So my questions are. Does the first method really makes the script fast? Which method is preferred most? Why?

答:
Although import sys and from sys import agrv both import the entire sys module, the latter uses name binding so only the argv module is accessible to rest of the code.

For some people this would be the preferred style since it only makes accessible the function you explicitly stated.

It does however introduce potential name conflicts. What if you had another module named argv? Note you can also explicitly import the function and rename with from sys import argv as sys_argv, a convention that meets the explicit import and is less likely to gave name space collisions.


答:
CONSISTENCY

I'm not bothered by any particular naming or coding conventions (though, I obviously have preferences) as long as whatever codebase they're applied to uses those conventions consistently.

I've been going through Clean Code lately, and I find that it's helped me a fair bit (though I don't agree with/use all of it).

Title: What parts of your coding standard contribute to quality code?

Body:
In response to This Question, I ask:   What are the best parts of your coding standard?

What are the best practices that help with code quality, reliability, maintainability, readability, etc.

Please include the language, the item from the standard, and the reason it improves your code.


答:
In your example, it might likely be bad to keep the old value. If you have constructed one list of cars in N and returned that list to caller A, and then caller B makes a request using M, and M cleared the same list and populated a different set of cars, wouldn't caller A perhaps be confused when suddenly the list mutated? It is more likely that Greg Hewgill's comment to your question is entirely valid, it never should have been member state in the first place.

What you see there is just a symptom of what often accompanies this, and that is a large class with members at the the wrong layers of abstraction, a class that is probably doing too much for too many people and can often sprawl to the point of being indecipherable. If, on the other hand, reinitialized member state is your only problem with the class, then maybe you're better off than those of us who have seen and worked with far worse.

Title: Why do some programmers keep values in global variables or member variables but not reused?

Body:
I am talking about normal PC applications, memory should be sufficient.

They declare global or member variables.

In each function/method, they use the same global/member variables.

At the beginning of each method, the variables are re-initialized so the old value is never used.

Why do they keep the variables but no chance to reuse the old value?

```<code>class A
{
    List<Car> carList;
    public List<Car> M()
    {
        // always re-init variable
        this.carList = new List<Car>();
        // ...
        // fetch from DB
        return this.carList;
    }

    public List<Car> N(string id)
    {
        // always re-init variable
        this.carList = new List<Car>();
        // ...
        // fetch from DB
        return this.carList;
    }
}
</code>```


答: Its not a good practice. Local variables should be used, if you are re-initialize the global variable every time in function. Global variables shoud be used if you want to retain the old values.</p>


答:
It's impossible to know the motivations behind this code given a single point in time. It could be the result of wear-and-tear on the class.

Imagine, for instance, that once the car list really did function as a member variable, with some methods modifying it and some retrieving it. Then, some bugs were discovered that were caused by different methods modifying the value at the wrong time - perhaps the introduction of multithreaded execution. Now the programmer went and changed all car-list-generating methods to return the list, rather than store it in the member variable. But people often change the minimum amount required to get things working, especially if rushed and working on a critical bug, and rather than creating a local varible, he just left the existing reference to the member variable. Voila!


答:
@anaximander's answer is pretty good, I thought I'd comment on this part of your question:

It seems like due to the training algorithm of backpropogation of error, as you train up one exit node (i.e., "This is a dog") and the weights of the neurons are changed, then the ideal state for another exit node that you previously trained (i.e., "This is a bird") will begin to deviate, and vice versa. So training the network to recognize one category would sabotage any training done for another category, thus limiting us to a simple "Yes" or "No" design.

Well, I think your assumption is wrong here; if I understand correctly, you have an NN with one output per category you're trying to classify.  Ideally, you'd like them to operate almost independently, so that the "dog" and "bird" classification don't fire at the same time.  So really, during training, what will happen is that when you are training the NN with a "dog" result, backpropagation will try to ensure that the "bird" and other output neurons don't produce false positives.  So, theoretically, it will work just fine, contrary to your comment; the reinforcement of a negative outcome for "bird" is correct.

However, your problem will be the scalability of this approach.  As you add more categories to the network, the training will become more complex in at least a linear (but likely far worse) manner.  For this reason, many people use an approach where individual NNs are trained for each category; this keeps things simple enough and relatively scalable.  The meta-level of how these are combined are then up to you.  You could simply loop through all NNs and see which ones produce positive outputs, you could create mid-level heuristic NNs which try to narrow down the type of animal for you, or you could even have a giant NN which combines the individual NNs as neurons.  In essence, what I am trying to say is that you have prior knowledge of the structure of the problem - the individual classifications are most likely distinct from each other; you can let a giant NN figure that out for itself (but it might not work well with today's technology), or you can architect your NNs by hand to reflect this, which may yield better results.

EDIT:  To answer the title question, of course NNs can provide more than yes / no answers.  In the "standard" models, each output neuron typically fires yes / no (although this behaviour could be changed, if you were so inclined), representing one bit of information; but just as with your computer, bits can be combined to provide a range of discrete values, which can be interpreted any way you wish to.  A fairly visual example of non-binary outputs would be a Self-Organising Map, which typically have a 2D output.


答:
It could be that you've got something like this:

```<code>class A
{
    List<Car> carList;
    public List<Car> M()
    {
        // always re-init variable
        this.carList = new List<Car>();
        // the following functions modify carList
        sortTheCarList();
        filterTheCarList();
        frobnicateTheCarList();
        return this.carList;
    }
}
</code>```

It possible that it at least makes sense. Although I still think its bad style to do it this way.

Body:
It could be that you've got something like this:

class A
{
    List<Car> carList;
    public List<Car> M()
    {
        // always re-init variable
        this.carList = new List<Car>();
        // the following functions modify carList
        sortTheCarList();
        filterTheCarList();
        frobnicateTheCarList();
        return this.carList;
    }
}

It possible that it at least makes sense. Although I still think its bad style to do it this way.


问:
What is the most cross-browser/system compatible option for 3d graphics on a web page?
I would like to develop a bit of functionality for a web site that involves a bit of 3D - the user can move around objects, rotate them and texture them.

So far I've looked into:

WebGL (in particular three.js) and it looks great, but it's not supported in IE nor IOS.

IOS supports the <canvas> tag, but only 2d. It looks like three.js has an unsupported hack to make a 3d thing use the 2d canvas instead without textures, but this looks like a hack.

I also considered resorting to Flash which works on most browsers, but that won't work on IOS.

What's my best option for doing 3d web graphics on the vast array of browsers and interfaces?

At the moment I'm thinking WebGL for web (and ask people to use chrome or firefox, and take the hit on IE) and then maybe write a native app for IOS, but I am not sure if there are better alternatives available that I don't know of.

答: Unity has a huge array of platforms that it supports (browsers, flash, and iOS included). http://unity3d.com/unity/multiplatform/</p>


答:
Related to github this one might be an interesting solution:
http://huboard.com

Huboard is a solution based on the API of Github. It uses the real GitHub issues as you are familiar with when using GitHub.

It allows you to sort and manage the tasks by dragging them.

Because they are from the API it means all data is the actual GitHub data. So if you commit to close a task it will also be closed in Huboard. That makes it special, it's really the real data without synchronisation issues.

Title: Software for prioritising issues / tasks in an ordered list/queue (ideally in Github)?

Body:
It seems to me that the best way to manage priority for programming tasks in a backlog is to simply put them in order. Do the top task first, second one next. If priority changes, re-order the queue. I thought this was exactly how things were supposed to work in Agile.

I have yet to find an online open-source team task manager that supports custom ordering of tasks this way - although I might be out of date. Assembla definitely doesn't. Jira doesn't seem to. When we used Agilo in my previous company, it didn't seem to either. The only service I've found that implements this simple concept well is Google Tasks, but that's hardly suitable for managing software projects.

I don't understand why this isn't the standard way to manage priority.

My ideal way to track issues would be through Github. As far as I can tell Github Issues also doesn't support custom ordering of tasks. Does anyone know if there's any way to implement this on top of Github Issues somehow? Is there any way I can suggest it as a feature?


问:
Checking "instanceof" rather than value using a switch statement
Is there some syntax (other than a series of if statements) that allows for the use of a switch statement in Java to check if an object is an instanceof a class?  I.e., something like this:

```<code>switch (object) {
     case instanceof SecondObject:
        break;
     case instanceof ThirdObject:
        break;
}
</code>```

Sidenote:  I recognize that as a design pattern, checking against instanceof and making decisions based on it is not as preferable as using inheritance.  To give some context why this would be useful to me, here's my situation:

I'm working on a project that involves a kryonet client/server.  For communication over KryoNet, you pass objects that it serializes using kryo.  Anything added to the object increases the size of these packets,1 so to minimize the network traffic, you keep these objects as light weight as possible.  When you receive a packet, you need to know what to do with it, so I'm making this determination based on what type of packet object the passed object is an instanceof.  This approach is the same undertaken in the examples included with Kryonet's distribution.  I'd love to clean up the hideous class that translates these packets into action, and figure a switch statement would at least make it look moderately more organized.

1As I wrote the statement above, I had doubts about whether what I was saying was accurate. The answer below seems to disagree:

Methods don't add anything to the runtime size of an object. The
  method code is not transmitted, and nothing about the methods requires
  any representation in an object's state. This is not a sound reason
  for instanceof testing, etc.

I guess the real issue is I don't know what happens under the hood for Kryo to serialize an object and I was nervous to do anything that increased the bandwidth.  Your answers have inspired me to do it with inheritance and add the appropriate methods to the objects.  So thank you!

答:
No, and it's very unlikely that such a thing will be added.

You see, checking for the type of an Object and then doing different things for different types is considered terribly inelegant, because there already is a much better pattern for doing that: using inheritance and overridden methods. (Granted, that's only of use when the "do something" can be formulated as a method call on the checked Object, but usually it can.)


问:
Should you version web applications?
I've recently had a discussion with a coworker about versioning web applications.

I don't think you need it at all, and if you just want a sanity check to confirm your latest release is live, I think a date (YYMMDD) is probably good enough.

Am I off base?  Am I missing the point?  Should I use web application version numbers

答:
Yes, you should version it! And there should be a tag in your revision control system (like subversion, git, mercurial, etc.) that matches the version number.

The tag allows you to go back and make a branch. For example: the current production version has a bug, but you can't fix it because the code on your machine just isn't ready to roll out the door. If you have it tagged in your RCS though, you can branch at that tag and fix the bug in the exact version of the code that's running in production.

Title: Should you version web applications?


答:
The answer is no.

But using Java 7 you could do this:

```<code>switch (object.getClass().getName()) {
  case "some.pkg.SecondObject":
    break;
  case "some.pkg.ThirdObject":
    break;
}
</code>```

... which is not exactly the same, but may be close enough.

The problem is that this is "code smell", whether you do it using if ... instanceof tests or the switch hackery above.

Why?

Because any time you add a new class, you need to revisit all of the places where you do this class testing!!  And there is the added problem that the code breaks if you rename the classes.

The recommended OO approach is to use polymorphism.

Anything added to the object increases the size of these packets, so to minimize the network traffic, you keep these objects as light weight as possible.

Methods don't add anything to the runtime size of an object.  The method code is not transmitted, and nothing about the methods requires any representation in an object's state.  This is not a sound reason for instanceof testing, etc.

Title: Checking "instanceof" rather than value using a switch statement

Body:
Is there some syntax (other than a series of if statements) that allows for the use of a switch statement in Java to check if an object is an instanceof a class?  I.e., something like this:

```<code>switch (object) {
     case instanceof SecondObject:
        break;
     case instanceof ThirdObject:
        break;
}
</code>```

Sidenote:  I recognize that as a design pattern, checking against instanceof and making decisions based on it is not as preferable as using inheritance.  To give some context why this would be useful to me, here's my situation:

I'm working on a project that involves a kryonet client/server.  For communication over KryoNet, you pass objects that it serializes using kryo.  Anything added to the object increases the size of these packets,1 so to minimize the network traffic, you keep these objects as light weight as possible.  When you receive a packet, you need to know what to do with it, so I'm making this determination based on what type of packet object the passed object is an instanceof.  This approach is the same undertaken in the examples included with Kryonet's distribution.  I'd love to clean up the hideous class that translates these packets into action, and figure a switch statement would at least make it look moderately more organized.

1As I wrote the statement above, I had doubts about whether what I was saying was accurate. The answer below seems to disagree:

Methods don't add anything to the runtime size of an object. The
  method code is not transmitted, and nothing about the methods requires
  any representation in an object's state. This is not a sound reason
  for instanceof testing, etc.

I guess the real issue is I don't know what happens under the hood for Kryo to serialize an object and I was nervous to do anything that increased the bandwidth.  Your answers have inspired me to do it with inheritance and add the appropriate methods to the objects.  So thank you!

Body:
The answer is no.

But using Java 7 you could do this:

switch (object.getClass().getName()) {
  case "some.pkg.SecondObject":
    break;
  case "some.pkg.ThirdObject":
    break;
}

... which is not exactly the same, but may be close enough.

The problem is that this is "code smell", whether you do it using if ... instanceof tests or the switch hackery above.

Why?

Because any time you add a new class, you need to revisit all of the places where you do this class testing!!  And there is the added problem that the code breaks if you rename the classes.

The recommended OO approach is to use polymorphism.

Anything added to the object increases the size of these packets, so to minimize the network traffic, you keep these objects as light weight as possible.

Methods don't add anything to the runtime size of an object.  The method code is not transmitted, and nothing about the methods requires any representation in an object's state.  This is not a sound reason for instanceof testing, etc.


问:
Shouldn't SVN warn me if I'm about to commit files which have newer versions in the repository?
We use SVN and PhpStorm at work. Recently our team has grown a bit so there are several people working on the same project at a time, sometimes on the same file. We've run into the problem where people don't update before comitting and overwrite the changes that were made by someone else. This is a hassle. I don't know SVN very well, but it seems like this shouldn't even be possible. What are we doing wrong?</p>

答:
SVN will not just warn you, it will outright refuse the commit. Then you have to do an update, handle any merge conflicts, typically by explicitly marking any conflicted files as "merged", and only then can you commit.

Of course, it's possible to have a client that does all this silently and just overwrites conflicted files. Such a client would be considered seriously broken and worse than useless. I doubt PHPStorm does that. Most likely, the developers don't know how to handle merge conflicts and just incorrectly mark the files as "merged" to get SVN to "work".