答:
Having these abstractions implemented as interfaces allows more flexibility.

Interfaces allow programmers to use multiple inheritance of type in Java. This way you can treat any class as an instance of the interface regardless of its inheritance hierarchy.

You can implement any number of interfaces in a single class but you can only have a single superclass (as expressed by the extends keyword).

At the same time, nothing prevents you from providing a skeletal implementation of any given interface. Just write an abstract class implementing it and use it as you please. You still have a single place to put the common parts and you don't make the clients of your API dependent on any actual implementation.

Besides, lists can have vastly different implementations and the details of the core behaviours can rely on mechanisms that are not at all similar.

Take a look at LinkedList and ArrayList for example.

The first one is backed by a number of interlinked objects. The latter stores its elements in an array. The way you access elements of these data structures is simply different. The effect of these operations is identical (and understandably, both these collections implement the List interface) but the actual behaviour, the algorithms used to perform those operations are not really common.

Coincidentally, these concrete classes also have abstract superclasses that serve as their skeletal implementations. LinkedList is an instance of List and AbstractSequentialList while ArrayList is a List and an AbstractList

List is an interface because of how general it is. It does not assume anything about implementation. AbstractSequentialList and AbstractList on the other hand do assume certain ways of element access. Hence they're implemented as abstract classes.

In response to the very beginning of your question

While defining the hierarchy, one can think to embed the abstract method(behaviour) in abstract class only because the derive concrete class posses that as core behaviour with it's specific implementation, one can think to embed the abstract method(behaviour) in interface only because derived concrete class does not posses that as core behaviour(but as peripheral) having it's specific implementation.

Above definition can be understood well with this example

One of the good reference also supports this point:

It's true that implementing multiple interfaces in a single class allows you to combine possibly unrelated sets of behaviour, or as you express it, peripheral behaviour but this is just a use case rather than the purpose of interfaces in its entirety.

Using interfaces to create mixins is a great use case for them and the only way to have multiple inheritance in Java but you're free to use interfaces outside this context.

It's perfectly valid to use an interface to define a set of core behaviours for a family of classes. In this case, I wouldn't say it is used as a mixin. It just defines a contract. At the same time, it can be used as a mixin by any other class if the programmer so desires. This is a matter of naming and the context in which you use these concepts.

The distinction between core and peripheral behaviour is completely separate from the distinction between classes and interfaces. What truly makes the difference here is that the set of implemented interfaces specifies what you can do with an object while the classes (abstract or not) in its inheritance hierarchy define how these things are to be done.

An abstract class with all its methods declared as abstract is just like a poorly implemented interface with its usage severely limited by the lack of capability regarding multiple inheritance of type.

Title: Why 'List<E>' is an 'interface' but not 'abstract class'?

Body:
Amidst defining the hierarchy, firstly,  one can think to embed the abstract method(behavior) in abstract class only because the derive concrete class possess that behavior as core behavior with it's specific implementation, secondly, one can think to embed the abstract method(behavior) in interface only because derived concrete class possess that behavior as non-core behavior(peripheral) having it's specific implementation.

As I would not rely on this example which supports above point, below are the two references, I would rely on.

1) First reference that supports this point:

Interfaces are ideal for defining mixins.  Loosely speaking, a mixin is a type that a class can implement in addition to its "primary type" to declare that it provides some optional behavior.  For example, Comparable is a mixing interface that allows a class to declare that its instances are ordered with respect to other mutually comparable objects.  Such an interface is called a mixin because it allows the optional functionality to be "mixed in" to the type's primary functionality.  Abstract classes can't be sued to define mixins for the same reason that they can't be retrofitted onto existing classes: a class cannot have more than one parent, and there is no reasonable place in the class hierarchy to insert a mixin.

2) Second reference that support this point:

In UML sketch, the relation between interface model and concrete class model is named Realisation, where as, the relation between abstract class model and concrete class model is named is-a relation. Here is-a can be told, when concrete class has core behavior unlike realisation relation.

So, with these two references, It looks list<E> and Collection<E> are abstract class but not interface.

With this above explanation, I would like to understand,

Why Collection<E> and List<E> is designed to be interface in  java.util package?

Is my understanding correct?


问:
Documenting higher-level concepts
I will be leaving my current project in a few days, and as part of securing my knowledge I have been asked to add comments to the code wherever I feel that can add value.

The problem I am running into now is that the comments I want to write are not really suitable as comments, because they do not pertain to a single entity in the code (a few lines, a function, a class or even a file), but they are more about how two or more entities interact with each other or about a feature whose implementation is spread over multiple entities.

So, how do you go about documenting the stuff that does not belong to a single entity but is important to know to understand the bigger picture?

And also: Where do you document it? In the source file or in an external document?

As an example, we have a client-server architecture in C (with the client and server both running on the same embedded device). To avoid flooding the server, the client has a mechanism to throttle the sending of similar requests to the server such that a request can only be sent if the previous one has been answered.

The innards of this mechanism are spread over multiple functions.

Where would you place the documentation of such a feature, especially if the file with the functionality also has some other, unrelated, functions?

Edit: Extended the question a bit.

答:
Describe the system through tech articles which address certain scenarios, depict problem solving ways and so on.

Install a wiki and put the articles online so that the other team members can edit them later.

ContentLicense: CC BY-SA 3.0

Title: Documenting higher-level concepts

ContentLicense: CC BY-SA 2.5


问:
Why were punch cards used for programming
I am doing a research essay on the history of programming languages, and I was wondering, why did programmers ever write their programs on punch cards? Didn't computer screens and keyboards already exist by the time programmers used them?

I know they were first invented for the use of the Jacquard loom and to control the desired design, but when people programmed, why did they decide to write their programs on a card oppose to writing it on a terminal?

Was it because since computers were very expensive, not many people had access to them, resulting in people writing programs on punched cards, submitting it to a company or someone or some organization that had one to run them and tell them the result?

答: Computer time was extremely expensive back then, so anything that could be offloaded typically was.</p>

OwnerDisplayName: Jwags

OwnerDisplayName: dave


答: Computers did not start off as you see them today, obviously. They were more mechanical. A punch card is used to mechanically represent binary numbers. A mechanical reading head which moves over the punch card reads a "hole" or a "no hole". These combinations of holes and no holes can be used to control the behavior of a mechanical device. There by, we have a program to control something!</p>

Title: Why were punch cards used for programming

Body:
I am doing a research essay on the history of programming languages, and I was wondering, why did programmers ever write their programs on punch cards? Didn't computer screens and keyboards already exist by the time programmers used them?

I know they were first invented for the use of the Jacquard loom and to control the desired design, but when people programmed, why did they decide to write their programs on a card oppose to writing it on a terminal?

Was it because since computers were very expensive, not many people had access to them, resulting in people writing programs on punched cards, submitting it to a company or someone or some organization that had one to run them and tell them the result?

OwnerDisplayName: Sunil D S


答: Punched cards served not only as an input/output medium, but also as a long-term storage device. You could run a program more than once by reloading the card deck for that program. There were no hard drives, no floppy drives, no magnetic tapes.</p>

OwnerDisplayName: Ferruccio


答:
I am so old I have used punched cards (and "editable" mark sense cards - pencil to mark + eraser to edit!) at Uni, and we submitted the deck of cards as our assignment. There was not a keyboard or terminal in sight. And it wasn't that long ago: the 80's.

Where do you think the usage of the term "to punch in data" came from (although, see below)? There was a job title "key punch operator" - essentially a typist that sat at a card punching machine and "punched" in code/data.

IBM still refers to a JCL program as a "deck", and each line has a maximum of 80 characters - why? Because a standard punch card had 80 columns, and on their original computers, the operator would put a deck of cards (a program) in the input hopper to run it. The OS (MVS) was locked (due to IBM's promise of backward compatibility) to an ancient hardware limitation.

Q: What's the difference between a drummer and a drum machine?

A: With a drum machine, you only have the punch the information in once.


问:
Domain/Model objects attributes good practices
Simple question: Should model/domain objects only include attributes that are meant to be persisted in a database or serialized to any other specific format?

My understanding of a domain/model object is that it should reflect the data store (the model) as tightly as possible, rather than carrying "off-topic" attributes.

Am I on the right track?

答:
It depends. Starting with persistent-only attributes is the most typical approach, and adding non-persistent attributes should typically be an exception. But such a decision is always a trade-off, and where you draw the line depends on the responsibilities you assign to that object. Some typical reasons for adding non-persistent attributes:

you need them for an operation which clearly belongs to the object, and holding them within the object turn out to be much simpler than using a second object (note that a second object needs its lifetime to be manage separately)

you see an opportunity to keep the API of your domain model as simple as possible

you need an option for storing this additional, temporary information without changing too much code in an existing program, and you are sure using a different class or objects will have a too big impact

performance reasons (assumed you have a real, measurable performance bottleneck, which can be most easily solved by caching some data in your object)


答:
The weight of history...

Lets go back to the Jacquard loom, a mechanical loom invented over 200 years ago.

The loom was controlled by a "chain of cards", a number of punched cards, laced together into a continuous sequence.

This was a known technology and later on the US Census Bureau used a tally machine - the Hollerith machine to tally census data. Which was collected using punch cards.

Herman Hollerith's tabulator consisted of electrically-operated components that captured and processed census data by "reading" holes on paper punch cards

These early tally machines later evolved into computers - but the input method remained the same.

Screens existed, keyboards exists (typewriters), but the idea of hooking those up to a computer? That took some time.

Additionally, punch cards were not just the running program - they were the actual data as well - the storage medium. There were no hard drives, no magnetic tape.


答:
Time-sharing, multi-user, systems were invented in the late fifties, but they were comparatively rare through all through the 60s. Most computers ran in batch mode, running a single program at a time, with no facilities for interacting with users other than the card reader, the line printer, and maybe a separate teletype for the console operator. Terminals you say? Up until the late 60s, electronic terminals with video displays were exotic, fabulously expensive gadgets limited to research facilities and specialized jobs like air traffic control, and national defense. Those computers that did support interactive sessions generally used teletypes. Entering a program on a teletype was just as unpleasant as punching it onto cards.

Let me expand a little bit on the problem of batch processing since it is so foreign to the way most people use computers now. It would certainly have been possible even in the 50's to write an interactive editing program that would have worked with a teletype. However, because of batch processing, the editing program would have completely monopolized the computer the entire time you were sitting at the teletype editing your program. Since several hundred to several thousand other people would have been waiting their turn to run their programs, you would have been a very unpopular person. You would also have been charged several dollars a minutes while your editor was running. It was much more cost-effective to write your program out in long hand, hand the final draft to a key punch operator, and let them transcribe your program onto punch cards or paper tape. That avoided wasting the CPU's precious milliseconds waiting for you to type 'GOSUB'.

Hard disk drives were also invented in the late fifties, but they were small (around 1mb), rare and expensive, not something you gave users casual access to. Obviously users did need some sort of long term storage. The choices were paper tape, punch cards and magnetic tape. Magnetic tape was new and expensive. Paper tape was used by some systems, but punch cards were an established technology used in non-computer business machines like tabulators and sorters since 1928, so a lot of businesses already had a major investment in punch card machinery and storage.

ContentLicense: CC BY-SA 4.0


问:
Versioning business rules

TL;DR

Storing ever-changing business rules so that an app can behave like it did at moment X in the past. Can it be done? If so, how?

Long version

At this very moment, this is more of a thought exercise than an actual need, though things could change in the not so distant future.

The company I work for is in the payroll business. We have desktop app whose job is mainly to figure out the amount of the salary an employee will receive.
In Italy this is a job in and of itself, because things change literally each month, with new taxes, merges of old ones, different calculations needing to be made. In short it's a terrible, terrible mess.

Not that it makes any difference, but this is a COBOL app (don't ask) and it's quite huge, clocking in at an estimated 5M LOC. Also, saying that instead of being badly designed it has no underlying design whatsoever would be putting it mildly.

For who knows what reason, customers need to be able to recalculate past payrolls. Of course, they need the program to behave like it did in that precise month.

A little aside: personally, this makes no sense at all to me, because once you paid the guy, the only thing you might be able to do is to adjust things next month, and keeping the resulting data (which is not just the salary, but thousands of other pieces of information) in an archive for later queries would be the most trivial of exercises. Then again, I don't have anything to do with the day-to-day maintenance of this app, so the precise reasons behind these requirements might just be escaping me because of that. I might be involved at least in part with the design of a major overhaul of the whole thing, though, and that's why I'm writing this question.
So, let's assume this is an actual requirement.

So what this app does each month is it copies all of the sub-apps it is composed of into a new folder, along with a complete copy of its data. A copy of almost everything, which ends up eating a tremendous amount of space on the customers' machines.

It doesn't use a database, it's still stuck with indexed files (again, don't ask).

Now the question: how would you design this if you could just start over? Whether it's turning it into a web application or making yet another desktop app, I am more interested in the conceptual side of things.

How would you design an app that needs to keep business rules versioned and reapply old ones on demand?

Now it can be done easily because they actually copy the whole shebang once per month, and every piece of data is stored in indexed files.

With a properly designed app, though, I wouldn't know how to approach this in an elegant way: database schemata tend to change, for instance, and making a copy of the whole thing each month would just be a nightmare.

But the crux of the matter is versioning business rules: can it even be done? One thing I would do for sure would be of course pulling them out of the actual code and into a set of scripts, because now, as in the best COBOL tradition, everything is hard-wired in the code, so they recompile and ship even if a simple calculation has changed.

Where to go from there, though, is a bit of a mystery.

答:
The difficulty is that you have to deal with already complex rules which change every month. I would think of two techniques which can be used to mitigate some complexity:

Don't store historical rules in code. Unless there are a lot of accounting errors and your company needs to recalculate the payroll often, you don't need to keep all this complexity.

At the same time, for audit, you can build an engine which builds a report of the current rules for a specific employee, i.e. a more or less programmatic, more or less humanly-readable piece of data which shows how the specific salary was determined.

Storing those final reports will not waste a lot of space and would give enough information in a case where an employee believes he was underpaid.

Don't handle every possible case. It may be just too expensive to maintain the code, much more expensive than to pay an accountant who will do by hand the same work as the piece of software.

If:

It takes 30 minutes for an accountant to compute the salary of an employee by hand,

Your company has 600 employees, 10 having a specific status which requires to apply some complicated business logic,

It takes two days to implement those complicated business rules,

then you'd better to keep them out of your code and focus on simple situations. If you spend more time developing a feature than it saves to your customers, don't develop it.

If you really need to keep all the business rules for every past month, you may be interested by plugin architecture, with plugins being loaded on demand by the application (for example the plugin September2014 loaded when you need to create the payroll for September 2014). This will ensure you keep the application clean and keep the rules for a specific month as simple as it is possible to keep. The drawback is that you may have a lot of code duplication.

Note that in this case, using document-based NoSQL instead of ordinary SQL systems with a strict schema can help. With ordinary SQL, once you change the schema, old plugins may stop working. With NoSQL, you're free to store whatever you want in different documents corresponding to different months; you can still use legacy plugins, with the only limitation of not being able to load with old plugins documents stored with new plugins (but why would you do that?)

Title: Versioning business rules


问:
Why isn't it possible to switch between header and cpp in Visual Studio?
For the last eight years I wait for Microsoft to add the basic C++ functionality of switching back and forth between .h and .cpp files, and it keeps astonishing me it is still not supported in Visual Studio 2010. Does anyone know why they refuse to add this essential feature?  </p>

答: Visual Assist does it, but also offers you to open any file in your solution which has a name that includes the substrings you give.  Extremely useful in my opinion: I always use it, but very hardly use the 'jump to header/source' command...</p>


答:
[W]hy did programmers ever write their programs on punch cards? Didn't computer screens and keyboards already exist by the time programmers used them?

We use whatever i/o mechanism our computers have. In the 1960s, paper tape was common. In the 1970s (when I started programming), paper tape was being replaced by punched cards.

Yes, there were machines with teletypes, and also astonishing things called VDUs. But they were not in the mainstream yet. Both of these technologies were more commonly used by the (mainframe) computer operators; rarely for us.

At the peak of the punch-card era, the most common machine was the IBM029

In that image, students are punching in their own code. Professional programmers more commonly wrote their code by hand on coding sheets, formatted according to the language you were coding in.

We would send our coding sheets off to the data center, where operators would punch them in (at blinding speeds), and then pass the cards to the verify operator. She (90% of data center staff were women; only their managers were male) would type your code again, with the punch machine set to verify mode. The machine would ding if what she was typing was different from what was on the card already. By doing it twice, they achieved speed and accuracy.

When you got your cards back, the first thing you would do was draw a diagonal line across the top of the entire deck. Woe betides if you dropped your cards before doing that! With the line drawn you had a fighting chance of getting your cards back in order after dropping them.

A lot of program editing consisted of inserting new cards, which we would usually punch ourselves, and moving existing cards to another place in the deck. Obviously, the diagonal line you draw originally would now be less useful, so after a few edits, you would draw another line. When the cards were getting too many lines or were starting to produce read errors on the card reader (the fastest readers worked at 1200 cards per minute and higher, so cards took a pounding each time they were read), you would send your deck back to the data center to be duplicated.

Small edits could be performed using a hand punch.

With experience, you would learn the Hollerith code for each character and could punch as fast as using a keyboard.

If no one senior was watching when you made an error, you could fill the wrong hole with a "chad" that had been punched out of the card, rubbing it with your thumbnail so that its edges meshed with the rest of the card. Such patches often came loose during the read process, but they often worked at least once. If the chad came out during the read process it would cause a "crash", and the following card(s) would be crushed and crumpled beyond recognition. The card reader would be jolted out of alignment, requiring a Computer Engineer to come and fix it.

In the late 1970's it become more common to load your program to magnetic tape. The tape held your code in fixed-length 80 character records, and we had "librarian" programs to do the editing. As I recall one was actually called Librarian. You would code another card deck to do the editing, or as was becoming more common, use a teletype or VDU to do your editing online. Wow!

The syntax used to drive those librarian editors was very much like the IBM-PC Edlin syntax.

In summary, we use what tools we have available. The newest technology is always the most expensive, and it can take a while before everyone has access to it. It's also a matter of convenience and skills. I am typing this on my laptop, but when writing an email on my smartphone, I use "Swype" input, where my finger makes a weird zigzag pattern over a keyboard image and the software works out what word I intend.

Good luck with your essay.


问:
Should a class explicitly implement interface if its superclass also implements it?
Given an interface

```<code>interface I {
    one();
    two();
}
</code>```

An abstract base class partially implementing I

```<code>abstract class A {
    @Override
    void one() {
         //something
    }
}
</code>```

And lastly a subclass of A

```<code>class B extends A (implements I) {
     @OVerride
     void two() {
         //something
    }
}
</code>```

And now B has to implement I since A did.

In the B class I have (implements I) and my question is,

is it good coding style to explicitly mention that you implement I?

Even though that's given implicitly by the fact that you're subclassing A, that's partially implementing I?

Please note this is a question about good style. I know there is no difference between the two approaches, language-wise.

答:
While I don't have an authoritative answer, in my experience it would depend on the situation.

Usually, the redundancy is unneeded. The main point here is readability, and shorter is typically better. And, as you've already mentioned in the question, there's no functional difference, so write whichever one better fits the logic of the model and will make it easier to understand.

From time to time, including the redundant interface can be useful. Here's a version (using the Animal->Cat classes) of one time I left it in:

```<code>interface Animal {}
interface DomesticAnimal implements Animal {}

abstract class AbstractMammal implements Animal {}
class ConcreteDolphin extends AbstractMammal {}
abstract class AbstractCat extends AbstractMammal implements Animal {}
class DomesticCat extends AbstractCat implements DomesticAnimal {}
class WildCat extends AbstractCat {}
</code>```

A bit of context: In that particular case my task was to implement some new functionality in the new ConcreteDolphin and AbstractMammal classes and refactor a bit of common code in the abstract class.

However, my team was already used to working with Animals, and AbstractMammals were still a fairly new concept. After all, everyone knows that a Cat must be an Animal; what was this AbstractMammal nonsense?!

Thus in this case I thought it was better to leave the redundant AbstractCat  extends AbstractMammal implements Animal as it made it easier to read. I'd say this is a somewhat rare case, though, most times it would be cleaner to only have the one.

Body:
While I don't have an authoritative answer, in my experience it would depend on the situation.

Usually, the redundancy is unneeded. The main point here is readability, and shorter is typically better. And, as you've already mentioned in the question, there's no functional difference, so write whichever one better fits the logic of the model and will make it easier to understand.

From time to time, including the redundant interface can be useful. Here's a version (using the Animal->Cat classes) of one time I left it in:

interface Animal {}
interface DomesticAnimal implements Animal {}

abstract class AbstractMammal implements Animal {}
class ConcreteDolphin extends AbstractMammal {}
abstract class AbstractCat extends AbstractMammal implements Animal {}
class DomesticCat extends AbstractCat implements DomesticAnimal {}
class WildCat extends AbstractCat {}

A bit of context: In that particular case my task was to implement some new functionality in the new ConcreteDolphin and AbstractMammal classes and refactor a bit of common code in the abstract class.

However, my team was already used to working with Animals, and AbstractMammals were still a fairly new concept. After all, everyone knows that a Cat must be an Animal; what was this AbstractMammal nonsense?!

Thus in this case I thought it was better to leave the redundant AbstractCat  extends AbstractMammal implements Animal as it made it easier to read. I'd say this is a somewhat rare case, though, most times it would be cleaner to only have the one.


问:
Python - defining exit method before importing
This breaks nothing (in my experience), but lots of things "don't break anything" and are still wrong.

```<code>#! /usr/bin/env python
"""Short description of this module."""

def preferred_exit_method(*args):
    #code for exiting as desired

try:
    import foo
    import bar
    import eggs
except ImportError as e:
    #code code code
    preferred_exit_method(e)
</code>```

So, clearly defining the program's behavior on exit, then using it during the import process can't be too terrible, right? But it goes against the oft-cited PEP 8, which states that modules should be absolutely be imported before anything global.

It seems like an unrisky proposition, but then there's always something like this:

```<code>#! /usr/bin/env python
"""Description of module"""

def exit_of_choice(*args):
    #code code code
    sys.exit(0)

try:
    import sys
    import other_things
except ImportError as e:
    exit_of_choice(e)
</code>```

Apart from writing code that never needs to do this because it is perfect and never fails at anything, is there a reason besides PEP 8 and "other Python people will be cross with you" not to do this? (well, I'm less concerned with the latter - even though sys wouldn't typically fail to import, I still sort of hate that on principle)

答:
It should be noted that you could defined preferred_exit_method inside the exception block:

```<code>#! /usr/bin/env python
"""Short description of this module."""

try:
    import foo
    import bar
    import eggs
except ImportError as e:
    def preferred_exit_method(*args):
        #code for exiting as desired

    #code code code
    preferred_exit_method(e)
</code>```

This does the same thing without any globals being created before the import.

Body:
It should be noted that you could defined preferred_exit_method inside the exception block:

#! /usr/bin/env python
"""Short description of this module."""

try:
    import foo
    import bar
    import eggs
except ImportError as e:
    def preferred_exit_method(*args):
        #code for exiting as desired

    #code code code
    preferred_exit_method(e)

This does the same thing without any globals being created before the import.


问:
How to introduce Agile to a team that uses rigid non-Agile methods?
Consider a company that is proudly certified for some non-Agile methodology, uses it as a selling point to its customers to demonstrate accountability.

How do you go about introducing Kanban or Scrum progressively without breaking their whole system and still making them confident that it can still be just as accountable / auditable?

I know this is possibly related to "How would you introduce an agile methodology like Scrum", but here I am wondering about ways to circumvent/work around the fact that the company imposes a certain way of managing the SDLC under the false pretense that it's the only way to have an audit trail.

答:
This is almost exactly what happened at our company. We followed strict, non-agile methods. When a new Lead Technical Manager joined, who had some experience with SCRUM, he thought it would be good to try it out.

The way we did it, was to take a small group of developers (and analysts) to make a pilot SCRUM team. We followed strict SCRUM methodology for about 4 months, after which the company reflected on what we have done, how we did it, analysed to data (you know, all the stuff the BA's need to do).

What they found was that the pilot was a great success. So they made another team which follows Kanban, and they too have been a great success. I think there is talk that the rest of the developers also forming SCRUM/Kanban teams.

I think the pilot was pivotal. It gives the strict side of the business time to evaluate and see that it works first.


问:
Why can't I understand Java?
I'm a 9th grader and I joined my school's robotics team in order to learn how to code Java and enter the programming team. However, I am so confused! Even after the first lesson, I had no idea what the teacher was talking about. I don't know if it's just me but, but I just can't understand any of the terms or how to put them together to form code.

My teacher is always busy on weekdays so I only have Saturday to talk to him. Until then I'm just sitting in front of Netbeans without a clue on how to code our first assignment which is to write Java code that solves a geometry question of my choice. I really want to become a good programmer, but I just can't get a grasp on Java. My teacher and many websites say that learning Java is like learning a new language and one must practice to be good at it.

I learned HTML, which was a breeze for me, so I have experience with programming, but I just can't understand Java! The two are completely different the way I see it.

However, how am I supposed to practice if I have no idea what in the world is going on? Also, does one have to be a math wiz to be a good programmer?

答:
It is true that you need to practice. But different people have different ways of learning, and not every teacher is

an expert in what they teach

an expert teacher.

So a key part of school is learning how to learn.

I have Googled "basic java tutorial" for you. Two of the top links look useful for you

http://www.tutorialspoint.com/java/

http://javabeginnerstutorial.com/core-java/

I suggest you cut and paste example code, such as a "Hello, World" program, see what it does and how, then make changes and see what they do.

Expect to spend many hours at this. It is learning to express your thoughts in a new language.

Edit: does one have to be a math wiz to be a good programmer?

No. There are many different problem domains, and you'll initially deal with problems you know about. But programmers are learning about things all the time - new skills like how to handle particular math problems, or some new language, or some new way of thinking. A lot of programming just involves "If item A is XYZ put it in bucket B, but if it's UVW put it in bucket C".

But math is closely related to programming, in that it is a precise way of thinking and solving problems. You need to just as precise in programming. The computer doesn't know what you want it do - it does exactly what you've told it do. Which is both the joy and agony of programming.

And one branch of math is very important: logic. You will learn this one!

Title: Why can't I understand Java?


问:
What is an Anti-Corruption layer, and how is it used?
I'm trying to figure out what the Anti-Corruption layer really means. I know that it's a way to transition/work around legacy code or bad APIs. What I don't understand is how it works and what makes it a clean separation from the undesirable layer.

I've done some searching, but I can't find any simple examples or explanations, so I'm looking for someone who understands it and can explain it with simple examples. An answer that would satisfy my question should be simple (not necessarily short), and provide understandable examples of implementation and use.

See this question, for my use case.

答:
Adapter

When you have incompatible interfaces, that perform similar logic, to adapt one into the other, so that you can use implementations of one with things that expect the other.

Example:

You have an object that wants a Car, but you only have a 4WheelVehicle class, so you create a CarBuiltUsing4WheelVehicle and use that as your Car.

Facade

When you have a complex/confusing/gigantic API and you want to make it simpler/clearer/smaller. You will create a Facade to hide away the complexity/confusion/extras and only expose a new simple/clear/small API.

Example:

You are using a library that has 100 methods, and to perform certain task you need to do a bunch of initialization, connecting, opening/closing things, just to finally be able to do what you wanted, and all you wanted is 1 feature of all 50 the library can do, so you create a Facade that has only a method for that 1 feature you need and which does all the initializing, cleaning, etc. for you.

Anti-corruption Layer

When you have a system that's out of your domain, yet your business needs requires you to work with that other domain. You do not want to introduce this other domain into your own, therefore corrupting it, so you will translate concept of your domain, into this other domain, and vice-versa.

Example:

One system views the custumer having a name and a list of strings, one for each transactions. You view Profiles as stand alone classes having a name, and Transactions as stand alone classes having a string, and Customer as having a Profile and a collection of Transactions.

So you create an ACL layer that will let translate between your Customer and the other system's Customer. This way, you never have to use the other system's Customer, you simply need to tell the ACL: "give me the Customer with Profile X, and the ACL tells the other system to give it a Customer of name X.name, and returns you a Customer with Profile X.

====================

All three are relatively similar, because they are all indirection patterns. But they address different structures, classes/objects versus APIs versus modules/sub-systems. You could have them all combined if you needed to. The sub-system has a complex API, so you build a FACADE for it, it uses a different model, so for each data representation that don't fit your model, you would TRANSLATE that data back into how you model it. Finally, maybe the interfaces are also incompatible, so you would use ADAPTERS to adapt from one to the other.


答:
Java was my first language, and I found it very difficult. I'm not sure how much of it is just because I was a new programmer (I didn't realize I had to go through a learning stage before I would be able to even start the program I wanted to write); how much was because I was following the official Sun tutorial ("why is this going on and on about"), and how much of it is related to the fact that Java is not a great first language (or in my opinion for anything: it does a lot of things passably, but nothing excellently).

Sure, I could make stuff happen but I didn't understand why or what I was doing at all.

I recommend Python for the earliest starting:
 * less focus on "Object-oriented" propoganda, but actually better and really being object-oriented
 * dict, list, and set as builtin types instead of library types.
 * saner use of exceptions (but please specify types)
 * more functional style as opposed to imperative
 * a REPL
 * doesn't hide things behind an IDE (there are IDEs for python, but you should just use some text editor that's designed for programmers and explicitly save and run your code)

After you write your first several programs, go back and write them all without using any mutable global variables (probably the biggest thing that newcomers use way too much, and also ask more experienced python programmers about things you're missing).

Once you're confident that you can write any small-to-medium (to your sense of scale) program in Python, go back and rewrite the same programs again in Java. Learning involves a lot of this "go do the same thing, but in a different way".

It would also be profitable, you'll learn a bit of C. Don't expect to write any big programs in it, but you should be confident that you no bugs related to malloc/free, strcpy, I/O that may have errors.

Also, it is unquestionably useful to get comfortable with the command line in general, and with a version control system in specific. A programmer who can't use version control is a net loss to any programming team.

I recommend your first version control be some decentralized one, such as git or mercurial, so that you don't need a remote server. As a newcomer the most important rule is "commit early, commit often". Eventually, you'll get a better idea of when it is useful to commit, when to amend or squash (it is always easier to start with many small commits and turn them into one larger commit later - if you have a reason to do so); and you'll also gain the skill to be able to follow the "every commit must work, for some definition of work" rule.

Do not make the mistake of doing version control from an IDE. If you must use an IDE, pretend that the VCS-integration doesn't exist, because it will be worst than useless whenever the slightest thing goes wrong (and things go "wrong" very often when there are 2 people working on the same project). Just type git status a lot, and make sure you understand why everything is red or green, then figure out the best way to get rid of the red (some common ways: add untracked files, add changes to a tracked file (only in git), add to ignore list), and run both git diff and git diff --cached before making a commit. (The concept of staged vs unstaged changes is a bone of contention between git and most (all?) other DVCS, but I find it much more obvious to be able to separately talk about "changes I'm fairly confident will go into the commit without much change" from "changes that I'm still working on". But again, as a newcomer, commit often).

You may note that I didn't explicitly mention the commands to actually add changes or make commits. This is because it is far more important to know how to get information out of the VCS than to put it in.

You may also note that I didn't put any links here. This is a deliberate decision, learn to Google, and remember than 90% of everything (including the front page of Google) is crap.

Finally - congrats on trying to get an early start. If you know programming when you start college, you won't be hopeless like most graduates. Of course, if you're really good and know how to make friends, you might be able to avoid wasting time and money on college at all.

Title: Why can't I understand Java?

Body:
I'm a 9th grader and I joined my school's robotics team in order to learn how to code Java and enter the programming team. However, I am so confused! Even after the first lesson, I had no idea what the teacher was talking about. I don't know if it's just me but, but I just can't understand any of the terms or how to put them together to form code.

My teacher is always busy on weekdays so I only have Saturday to talk to him. Until then I'm just sitting in front of Netbeans without a clue on how to code our first assignment which is to write Java code that solves a geometry question of my choice. I really want to become a good programmer, but I just can't get a grasp on Java. My teacher and many websites say that learning Java is like learning a new language and one must practice to be good at it.

I learned HTML, which was a breeze for me, so I have experience with programming, but I just can't understand Java! The two are completely different the way I see it.

However, how am I supposed to practice if I have no idea what in the world is going on? Also, does one have to be a math wiz to be a good programmer?


问:
Is it safe to catch ImportError when trying to import optional modules?
I usually see this pattern at least once in every Python project I work on.  For example, in a Django project, this is often added at the bottom of the base settings file:

```<code>try:
  from .local_settings import *
except ImportError:
  pass
</code>```

Also:

```<code>try:
  import simplejson as json
except ImportError:
  import json
</code>```

This has always bothered me a little bit though; what if the module is imported successfully, but then it triggers an ImportError itself?  E.g., in the first example, the local_settings module exists, but then local_settings tries to import a non-existent module.

Is this the safest way to import an optional module, is there a better way to achieve this functionality, or does it depend on the context/usage (and if so, what are the guidelines to deciding when to use this approach)?

答:
This is generally safe, assuming your modules are free of import-time side effects.

If an imported module raises any exception (not just ImportError) at import time, it is removed from sys.modules.  This means if any other code tries to import the module, it will not get a partially-initialized module.  Instead, Python will try to load the module all over again, and presumably fail with an ImportError all over again.

This can cause issues if your modules have import-time side effects, since those effects are not undone.  In particular, if the offending module successfully imports another module, the latter is not removed from sys.modules.  This particular side effect is rarely a problem, but some side effects can be more troublesome.


答:
Magnetic tape was first used for data storage in 1951. Hard drives were introduced in 1956. Floppy drives were introduced in 1971. The punched card had a significant head start on all of these storage mediums.

By the 1970s, IT organizations were at least investigating a move away from punched cards. By the late 1980s or early 1990s, the transition was all but complete.

Punched cards held on for as long as they did, when there were other more efficient storage mediums available, for at least a couple of reasons.

1) They were in use, and inertia is a tough thing to overcome. In other words, "We'd always done it this way."

2) Cost. A 1 TB SATA drive can be had for a little over $50 today, but a variation on Moore's Law has been driving down costs over time. For comparison, a Seagate ST-506 5 MB drive in 1980 cost $1,500 (about $4,300 today).


问:
How to safely chain several API requests for a single user
I am writing a web application with Python and Flask. At a high-level, the web service takes an ID, downloads a file from a third-party API based on that ID, reads and analyzes the data inside the file, and finally returns that analysis to the client.

Since this process takes a fair bit of time, I'd like to have notifications to the client when (1) the file is being downloaded, (2) the file is being analyzed, and (3) the analyzed value has been returned. Since HTTP is based on a single request-response cycle architecture, I have decided to break each step into an API endpoint. The client-side JavaScript will handle chaining the AJAX requests and updating the client of the progress.

Here is the request-response workflow I have in mind:

1a. The front-end makes a request with an ID to a "download" endpoint and then notifies the client that the file is being downloaded.

1b. The server downloads the file and responds to the front-end with the downloaded filename. When this is successful...

2a. The front-end makes a request with the filename from step 1 and some additional configuration values--set when the user initially clicks "submit"--to an "analyze" endpoint and then notifies the client that the file is being analyzed.

2b. The server analyzes the file based on the client's configuration and generates an output file with the analysis. The server then responds with the output filename.

3a. The front-end then makes a request to the "output" endpoint with the output filename from step 2 and notifies the client that the output file is being downloaded locally.

3b. The server simply returns the static file on request. The server then deletes the output file.

Broadly, my question is: does this architecture work? More specifically:

Is there a better way to show progress to the client? This seems like a lot of overhead for that functionality--on the other hand, it's nice to have cleaner API endpoints.

What happens when client A and client B request the same data back-to-back? Client B's server-side process might respond that the output file is ready right before client A's process delete the file. Is there a way to avoid this scenario?

I realize this is a bit messy, but I am pretty new to back-end development and am very open to any suggestions.

Thanks in advance.

答:
Alternative could be to use some batch frameowrk like spring batch.
The advantage over javascript would be easy to configure, inherent logging , retry and monitoring and easy integration to other system which will help in sending notification and downloading files</p>


问:
Sorting displayed results vs. entire results
If I present a user with a table of results from a database which only displays the first 1000 rows, what does the user expect when they re-sort the table?  Do they expect only the displayed results to be sorted (on the client) or do they expect an entirely new result set from the db, sorted accordingly?

For example, if the first (default) table view displays rows A through D, should reversing the sort on that column simply display D through A, or Z through W?

Or should I provide the user with the option to do either?  If so, how could I succinctly phrase the options?

答: There's no added value to reversing data you can already see (consider the 'head' and 'tail' commands in unix). Even if you only get a snapshot of data, you still need to have access to all of it.</p>


问:
Models, types, different views and meta data
We have a software which purpose is to be used to help users build their own applications. It has to be very loose coupled with the infrastructure: for example, I can imagine users running it on MySQL database as well on MongoDB.

We have modules of functionalities. In each module we do have what I call pure models - containing only what is required. For example, a Book contains authors, title, number of pages and so on.

The problem is that we need to bundle additional meta-data with the models that depends on the other infrastructure! Trivial example is a technical key of the Book: for MySql repos this is primary key of the table, some other ids as well; for MondoDB repos is just its own string key. As you see, the meta-data information is not unique and depends on infrastructure.

This additional data is provided by concrete repository implementation, every time when model is stored or retrieved from repo.

Now the problem: we would like to 'hide' this from the Book (i.e. model) interface - since there is no sense to bundle all variants of meta data to the Book.

How to solve this?

[A] We can have factories that builds our models, depending on used repo. So for SQL repo, we have a SQL factory, that builds a SQL variant of the model. Not sure that I like this.

[B] We simply add a property to Book for additional meta-data, like repoMetaData. This property is strictly technical, i.e. it is not related to the business. Then any repository implementation may inject whatever inside. Book would become RepositoryAware (an interface).

I like the [B] more, but some don't like the fact we are adding technical stuff to the book interface. How far it make sense to add additional, technical info to the models?

答:
If you group your technical meta data (as you call it) into reasonable classes, I do not see  a problem to be part of your Book.

There is just a problem if some of your meta data is needed during the model creation. If this is a case, then you can't run from factories - or to have instance to providers of those meta data.


问:
Duplicate method in spring services, how to refactor?
ServiceOne.java

```<code>private void doStuff(){}
</code>```

ServiceTwo.java

```<code>private void doStuff()
</code>```

Where to put common code ?

Shall I create a new service, but then what interface will it implement ?

Or shall I just create a utility class ? Please guide on what is the best approrach.

答:
Well it actually depends on the stuff. If the stuff is related to the business logic of the application and inside has to do with domain objects then it has to go in another class and be aggregated in the services or depending on domain in a superclass of both services. For example both services need to check if a user already exists.

On the other hand if that method has nothing to do with business logic, it could go in a utility class. For example suppose it has to poll a given function, calling it multiple time until response is not null.


答:
As discussions on Visual Assist shows, this feature is far from simple: which extensions are included (.c, .cpp, .cxx, .h, .hpp, .nothingatall, .inl, ...), which way you cycle through them when there are more than two, etc.

I agree it's still a rather simple feature to implement, but it's not as simple as you think.

Title: Why isn't it possible to switch between header and cpp in Visual Studio?

Body: For the last eight years I wait for Microsoft to add the basic C++ functionality of switching back and forth between .h and .cpp files, and it keeps astonishing me it is still not supported in Visual Studio 2010. Does anyone know why they refuse to add this essential feature?  </p>


问:
Is it a correct practice to handle error / success responses based on content type, or should I handle the two separately?
Right now, when I handle a success / failure message, I handle both response types via the same listener and check the response type to decide whether it's a success or failure response. Like this:

server

```<code>socket.on('event', function(){

    //process request

    if (success) {
        var data = {
            foo : 'useful',
            bar : 'info'
        }
    } else {
        var data = 'failure message';
    }
    socket.emit('eventResponse', data);
}
</code>```

client

```<code>socket.on('eventResponse', function(){
    if (typeof data = "object") {
       //assume successful response / utilize response data
    } else {
       //assume failure and utilize data as failure message
    }
}
</code>```

At this point, I always send a failure as a string containing the failure message, and always send success as an object, containing response data. I think of this as sort of a dependency topic. Since I'm not defining clear input type dependencies, it may be considered bad practice, or perhaps because doing this is simpler and faster, it may be good. I'm not sure.

Is it a correct/acceptable practice to handle error / success responses in this way, or should I handle the two separately?

答:
If you consistently do this, and document it, and it fulfills all your needs, then there is no problem with it.

But if you know you'll need more complex error indicators in the future, or if you do this in some places but not others, or if your handlers are so complex that a combined function becomes unreadably large, then nip the practice in the bud now.


问:
Tree View Children condition indicator on topmost un-expanded parent
I am using a tree view in c# and i am creating custom icons for the nodes.

Let say this is my hierarchy with a node that satisfies a certain condition:

```<code>Root1
|_Ax
 |_Bx1
 |_Bx2
  |_Cx1
  |_Cx2(condition true)
 |_Bx3
 |_Bx4
|_Ay
 |_By1
 |_By2
  |_Cy1
</code>```

when the tree it's collapsed I don't know if some inner child satisfies that particular condition so I want to display an icon on the topmost un-expanded parent.

For example let say that the tree it's completely collapsed I would like this behaviour :
1) the first root will be like this :

```<code>Root1(!)
</code>```

2) I expand Root1 and i see there is something the children of Ax :

```<code>Root1
|_Ax(!)
|_Ay
</code>```

3) I expand Ax :

```<code>Root1
|_Ax
 |_Bx1
 |_Bx2(!)
 |_Bx3
 |_Bx4
|_Ay
</code>```

4) Last I expand Bx2 to find the target node Cx2:

```<code>Root1
|_Ax
 |_Bx1
 |_Bx2
  |_Cx1
  |_Cx2(condition true)
 |_Bx3
 |_Bx4
|_Ay
</code>```

The symbol (!) appears only on the topmost un-expanded parent and disappears once the node is expanded indicating a path to locate the target node Cx2.

But I would like some idea on how to add the node indicator (!) in an efficient fashion.

I need to do this in 2 steps
 - tree creation
 - node expanded

In the first case as soon as I create the node Cx2 and I notice it satisfies that particular condition I need to put the indicator on the topmost unexpanded parent node.

In the second case I need to change the indicator location dynamically when the node it`s expanded.

What is the most efficient way to do that ?

答:
I don't think recursion is the efficient way to solve this because on expanding the marked node you would have to apply that recursion on every single one of its children.

A marked node should carry information (e.g. in form of a list, array, ...) which of its descendants are matching the condition. So if that marked node gets expanded you would just start at the condition-matching node and go up until you reach the first visible node an mark it. After you have done this for every descendant you remove the marker from the now expanded parent node.


问:
How best to implement a local-area peer to peer network
My goal: To write a program where any two computers on the same LAN see each other, and can talk directly to each other without any servers or accounts. Every client must be just as strong as every other client, and maintain their own list of which clients are online. (I plan on using computer hostnames hashed with IP addresses to keep entries unique).

My design: I want to get every client a list of every other client currently on the LAN. That means regular broadcast messages to all clients on the network, and timeout periods for clients so that the list is trimmed of offline clients.

My problem: That takes a toll on the network, to broadcast to every client there. If there are 2 client programs on a network with 300 computers, that is 298 computers that have no use for the packets they are receiving. Also I don't know which port to use. In addition, network broadcasting is obsolete in IPV6, and I don't want to structure this part of the code in a to-be-obsolete way.

My research: I could use IP Multicasting to send out signals to only interested clients (those running my program). Regularly sending signals out every 60 seconds shouldn't be too wasteful if it isn't going to any non-interested programs.

Source Specific Multicast is a bad choice for me because no one source can be established ahead of time. I would need to do either Sparse or Dense multicasting.

I just want to confirm that I am on track, that using Multicasting is the best possible protocol for keeping my clients on the same page.

Here is one last caveat. Let's say all the wired clients are on a LAN which contains a wifi router, such that the wifi router runs a DHCP and packet routing service for just wifi enabled clients. What technique would be most reasonable to multicast across a network gap like this (and not all the way to the global internet)?

答:
You're on the right track with multicast for a peer to peer system without a central broker. Very expensive systems used in financial services for low latency messaging do exactly that to implement topic resolution and optionally the messaging itself.

However, take it from me, once you get out of the single VLAN scenario and need to traverse firewalls and routers then multicast becomes very brittle. It's not that those devices don't support multicast very well - they do. Nor is it that IGMP is a poorly thought out protocol - it's not. It's that the knowledge of how to set up multicast routes and maintain them seems to be the domain of only the most experienced network engineers.


问:
How are the tiles in WORDAMENT organized?
I'm trying to create a word game, just like WORDAMENT, in my spare time. In order to present a new round, I need to create a board with 16 letters organized in a 4*4 grid. Currently, I'm generating the grid randomly. But it has some obvious problems. So my main purpose is to organize those 16 letters in such a way that maximum number of words can be formed out of connected tiles. How shall the letters be organized ?  I think this comes down to the probability of occurrence of letters in the English language. How can I use the letter frequency table, to organize my tiles? Any relevant pointers/suggestions/articles are appreciated. Thanks.</p>

答:
Sometimes, it is simpler to "cheat" a little bit and start from the answer. In this case, I am more likely to take a set of words and continue to arrange them on board in the remaining spots until some criteria is met, and then fill the rest randomly.

For example, I'll pick a dictionary with the relatively "simple" words and create my word DB so that I can efficiently look up a random word based on two criteria: 1) How many letters do I want in a word, and 2) Which letter should the word begin with.

This is how I would build the game:

1) Pick a word from dictionary that's either 6 or 7 chars long. Put it on the board in a random order. Let's say the word was BORDER:

2) Find 2-3 consecutive empty spaces. Pick an adjoining letter and find a word from the dictionary that can meet the length (i.e. based on empty spaces) and begins with that letter. Arrange the letters on board. For example, after DINE is added:

3) Again, this time around BET:

4) Iterate until you can no longer find 2 consecutive empty spaces. Fill any single spaces with random characters. So after adding NUN and ZOO, the last space is filled with P:

Done. Now if you look at the final board, since the algorithm had especially added a few words, they are bound to be there. Since they were English words, they are likely to make a lot of combinations with other words since they are arranged together on the board. So you can easily see a few words already that were never initially added: ODE, BOO, RIDE, BODE, PEN, RUN, PRIDE, etc. I am sure if you play more with this board, you'll find many more :-)

I would play with the variables (e.g. is 6-7 letter the best way to start, or larger or smaller), and how to decrease the length (i.e. if 5 consecutive blocks are available, should add a word for 5 letters, or two smaller ones, etc.).


问:
Documenting higher-level concepts
I will be leaving my current project in a few days, and as part of securing my knowledge I have been asked to add comments to the code wherever I feel that can add value.

The problem I am running into now is that the comments I want to write are not really suitable as comments, because they do not pertain to a single entity in the code (a few lines, a function, a class or even a file), but they are more about how two or more entities interact with each other or about a feature whose implementation is spread over multiple entities.

So, how do you go about documenting the stuff that does not belong to a single entity but is important to know to understand the bigger picture?

And also: Where do you document it? In the source file or in an external document?

As an example, we have a client-server architecture in C (with the client and server both running on the same embedded device). To avoid flooding the server, the client has a mechanism to throttle the sending of similar requests to the server such that a request can only be sent if the previous one has been answered.

The innards of this mechanism are spread over multiple functions.

Where would you place the documentation of such a feature, especially if the file with the functionality also has some other, unrelated, functions?

Edit: Extended the question a bit.

答: You can probably utilise simple UML diagrams to highlight the high-level concepts.</p>

Title: Documenting higher-level concepts


问:
Why were punch cards used for programming
I am doing a research essay on the history of programming languages, and I was wondering, why did programmers ever write their programs on punch cards? Didn't computer screens and keyboards already exist by the time programmers used them?

I know they were first invented for the use of the Jacquard loom and to control the desired design, but when people programmed, why did they decide to write their programs on a card oppose to writing it on a terminal?

Was it because since computers were very expensive, not many people had access to them, resulting in people writing programs on punched cards, submitting it to a company or someone or some organization that had one to run them and tell them the result?

答:
In the early days the computer system was in a room that was not accessible to programmers and most systems could only execute one program at a time (batch processing).  To have your program executed you submitted it via punched cards or paper tape and came back later to get your results which was normally a print out. Programmers were rarely allowed direct access to the 'console', and if they were it was to debug a program, not to write it.

With the advent of preemptive multitasking circa 1965 (see Multics), many users could be supported at once via 'terminals'.  In the beginning these terminals were teletype like machines and then later CRT screens with keyboards.  These systems were not widely available until the early 1970's.

My first computer did not have a hard disk.  To compile a program the compiler was read into memory from punched cards and executed.  It read your source code from punched cards and punched the compiled version.  That version was put behind a loader program and read in.  It was only then that your program was executing.  Oh the good ol' days ;)


问:
Why is a python package more perfomant as zip?
I have read the following text in the setuptools documentation:

For maximum performance, Python packages are best installed as zip files.

https://pythonhosted.org/setuptools/setuptools.html#setting-the-zip-safe-flag

Why is it like this? one would think that the unzipping of the file would have negative impact on the performance. Thanks.

答: CPUs are fast and hard disks are (despite SSDs) slow. Thus it's usually faster to load compressed data from disk (less data to transfer) and uncompress it in memory (needs some CPU time).</p>


问:
How do different technologies connect to form a web stack?
I am a little confused, is it possible to implement a front end using common languages like html, css and javascript and then do server side processing using a language of your choice, say python or java?

I am aware of what a LAMP stack is; I'm aware that rails is a full stack framework; I'm aware that you can use things like spring MVC and Grails. But I'm not sure how you would combine technologies of your choice.

For example:

Java has a great API that you can do a lot with, but is not really the best choice for developing front end stuff in a non enterprise environment.

Python has great libraries for processing and visualizing data (yes I know about django).

I suspect that this is when you want to use a custom technology stack you have to create a RESTful or SOAP API or just pass data using XML or JSON...

Would someone be able to clarify if my understanding is correct?

答:
... is it possible to implement a front end using common languages like html, css and javascript and then do server side processing using a language of your choice, say python or java?

Yes, it is possible. It is standard, in fact.

But I'm not sure how you would combine technologies of your choice.

When an HTTP request is received by your web server process it forwards that to your back-end (Java or Python code), which then returns content (like HTML). The web server transmits an HTTP response back to the web browser.

There are a variety of ways that your web server could communicate with your back-end code. It could host it directly, like via WSGI, or I suppose you could use some form of Inter-process Communication.


问:
Why 'List<E>' is an 'interface' but not 'abstract class'?
Amidst defining the hierarchy, firstly,  one can think to embed the abstract method(behavior) in abstract class only because the derive concrete class possess that behavior as core behavior with it's specific implementation, secondly, one can think to embed the abstract method(behavior) in interface only because derived concrete class possess that behavior as non-core behavior(peripheral) having it's specific implementation.

As I would not rely on this example which supports above point, below are the two references, I would rely on.

1) First reference that supports this point:

Interfaces are ideal for defining mixins.  Loosely speaking, a mixin is a type that a class can implement in addition to its "primary type" to declare that it provides some optional behavior.  For example, Comparable is a mixing interface that allows a class to declare that its instances are ordered with respect to other mutually comparable objects.  Such an interface is called a mixin because it allows the optional functionality to be "mixed in" to the type's primary functionality.  Abstract classes can't be sued to define mixins for the same reason that they can't be retrofitted onto existing classes: a class cannot have more than one parent, and there is no reasonable place in the class hierarchy to insert a mixin.

2) Second reference that support this point:

In UML sketch, the relation between interface model and concrete class model is named Realisation, where as, the relation between abstract class model and concrete class model is named is-a relation. Here is-a can be told, when concrete class has core behavior unlike realisation relation.

So, with these two references, It looks list<E> and Collection<E> are abstract class but not interface.

With this above explanation, I would like to understand,

Why Collection<E> and List<E> is designed to be interface in  java.util package?

Is my understanding correct?

答: You're quoting your reference (Joshua Bloch, Effective Java) out of context. It isn't stating one particular purpose for interfaces and that they should only be used for that purpose.  It's enumerating a (non-exhaustive) list of possible applications for them, all of which fall under the general heading "Prefer interfaces to abstract classes".  How you get from this to deciding that List<> would be in some fashion better as an abstract class, I'm not quite sure, but it seems that you're picking up details of Bloch's argument without comprehending the overall purpose of it.


问:
Mid-Large Asp.net MVC project: Storing images on filesystem or via SQL Server FILESTREAM
We have a ASP.NET MVC project with AngularJS and Entity Framework database-first, a news portal already in production for about a year. The project is mainly focused on providing content for users (articles, news and etc) and of course there is a lot of images. Currently we are storing the images in the File System and in SQL Server we store only the path.

The site today has something like 2000+ images (every day a lot of new images are uploaded so this number can grow very fast). The size of the images are on the average of 1 MB (but can also be larger).

Our client has requested (really don't know the reasons..) for us to start saving the images inside the database, using SQL Server’s FILESTREAM. As a company, we had never developed any project using this technology. We already know that storing BLOB's (as VARCHAR(MAX)) is a really bad approach but what about FILESTREAM? Is it really worth it?

The main objectives are:

FILESTREAM will offer better performance over time?

What about the way to manage (save, retrieve) images? Is it a lot of different than using System.IO.File ?

What about EntityFramework 5? Is it compatible? (Couldn’t really find actual answers for this on the internet)

The user can upload up to 10mb. Also, we have plans to let them also upload files (.pdf, .doc, .xls, even .mp3 max 10mb)

答:
Since you're talking about images in a context of a news portal, I imagine that those images are small JPEGs, not RAW files which can easily be 30 MB in size. In that case, FILESTREAM won't be recommended, because its primary purpose is to host large files within the database.

For smaller objects (less than 1MB), storing varbinary(max) BLOBs in the database can provide better streaming performance.

Source: Best Practices on FILESTREAM implementations

FILESTREAM has one major benefit: you can store very large blobs of data without being limited by the amount of memory on your server. By storing this data within the database instead of plain file system, you make it possible to unify data management. For instance, system administrators can define the backup strategy once for the database, and don't have to create a duplicate backup strategy for plain files.

But the benefit stops here. In other words, you get performance nearly identical to what you can get with plain files and the benefit of a single strategy, but there is nothing more there.

If you don't need this unified management of data, don't use FILESTREAM. Unfortunately, FILESTREAM is overrated in Microsoft community, leading many people to use it in projects which don't need it.

FILESTREAM will offer better performance over time?

One of the benefits I can see is that you won't need to query the path of the file any longer. Aside this, you won't see a benefit of using FILESTREAM compared to direct access to a file, because you simply add a layer of complexity.

Beware of the exact location of your actual files and the possible location of FILESTREAMed files: if currently, the files are stored locally, and in FILESTREAM, they will be moved to the machines hosing SQL Server, you'll have to consider the bandwidth usage between your app servers and your database servers.

What about the way to manage (save, retrieve) images? Is it a lot of different than using System.IO.File ?

No. Accessing files is really easy and similar to the way you access an ordinary file. You can easily find the examples on MSDN.

What about EntityFramework 5? Is it compatible? (Couldn’t really find actual answers for this on the internet)

It wasn't supported yet in 2011. I don't know if things changed since then, but in all cases, you'll probably circumvent Entity Framework if you need to access data stored in a FILESTREAM (which won't be difficult either).


问:
What did people do before templates in C++?
I am not new to programming, but I am one that started a few years ago, and I do love templates.

But in the before times, how did people deal with situations where they needed compile-time code generation like templates? I'm guessing horrible, horrible macros (at least that's how I'd do it), but googling the above question only gets me pages and pages of template tutorials.

There are many arguments against using templates, and while it typically boils down to readability, "YAGNI", and complaining about how poorly it is implemented, there is not a lot out there on the alternatives with similar power. When I do need to do some sort of compile-time generics and do want to keep my code DRY, how does/did one avoid using templates?

答:
One way of doing this is like this:

https://github.com/rgeminas/gp--/blob/master/src/scope/darray.h

```<code>#define DARRAY_DEFINE(name, type) DARRAY_TYPEDECL(name, type) DARRAY_IMPL(name, type)

// This is one single long line
#define DARRAY_TYPEDECL(name, type) \
typedef struct darray_##name \
{ \
    type* base; \
    size_t allocated_mem; \
    size_t length; \
} darray_##name;

// This is also a single line
#define DARRAY_IMPL(name, type) \
static darray_##name* darray_init_##name() \
{ \
    darray_##name* arr = (darray_##name*) malloc(sizeof(darray_##name)); \
    arr->base = (type*) malloc(sizeof(type)); \
    arr->length = 0; \
    arr->allocated_mem = 1; \
    return arr; \
}
</code>```

The DARRAY_TYPEDECL macro effectively creates a struct definition (in a single line), replacing name with the name you pass, and storing an array of the type you pass (the name is there so that you can concatenate it to the base struct name and still have a valid identifier - darray_int * is not a valid name for a struct), while the DARRAY_IMPL macro defines the functions that operate on that struct (in that case they're marked static just so that one would only call the definition once and not separate everything).

This would be used as:

```<code>#include "darray.h"
// No types have been defined yet
DARRAY_DEFINE(int_ptr, int*)

// by this point, the type has been declared and its functions defined
darray_int_ptr* darray = darray_int_ptr_init();
</code>```

Body:
One way of doing this is like this:

https://github.com/rgeminas/gp--/blob/master/src/scope/darray.h

#define DARRAY_DEFINE(name, type) DARRAY_TYPEDECL(name, type) DARRAY_IMPL(name, type)

// This is one single long line
#define DARRAY_TYPEDECL(name, type) \
typedef struct darray_##name \
{ \
    type* base; \
    size_t allocated_mem; \
    size_t length; \
} darray_##name;

// This is also a single line
#define DARRAY_IMPL(name, type) \
static darray_##name* darray_init_##name() \
{ \
    darray_##name* arr = (darray_##name*) malloc(sizeof(darray_##name)); \
    arr->base = (type*) malloc(sizeof(type)); \
    arr->length = 0; \
    arr->allocated_mem = 1; \
    return arr; \
}

The DARRAY_TYPEDECL macro effectively creates a struct definition (in a single line), replacing name with the name you pass, and storing an array of the type you pass (the name is there so that you can concatenate it to the base struct name and still have a valid identifier - darray_int * is not a valid name for a struct), while the DARRAY_IMPL macro defines the functions that operate on that struct (in that case they're marked static just so that one would only call the definition once and not separate everything).

This would be used as:

#include "darray.h"
// No types have been defined yet
DARRAY_DEFINE(int_ptr, int*)

// by this point, the type has been declared and its functions defined
darray_int_ptr* darray = darray_int_ptr_init();


问:
How do you keep control in a large software project?
I've a large-ish software project that I'm the sole developer for (~80KLOCS and counting - I know there are much larger projects out there, but it's an order of magnitude larger than I've ever had to deal with before).

If it's relevant, the code is split between PHP and JavaScript. I'd guess about a third of it was JS, about two thirds is PHP; I expect that over time, the size of the JavaScript will outgrow the size of the PHP.

I'm starting to get to the situation where, occasionally, the odd part of it is getting more complicated to maintain. It's still workable, but I can see that maybe in a few months time, it will become a nightmare.

Anyway, my question is this:

With larger software projects, what's the best way to keep them as being maintainable?  I mean, when I suppose my cycle learning to program I've hit a series of these brick walls of maintainability:

First wall; solved by learning that you could put code inside functions

Second wall; solved by learning that you could put functions inside classes

Third wall; solved by learning that you could put classes in to an architecture (say, MVC). And at a similar time - versioning, unit testing etc

Fourth wall; ????

Anyways, I just wondered - is there some other learning thing that happens, some magical code organisation approach that makes these huge software projects 'work'?  Is there must be some kind of thing that keeps huge projects from just grinding to a halt?  Is it a just a case of being strict with oneself ... in which case, strict about what?

Thanks for the help, should it come :)

答:
At some point, every project becomes too large and complicated to keep it all in your head. For some this point comes sooner or later than for others and you seem to have hit that point in your project now.

The first step now is to start writing that dreaded documentation. Write down

what each class is supposed to be doing,

which classes work together in a design pattern and why you use that pattern there

for complicated logic, write down why it must be done this way and can't be solved in a simpler way,

add clarifying (UML) diagrams where needed.

This can be either a stand-alone document, or it can be extracted from comments in the code with tools like JavaDoc, doxygen, etc. The aim here is to have something that you can refer back to to refresh your memory when you need to go back to a piece of code after some time.

Something else that you can do to keep a growing code-base manageable is to split it all up in smaller modules/libraries.

By splitting the project up in several smaller modules with strictly defined boundaries/interfaces, you can work on each module in isolation without needing to know/remember what is happening exactly on the other side of the boundary.

This effectively makes each module a small project of its own, with a much smaller complexity than the overall project.


问:
How to ORM non-disjoint specializations
Consider this highly simplified sample of relational data (each table may be involved in one-to-many and many-to-many relationships not shown here):

```<code>people
+-------+------+--------+
| name  | born | gender |
+-------+------+--------+
| Alice | 1980 |      F |
| Bob   | 1975 |      M |
| Carl  | 1994 |      M |
| Dot   | 1942 |      F |
+-------+------+--------+

workers                         students
+-------+---------+-------+     +-------+-------------+-------+
| name  | company | since |     | name  | institution | since |
+-------+---------+-------+     +-------+-------------+-------+
| Alice | Soylent |  2003 |     | Alice | Western     |  2001 |
| Bob   | HAL     |  1999 |     | Carl  | Eastern     |  2012 |
+-------+---------+-------+     +-------+-------------+-------+
</code>```

Some people are workers (Bob), some are students (Carl), some are neither (Dot).

Some are both (Alice).

Mapping to OOP, it would be straightforward to have three classes, like:

```<code>class Worker extends Person

class Student extends Person
</code>```

But that's ok as long as the specialization is disjoint: object alice can't be instance of Worker and Student at the same time.
If you get a list of Person objects, you cannot cast the same element to both subclasses.

First of all, is there any specific name for this (likely common) impedance mismatch case?

Next, suppose you can't remodel the schema. I may have my own way to workaround with OOP, but I'm mainly interested in yours. Is there some sort of best-practice guideline?

This example has only two ISA relations, but my impression is, the more non-disjoint sub-entities, the more OOP gets uncomfortable.

答:
One way to do this would be to model this in the application using composition:

```<code>//maps to the table PEOPLE
class Person
{
   String name;
   Date birthdate;
   GenderEnum gender;

   Worker workerAttributes;
   Student studentAttributes;
}

//maps to the table WORKERS
class Worker
{
   String name;
   String company;
   Date since;
}

//maps to the table STUDENTS
class Student
{
   String name;
   String institution;
   Date since;
}
</code>```

Each Person object contains an object containing Worker information and Student information. When you populate these objects, you would have to ensure that you've joined to the correct Person.

Title: How to ORM non-disjoint specializations

Body:
One way to do this would be to model this in the application using composition:

//maps to the table PEOPLE
class Person
{
   String name;
   Date birthdate;
   GenderEnum gender;

   Worker workerAttributes;
   Student studentAttributes;
}

//maps to the table WORKERS
class Worker
{
   String name;
   String company;
   Date since;
}

//maps to the table STUDENTS
class Student
{
   String name;
   String institution;
   Date since;
}

Each Person object contains an object containing Worker information and Student information. When you populate these objects, you would have to ensure that you've joined to the correct Person.


问:
Is this type of data insertion safe and can stop sql injection in Python?
I am learning Database connection from MySQL Connector/Python Developer Guide.

This is the code I am using to insert data:

```<code>conn = mysql.connector.connect(user="user", password="password", host="127.0.0.1", database="db")
cursor = conn.cursor()
query = ("INSERT INTO test(name,email) VALUES(%s,%s)")
data = ("cool", "cool")
cursor.execute(query, data)
conn.commit()
cursor.close()
conn.close()
</code>```

Is this type of data insertion safe and can stop sql injection?

答: Yes.  According to the documentation, this is the correct syntax for specifying and executing a query with parameters.  Parametrized queries are immune to SQL injection; SQL injection can only occur when you mix user input directly into the query string instead of separating it out.</p>


答:
I've been using TiddlyWiki to gather some ideas that would not necessarily make a coherent text...  This gets you a single HTML file that contains a Wiki that anyone can edit.

Compared to a real Wiki, this is much easier to setup, and it can be stored in your source tree so that it 'follows' the branches and the changes between them.  On the other hand, it's not something that can be edited by several person simultaneously.

Title: Documenting higher-level concepts

Body:
I will be leaving my current project in a few days, and as part of securing my knowledge I have been asked to add comments to the code wherever I feel that can add value.

The problem I am running into now is that the comments I want to write are not really suitable as comments, because they do not pertain to a single entity in the code (a few lines, a function, a class or even a file), but they are more about how two or more entities interact with each other or about a feature whose implementation is spread over multiple entities.

So, how do you go about documenting the stuff that does not belong to a single entity but is important to know to understand the bigger picture?

And also: Where do you document it? In the source file or in an external document?

As an example, we have a client-server architecture in C (with the client and server both running on the same embedded device). To avoid flooding the server, the client has a mechanism to throttle the sending of similar requests to the server such that a request can only be sent if the previous one has been answered.

The innards of this mechanism are spread over multiple functions.

Where would you place the documentation of such a feature, especially if the file with the functionality also has some other, unrelated, functions?

Edit: Extended the question a bit.


问:
Pre-processor usage to separate logic to different versions of product
In the .NET code base of a product, there are #if pre-processor statements to define whether certain functionality should be available. Like so:

```<code>shared logic

#if version1
    some logic
#endif
#if version2
    some other logic
#endif
</code>```

Personally I twitch at this structuring. I find it harder to read, and it makes me nervous for some reason.

I was told that the reasoning behind having it like this is that there are too many changes that happen in all of the versions.  If the versions were stored in separate repositories or some other method, then any future changes would have to be implemented several times over.

I find the "too much to change" argument a bit vague, but I'll admit my experience with this kind of design is limited.

Is this really the best practice or the most common approach when it comes to handling multiple product versions with differing functionality?  Is there a better alternative?

答:
I'd avoid having separate code bases. All that branching and merging creates lots of unnecessary maintenance work. Even worse when they get out of sync it becomes hard to determine which differences were intentional and which by mistake.

I prefer replacing #if preprocessor directives by ordinary if statements, that way all variants of the code need to compile and refactoring tools see all the code.

Beyond this simple general change you should look into refactoring the code, but how to do that depends on the nature of the differences.

Some suggestions:

Don't mix different variants within a single method. For example you could replace your code with:

```<code>SharedPart();
if(cond1)
    Variant1();
if(cond2)
    Variant2();
</code>```

Use delegates, interfaces or virtual methods to dispatch to the different variants instead of if statements.

Inject* an interface containing the configuration instead of using global state. This allows you to write unit tests for all variants without recompiling or restarting.

For features that are either enabled or disabled, I'd create a Feature enum, together with an injected* interface that determines if the feature is available. The interface could look something like:

```<code>interface IGateKeeper
{
    bool IsEnabled(Feature feature);
    void Require(Feature feature);
}
</code>```

where Require checks if the feature is enabled and throws a meaningful exception otherwise.

* If you're not familiar with dependency injection (DI) and inversion of control (IoC) learn about them.

OwnerDisplayName: Phil

Body:
I'd avoid having separate code bases. All that branching and merging creates lots of unnecessary maintenance work. Even worse when they get out of sync it becomes hard to determine which differences were intentional and which by mistake.

I prefer replacing #if preprocessor directives by ordinary if statements, that way all variants of the code need to compile and refactoring tools see all the code.

Beyond this simple general change you should look into refactoring the code, but how to do that depends on the nature of the differences.

Some suggestions:

Don't mix different variants within a single method. For example you could replace your code with:

SharedPart();
if(cond1)
    Variant1();
if(cond2)
    Variant2();

Use delegates, interfaces or virtual methods to dispatch to the different variants instead of if statements.

Inject* an interface containing the configuration instead of using global state. This allows you to write unit tests for all variants without recompiling or restarting.

For features that are either enabled or disabled, I'd create a Feature enum, together with an injected* interface that determines if the feature is available. The interface could look something like:

interface IGateKeeper
{
    bool IsEnabled(Feature feature);
    void Require(Feature feature);
}

where Require checks if the feature is enabled and throws a meaningful exception otherwise.

* If you're not familiar with dependency injection (DI) and inversion of control (IoC) learn about them.

OwnerDisplayName: CodesInChaos


答:
I've been in this boat. It's not fun.
It can't always be a matter of using a runtime test:

```<code>if (IsConfigOne)
    ConfigOneImpl();
if (IsConfigTwo)
    ConfigTwoImpl();
</code>```

Because of dependencies that are mutually exclusive (ie, I can't reference ConfigOneImpl() when I'm in ConfigTwo because that would reference assemblies I don't have in ConfigTwo...).

In general, you're better off building an abstract class that implements most of the functionality and concrete classes that are made for each individual implementation.  In your case, you might have something like this:

```<code>public abstract class SomeThing {
    public void Logic() {
        CommonLogic();
        SpecificLogic();
    }
    protected void CommonLogic() { /* ... */ }
    protected abstract void SpecificLogic();
}

public class SomeThingImplConfig1 : SomeThing {
    protected void SpecificLogic() { /* ... */ }
}
</code>```

I've encountered other cases where this doesn't work and was in a position where I couldn't adapt or modify things because either didn't own those classes or was bound by other constraints, I tried to isolate specific code in partial classes.  For example, I had to build 3 different configurations of a set of classes that could work with unmanaged support routines, equivalents in pure managed code and equivalents for Silverlight, so I was able to isolate those by using 4 partials, one for all the shared code and interfaces, and 1 for each of the specific configurations.

Finally, there were some classes not available in Silverlight (System.Drawing, IIRC), but there were equivalents in Silverlight that had members with the same names (but were not compatible through an interface). Under those circumstances, I could use a C# type alias to make the Silverlight objects follow the System.Drawing equivalents:

```<code>#if SILVERLIGHT_CONFIG
using Rectangle = System.Windows.Rect;
#endif
</code>```

Title: Pre-processor usage to separate logic to different versions of product

Body:
In the .NET code base of a product, there are #if pre-processor statements to define whether certain functionality should be available. Like so:

```<code>shared logic

#if version1
    some logic
#endif
#if version2
    some other logic
#endif
</code>```

Personally I twitch at this structuring. I find it harder to read, and it makes me nervous for some reason.

I was told that the reasoning behind having it like this is that there are too many changes that happen in all of the versions.  If the versions were stored in separate repositories or some other method, then any future changes would have to be implemented several times over.

I find the "too much to change" argument a bit vague, but I'll admit my experience with this kind of design is limited.

Is this really the best practice or the most common approach when it comes to handling multiple product versions with differing functionality?  Is there a better alternative?

Body:
I've been in this boat. It's not fun.
It can't always be a matter of using a runtime test:

if (IsConfigOne)
    ConfigOneImpl();
if (IsConfigTwo)
    ConfigTwoImpl();

Because of dependencies that are mutually exclusive (ie, I can't reference ConfigOneImpl() when I'm in ConfigTwo because that would reference assemblies I don't have in ConfigTwo...).

In general, you're better off building an abstract class that implements most of the functionality and concrete classes that are made for each individual implementation.  In your case, you might have something like this:

public abstract class SomeThing {
    public void Logic() {
        CommonLogic();
        SpecificLogic();
    }
    protected void CommonLogic() { /* ... */ }
    protected abstract void SpecificLogic();
}

public class SomeThingImplConfig1 : SomeThing {
    protected void SpecificLogic() { /* ... */ }
}

I've encountered other cases where this doesn't work and was in a position where I couldn't adapt or modify things because either didn't own those classes or was bound by other constraints, I tried to isolate specific code in partial classes.  For example, I had to build 3 different configurations of a set of classes that could work with unmanaged support routines, equivalents in pure managed code and equivalents for Silverlight, so I was able to isolate those by using 4 partials, one for all the shared code and interfaces, and 1 for each of the specific configurations.

Finally, there were some classes not available in Silverlight (System.Drawing, IIRC), but there were equivalents in Silverlight that had members with the same names (but were not compatible through an interface). Under those circumstances, I could use a C# type alias to make the Silverlight objects follow the System.Drawing equivalents:

#if SILVERLIGHT_CONFIG
using Rectangle = System.Windows.Rect;
#endif

OwnerDisplayName: plinth


答:
It depends if your versioning problem is a compile-time or run-time problem.

For instance, you might want to be able to support a legacy message format in your API. That's a run-time problem because both code paths are still available within your application and can be called arbitrarily. It requires a run-time solution: DI, ifs, delegates, etc. They are really well covered by CodesInChaos' answer.

If you only want to build an older version of your code for legacy purpose, then the solution is clearly a compile-time solution. Even in a very large code base, I would still prefer to depend on a source control system for this and not on pre-processor conditions.

I would choose this path because, to my experience, the reasoning you mentioned is flawed. It doesn't matter how you store your many code-bases. Whether they are in different files or the same one, you still have multiple versions of the same code to maintain. Merging should not be an issue because changes to incompatible logic will never reflect one to one in a different code-base. It needs to be implemented independently. If it does, then your logic is not incompatible which indicates an architecture/factoring problem in your code. Aka, you are not reusing everything that you can.

On the other side, dealing with twice as much code in a function, separated through pre-processor conditions that have no concept of scope, quickly turns code into a huge and unreadable mess. You can end up having conditions that crosses scopes and the only way to understand what is really going on is by doing the pre-processor's job yourself. After-all, there is a reason why C++ developer considers the pre-processor like a demon that should have never existed. The only solution to this problem is the use of run-time if conditions to force the use of scoped logic. I would still avoid going this way because they can have a strong negative impact on performances if they are used in a critical path.

In the end, it all boils down to using the right tool for the job and an automatic text replacement tool is not the right tool to handle code versioning.

OwnerDisplayName: Etienne Maheu


问:
What is the purpose of Deprecation?
Is it just giving different names to previously named method? Does it change with the language you use? Is it essential? I have noticed different APIs having deprecated methods, which actually seem easier to use.</p>

答: It usually means that any code marked as deprecated is considered old and out of date, or it may have potentially serious issues with performance/conformity to standards/platform-specific issues/security/compatibility/etc..., and that there is probably a better replacement. It is marked as deprecated to indicate that developers writing new code should avoid that deprecated code, but it is left in the API so that old code that was written before the code marked as deprecated will still function without needing to be re-written. </p>

Title: What is the purpose of Deprecation?