答:
Is Python interpreted (like Javascript or PHP)? is worth a read for more information and it says:

...different implementations of languages may do different things. These days you can find both C interpreters and Javascript compilers.

Compiled and interpreted are descriptions of an implementation, not of a language;  Their usage in relation to languages is a throwback to the days when each language had few implementations and similar (simple) toolchains compared to the kinds of functions you might find in an IDE today.

There are layers of interpretation/compilation...

Pure interpretation

Tokenisation + interpretation

Bytecode compilation which requires a virtual machine to host

Bytecode + 'just in time' compilation to Machine code

Native Machine code compilation

Different Python environments use different options, cpython does only a bytecode compilation, where Psyco uses a bytecode + JIT approach.

New languages and implementations frequently use the Bytecode + JIT approach as it is the best way to make them portable and enables the application to make use of more features of an unknown host environment.

In terms of the language itself the descriptions are used as a shorthand for the level of abstraction.  With high-level languages like Python where performance consideration and optimisation is far removed from the programmers remit often described as being interpreted, where low level ones like C where those considerations are closely tied are considered compiled.

To answer to your question - Python as most people use it is PARTIALLY COMPILED and it would be right to consider it BOTH compiled AND interpreted.


问:
Exposition of Data Representation
I would like to know how the data representation is exposed in slide 7 of information hiding:

Modifying an exposed data representation propagates to all code which directly accesses that representation

Perhaps the best example of the impact this can have is the Year 2000 problem

Legacy software for applications as diverse as nuclear power station control, air traffic control, finance, and the military were coded using exposed data representations

To ensure the software will work correctly come 2000 every single place that uses the date representation needed to be changed to store years using 4 digits rather than 2

The cost of this conversion has been estimated in billions of dollars!

Exposed data representation leads to change propagation ... affects maintenance costs ... big trouble

I would also really like to know whether information hiding means 'hiding the data using visibility identifiers(public,private)' or whether it means 'hiding data representation'.What actually does data representation mean?Could anyone help me.

答:
How? Well, by making it public and writable.

The data representation in this case is an int value for each Date component, but you'll notice that this isn't actually a particularly fitting choice - day numbers do not range from –2,147,483,648 to 2,147,483,647, they range from 1 to 31. The point is not so much keeping it a secret from the API clients that the day number is stored as an int but to prevent them from invoking the full representational power of int when manipulating a Date.

With public fields, every user of the class has as much power over the values as the writer of the class: absolute power. In particular, they can set nonsensical values (e.g. dayOfMonth = 50) or values that are fine in themselves but conflict with other values (dayOfMonth = 31, month = 2), or values that are even more subtly wrong (dayOfMonth = 29, month = 2, year = 2001). This kind of restriction of the possible values and value combinations is exactly what the class is ideally suited for, but it can only do its job correctly if nobody else has the same power. That is why it's a good idea to have an advanceDay() method instead of publicly writable fields.

ContentLicense: CC BY-SA 3.0

Title: Exposition of Data Representation


问:
Why 'String' objects are immutable with an explicit constructor in java?
It make sense to make class String objects immutable with following declarations, because they share the same storage in common pool.

```<code>String str1 = "abc";
String str2 = "abc";
</code>```

But, am not sure, if it make sense to have class String objects immutable with following explicit constructor declarations, because they do not share the same storage in heap.

```<code>String str3 = new String("def");
String str4 = new String("def");
</code>```

So, if the content of a class String object has to be modified frequently, it is recommended to learn class StringBuffer and class StringBuilder.

Does it make sense to know, What is the reason that class String has been designed to maintain immutable content with an explicit constructor?

答: The explicit constructor is a so-called copy constructor. It's intended for the rare case where you need to make sure that you receive a new String instance instead of a pooled one. The newly created string still is immutable, as you can't modify the passed in string reference.</p>


问:
Why is python treated as a interpreted language when it has a compiling stage?
Why is that python is treated as only an interpreted language when there is in fact a compiling stage where the code we write gets converted into byte code(.pyc), which is later interpreted by the PVM. Is it wrong to say python is just an interpreted language?</p>

答:
Unlike .NET and Java, there is not a well-defined standard for python byte code, and they sometimes change it from version to version. See also this question.

This has the implication that you can't really distribute the compiled version of your code, which in turn means, that you can't really consider it a compiled language.


问:
What level/format of access should be given to a client to the issue tracking system?
So, I used to think that it would be a good idea to give the customer access to the issue tracking system, but now I've seen that it creates less than ideal situations, like:

Customer judging progress solely on ticket count

Developers denied to add issues to avoid customer thinking that there is less progress

Customer appointing people on their side to add issues who don't always do a good job (lots of duplicate issues, insufficient information to reproduce, and other things that distract people from doing their real job)

However, I think customers should have access to some indicators or proof that there is progress being done, as well as a right to report bugs.

So, what would be the ideal solution to this situation?, specially, getting out of or improving the first situation described?

答:
I think some transparency is needed. Customers are expecting it and it can separate you from a competitor that doesn't take that extra step.

For example, you may want your customers to see the status of their request, such as "open" or "closed" in their interface. On the other hand, the admin could have a wider array of statuses that would be invisible to the customer. This helps us to keep customers in the loop.


问:
What is the best C++ interview question?
If you could ask a C++ programmer one question to measure their C++ skills, what would it be?

The question I think is best is: Can you call "delete this;" inside a member function? (I put this as a link so you can think it through first, then go to The Best C++ Interview Question – Ever! to see the correct answer.)

I don't ask this because I expect most people to know the answer. If they did it would not be that useful a question. I ask to see if they can work their way to the correct answer and how they do so.

答: Tell me about the copy constructor.

ContentLicense: CC BY-SA 2.5

Body: Tell me about the copy constructor.


问:
Starting Execution of Java Program
While reading about Java Programming I couldn't get why it states Java static main necessity reason is because "before you're program starts,there aren't any objects to send messages to" as said in slide 8 of static variables.

The reason why I couldn't get this is why do you need an object to execute a program. I think in C program they haven't invoked any object to perform execution of C program.

Also since machine language is a sequence of instructions why should we consider objects here when the Java bytecode is also almost an machine language.

答:
The fundamental problem is that you need to have an entry point - the earliest of your code that will run once the program is started. That must be something allowed by the language of choice. Non-member functions are allowed in C and C++ but not in Java.

However static member functions are very close to non-member functions (you can simply call a public static member function of any class without instantiating an object just as you would call a non-member function) and are allowed in Java and so that's the choice for how the entry point is defined.

Yes, you could perhaps have a non-static member function being used as an entry point, but which object would it be invoked on? This could be done for example by specifying a specific class as holding an entry point function (using some attribute or program configuration file or whatever else) and the runtime would instantiate it and call the member function on the object. However this is an unnecessary complication - you can have all that with a static member function used as an entry point. Once control gets there - just instantiate whatever you want and call member functions thereof.

Title: Starting Execution of Java Program


问:
Simple and Composite transactional services: Question about separation of concerns and transactions
I believe I know the answer to this but I'm looking for any holes or anything I may be missing.

This is focused on Spring and Java but could really apply to any programming stack.

Anyway, we have a typical service layer annotated with @Transactional in Spring.  For example, we could have:

```<code>EmailService
OrderService
HistoryService
</code>```

Now, the user performs an action that calls a RESTful service that does the following:

```<code>orderService.create(....);    // wrapped in @Transactional
historyService.create(....);  // wrapped in @Transactional
emailService.emailUser(....); // wrapped in @Transactional (also annotated with @Async)
</code>```

While all of these are called from a controller (which is NOT @Transactional), if either the order service or the history service fail, I want both to be rolled back and the email service would abort.

I don't like mixing the services.  I think it would be ugly to have the order service call the history service just so that both of them are in the same transaction boundaries.

My first instinct was to create a hybrid service that would wrap both services together.  Something like:

```<code>@Transactional
public void orderEntryService.create(....) {
    orderService.create(....);    // STILL wrapped in @Transactional
    historyService.create(....);  // STILL wrapped in @Transactional
}
</code>```

This way, my controller could be:

```<code>public String create(...) {
    orderEntryService.create(...);

    emailService.emailUser(...);    // this is @Async
                                    // and will never be called if previous
                                    // orderEntryService.create fails
}
</code>```

While I think this keeps my service layer cleaner, it can quickly start adding up to bulky and forgetful "aggregate" service classes. How to handle this?

答:
I understand your doubts, because such service-mixins don't look natural for me either.
But why? Strictly speaking, even in complete SOA architecture service composition is not forbidden. But your case is different. Your services are not independent units located in own processes with independent transaction management. Your services are just level in your single-process architecture, plus methods of your services are wrapped in database-transactions. So, service composition could lead to nested transactions which itself is not a problem for Spring, but still looks unnatural for me. Plus, such composition could lead to circular dependencies between your services which is evil without a doubt.

You could solve your problem by adding one more level(let's say DataAccess) in your architecture, which will contain repositories: EmailRepository, OrderRepository, HistoryRepository. Here you will have methods for managing emails, orders, history etc: adding, updating, deleting, querying. And you could share these repositories in your different services, having transaction wrappers where they are now - around your services.

It's just the simplest solution that could help you, not talking about more sophisticated approaches such as DDD.


问:
architecture of database heavy application
A program I'm currently designing makes heavy use of the database, almost anything the user does will alter the database, or read from it. Now I have one interface which defines all these operations, and one database class which implements it.

The result is that that class is huge, it contains logic for creating users, editing them, creating events, showing events to the user, editing, adding friends, adding items to a product, ....

On the one hand I can argue this does not violate SRP, because the whole use is database communication. On the other hand, this is a lot of code for one class.

Are there any design patterns that solve this, or is this acceptable?

答:
Yes, I think you are violating the SRP. Not because you kept all of your database code in one class, but because you have database code for completely different entities (users, products, events, friends) all in one class. At the very least, separate your code into classes by the entity it's most closely related to. If you're looking for design patterns, you might want to read about the Data Access Object pattern as a place to start.

If your application really is sooooo "database heavy", it's also worth considering that some of your logic could be moved out of your application's code and into stored procedures/functions within your database. That would make your application's code a little more manageable, but you would have to maintain code in two different places.


问:
How to move php documentation closer to standards?
I have an large php project. I used to document it with NaturalDocs, but I didn't include the documentation generation in the build process for a long time ( years ).

I recently started using composer and looked into PSR. The only standard way to document my code seems to be docblocks for phpdocumentor.

Since my code is only in part object oriented and contains much procedural files, I cannot only rely on documenting classes and functions, but I have alot of file level documentation.

It turns out that page level docblocks are not well supported in phpdocumentor ( see https://stackoverflow.com/questions/26925742/page-level-docblocks-and-phpdocumentor-templates ). Therefore I'm really stuck now.

To conclude my questions :

Does it make sense to document non object oriented code with docblocks and phpdocumentor ? Is phpdocs a good choice here ? Is my approach to professionnalize the documentation of our project viable or is it somehow flawed ?

答:
I still think it makes sense to stick to phpDoc to document PHP code. It is the standard recommended by the php PSR project. It is also generalized into the annotations concept, as it is used for instance in Doctrine.
Another argument for phpDoc is that Javascript and many other languages have it's analoguos commenting system.

After much time spent to try to get phpDocumentor work, I generated the documentation with Doxygen. There are clear advantages over phpDocumentor:

It works out of the box. There is no need to deal with hosts of bugs.

Flexibility: there are many more options with doxygen.

Page level docblocks work out of the box (starting the docblock with @file).

It is possible to document all entities, even thoug they have no doc. This allows you to get a complete doc of all classes, functions and vars in the project, without starting to document. This goes with the DRY principle and allows you only to document manually what is important. You can document the bigger picture and let Doxygen enumerate all function arguments...

It's faster to generate the doc

The doc is nicer.

The only drawback I found is that you cannot stick 1 to 1 to the PSR-5 standard proposal :

@var is deprecated in favor of @type, but doxygen understands only @var.

@file is necessary, but doesn't exist as tag phpDoc.

But phpDocumentor does not honour phpDoc standard neither (e.g. the recommended way to describe hashes is not understood by phpDocumentor).

Conclusion

Having a complete documentation of the code is a must. It simplifies work and gives relief.

For me documentation is crucial, therefore it is difficult to understand that PHP Framework Interop Group issues recommendations about documentation, that no documentation generator compies to.


答:
When talking about a system (or a module, or class, or structure), there are two representations of data : internal and external (I don't want to call them public and private as not to mix their meaning with OOP). The external is representation that is used by every single thing that is using a system. There is a risk, that changing this external representation will require change of every thing that depends of this representation. You rarely have full control of all of those things. Internal representation on the other hand is only in one place and accessed by controlled set of functions (do not mistake with function in programming language). When this representation changes, only those functions have to change. So change is much easier (and thus cheaper) for internal representation than external representation.

The Y2K problem was caused by one simple fact: that the internal representation was also an external one. Every single piece of code relied on a fact, that year is represented as 2 digits and that before those there is always 19. If, on the other hand there was a clear separation, then the internal representation would use the two digits, but the external would be full year (all 4 digits). This would mean that only thing that needs to change would be the internal representation and function that converts the internal to external representation (and other way around).

Title: Exposition of Data Representation

Body:
I would like to know how the data representation is exposed in slide 7 of information hiding:

Modifying an exposed data representation propagates to all code which directly accesses that representation

Perhaps the best example of the impact this can have is the Year 2000 problem

Legacy software for applications as diverse as nuclear power station control, air traffic control, finance, and the military were coded using exposed data representations

To ensure the software will work correctly come 2000 every single place that uses the date representation needed to be changed to store years using 4 digits rather than 2

The cost of this conversion has been estimated in billions of dollars!

Exposed data representation leads to change propagation ... affects maintenance costs ... big trouble

I would also really like to know whether information hiding means 'hiding the data using visibility identifiers(public,private)' or whether it means 'hiding data representation'.What actually does data representation mean?Could anyone help me.


答: You can say that when we're talking about Python as a whole; including compiler that creates byte code and a virtual machine that interprets the byte code. Python as an language has no saying about if it's an compiled or interpreted programming language, only the implementation of it. Often with semantic issues, there are programming languages where the user can choose to compile the code into byte code to be interpreted at run time or compile it directly into machine code.</p>

Title: Why is python treated as a interpreted language when it has a compiling stage?

Body: Why is that python is treated as only an interpreted language when there is in fact a compiling stage where the code we write gets converted into byte code(.pyc), which is later interpreted by the PVM. Is it wrong to say python is just an interpreted language?</p>


答:
On the one hand I can argue this does not violate SRP, because the whole use is database communication.

You could also say you have a single class in your application, because the whole class does processing of data.

It doesn't work like this. If your class has:

a mix of different abstraction levels;

a mix of things that can be described as separated by "and" (your class manages users and items of a product and events etc);

things that are modified for different reasons;

then you should split along those lines.

It may be still acceptable to keep everything in a single class, but then the class' role should be "provide single access point for all DB operations".

In that case, your class should be an extremely thin class, simply forwarding calls to various sub-components and not needing alterations when (for example) the data model for users changes.

From my list above, you can extract one or (preferably) more refactoring guidelines:

split by abstraction level / operation type / DB query type

split by entity type (user data model, product data model, etc)

split by categorizing data models (user management tables and operations, products - and their subitems, prices, offers, etc)

Title: architecture of database heavy application

Body:
A program I'm currently designing makes heavy use of the database, almost anything the user does will alter the database, or read from it. Now I have one interface which defines all these operations, and one database class which implements it.

The result is that that class is huge, it contains logic for creating users, editing them, creating events, showing events to the user, editing, adding friends, adding items to a product, ....

On the one hand I can argue this does not violate SRP, because the whole use is database communication. On the other hand, this is a lot of code for one class.

Are there any design patterns that solve this, or is this acceptable?


问:
Multiple websites and applications using one user database
I've got several applications and websites that will be built around one main application. In a perfect situation users will be able to register once and be able to log into the different applications and websites using that single account. The different parts will be:

Main application (Windows application) that uses the account to get access to it's features and to the server.

Second application with it's own specific tasks (Also a Windows Application) that uses the account to get access to it's features and to the server.

Main website which is based on Wordpress. The website has a bbPress forum that would use the account.

Data server which can be accessed for specific data using the account.

Most of the data that the users have will be the same for the different applications and websites so to me it seems that having a database for each separate part would complicate things more than having one database for everything.

My main concern is the Wordpress site and bbPress forum because of the fact that these already have their own account systems.

What would be a valid approach? Using one of the existing databases from Wordpress or the forums with the risk of having a lot of Wordpress/bbPress specific data with the accounts or making a database especially for the other applications and websites and somehow linking those to the website and forum databases? Would the valid approach be secure for use by these different applications and websites?

答:
I would recommend separate databases for the applications  and one database for the user accounts.

I would put any fine-grained access control within the individual applications.

I would also look to make the one 'user database for the user accounts' be accessed via an authentication service using industry standard protocols such as LDAP.


问:
Would you use C, today, for a software project?
If yes, where and why would you use it?

If no, please provide an explanation to why C is not acceptable to you.

答:
C++ is portable across platforms and embedded devices like microcontrollers.
(C++ can be compiled to C, therefore microcontrollers.)

C is even portable (as foreign functions) to other languages. Therefore, iff I program low-level libraries, then I want more compatibility than C++.

Haskell is portable across platforms (ARM is coming soon) but NOT embedded devices like microcontrollers. Its speed is comparable to C and C++; but because it is functional, it uses a garbage-collector instead of an runtime-stack, therefore it can be faster and slower than C at different times (garbage-collecting) and in different situations (continuations instead of sub-routine calls).

I choose the most abstract language possible, because the program speed does not differ but the development time and bug-rate. C and C++ differ much, but not from the point of view of Haskell.

I do not prefer other languages, even though I know one or two hand full.
…except in a few cases, well, bash.


问:
Who is responsible for stream positioning?
The samples in question are c#, but it applies to any language.

If you have a function which reads content from a stream. Who should be responsible for ensuring that the stream position is correct before reading?

The caller, or the function doing the reading?

e.g.

Caller positions the stream:

```<code>    public byte[] ReadBytesFromStream(Stream inputStream)
    {
        using (var ms = new MemoryStream())
        {
            inputStream.CopyTo(ms);
            return ms.ToArray();
        }
    }

    public void DoThingWithStream(Stream stream)
    {
        // .. do some stuff
        stream.Position = 0;
        var bytes = ReadBytesFromStream(stream);
        // .. do some more stuff
    }
</code>```

Reader positions the stream:

```<code>    public byte[] ReadBytesFromStream(Stream inputStream)
    {
        inputStream.Position = 0;
        using (var ms = new MemoryStream())
        {
            inputStream.CopyTo(ms);
            return ms.ToArray();
        }
    }

    public void DoThingWithStream(Stream stream)
    {
        // .. do some stuff
        var bytes = ReadBytesFromStream(stream);
        // .. do some more stuff
    }
</code>```

The reader positioning the stream means that I can call the function over an over again with the same stream and get the same bytes out.

The caller positioning the stream means that

It's a little more work to set up and if you're throwing the stream around a lot there may be a lot of re-positioning going on. But,

I could use the same reader function to read from an arbitrary point in the stream if I really wanted to.

I've pretty much convinced myself that the caller should do the positioning, but if that's the case then are there any circumstances when it shouldn't?

答:
The caller is responsible for putting the Stream in a suitable state to be consumed by the reader. There are two main reasons:

Not all streams support repositioning. You should only set the Stream.Position property if that Stream.CanSeek. Otherwise, you'll get an exception. (see the Stream.Position documentation).

“Reading from the beginning” is a special case of simply “reading”. It is generally advisable to write your functions as general as possible (as far as it's sensible, compare also YAGNI). If we frequently need a special case, we can always add a convenience wrapper with very little effort. However, getting a general function out of a special-cased function is not possible (or requires refactoring of the code).

Especially when creating a public interface is it important to make this interface composable. One possibility would be to pass in the wanted location as a parameter. This works in general, but not in this specific case because not every Stream.CanSeek.

And then there's also the matter of avoiding “spooky action at a distance”. It's irrelevant what your function does as long as the effects are contained inside that function. However, mutating non-local state can lead to hard to locate bugs. If functions have side effects or unexpectedly mutate their arguments, this should perhaps be reflected in their name, but certainly in their documentation. In this case, it's expected that the reader function will advance the position by reading from the stream. However, it's probably not expected that the reader will reset the position first.

If we work backwards from that, we can find a few cases where the reader method should set the position:

In the context of your application, you'll only ever want to read streams from the beginning, and read the same stream multiple times. You've documented the behaviour that, as a convenience, the reader method will reset the position first.

The method is private. That's a carte blanche to ignore any argument referring to “composability”, since you control all uses of that method.


问:
Does class Availability makes programming as Object Oriented Language?
Does class Availability makes programming as Object Oriented Language ?

Most of the people think that if there is Availability Class in a language, then that language becomes Object Oriented. Is it true ?

According to me, its not class that makes the language object oriented, but the OOP Concepts that makes the Language Object Oriented right ?

If Class makes a language object oriented then Javascript is not a object oriented language, but JS is a object oriented language without any Class being implemented.

It also brings me to ask one more question, Can we implement all the OOP Concepts in JS ? i.e

Inheritance
Data Abstraction
Polymorphism
encapsulation

Please let me know whether my understanding of JS is right or no ?

答:
No, (1) classes don't automatically make an object-oriented language nor does (2) lack of them make a language non-OO.

An example of (1) is Java: Java has classes, but that doesn't make Java OO; in fact, classes in Java are used for defining Abstract Data Types, in order to define objects, you need interfaces. It's the interfaces that make Java OO, not the classes.

An example of (2) is Self: Self is an object-oriented language with no classes.

JavaScript allows you to implement objects easily, by using what JavaScript calls "objects" (which are actually not objects in the sense of OO) in conjunction with closures. Whether or not that makes JavaScript an "object-oriented language" really depends on your definition of what an "object-oriented language" is. Is it a language which makes OO possible? Is it one that makes OO feasible? Is it one that makes OO easy? Is it one that guides you towards OO? Is it one that forces OO? Is it one that makes OO affordable?

You can use OO in assembly, if you want. Does that make assembly OO? (In fact, in one of his talks, Alan Kay has mentioned that he discovered a paper from 1953, which describes pretty much exactly his vision of OO, implemented in assembly.)


问:
MPL: Can I safely build software that uses this license without having my hands tied legally?
I work for a very large company that would like to use RabbitMQ.

RabbitMQ is licensed under the Mozilla Public License, v1.1

https://www.rabbitmq.com/mpl.html

The problem scenario, as I understand it, is this:

Just say a contributor to RabbitMQ decided to sue our company for any reason

If we countersue, then we lose all license to use RabbitMQ, because we can't legally use the code that was contributed by that contributor anymore.

Therefore any work we've put into using it (ie integrating it into our toolset), could be potentially wasted.

This may seem contrived, but from my understanding, there are some very large contributors to the RabbitMQ code base.... Some big companies like Rackspace or something like that. And the possibility of them suing the large company I'm in is not inconceivable ;-)

Thanks for any insight!

答:
It appears that you have not carefully read the license.

Termination of the type you describe only applies to patent infringement claims.

Termination only applies to the rights granted to you by the infringer, not to your rights to use the software.  The license is very specific about that.

You're given time to work out the problem with the infringer.  This is also true of breaches to the agreement made by you; you're given 30 days to remedy the breach before your license terminates.

Basically, it's saying you can't have your cake and eat it too.  You can't claim that one of the contributors is violating a patent, while at the same time taking advantage of their contributions.


问:
What is the point of making a syntactic distinction between standard and user-defined types?
Although here I will refer specifically to C++ and Bjarne Stroustrup's naming conventions, in principle, I've seen that people use somewhat similar rules for other languages here and there.

So, the basic idea is that one should be able to distinguish standard types from user-defined types while reading the code. For instance, Bjarne Stroustrup suggests that one uses

an initial capital letter for types (e.g., Square and Graph)

which, taking into account that

The C++ language and standard library don't use capital letters

allows achieving the goal mentioned above.

But why do we need to do so? What can be the purpose of distinguishing standard and user-defined types?

I could not find any Bjarne Stroustrup's reasoning on that matter, and besides, I myself think in diametrically opposite way. :D I know, I know, "Who am I to dispute Stroustrup?" But, listen, a bunch of the C++ language features, e.g. operator overloading, serve the purpose to allow user-defined types a similar level of syntactic support as standard types. And then all this is baffled by a different naming discipline...

P.S. Not to mention that often one word is not enough to name a class and an underscore-separated word that starts with a capital letter looks so foreign.

答:
There is absolutely no purpose or benefit in such. One of the goals of C++ was to treat UDTs and primitives interchangably, and whilst they haven't entirely succeeded, this is one area where you don't have to differentiate.

When it comes to naming, Stroustrup is nuts, and this is a scientifically-proven fact.


问:
Unit testing the variables passed to the view from the controller
Let's say I want to test a controller that gets some value from a service and then pass some of all of those values to the view.

Do you test that the view gets the result that the controller took from the service, without taking care of seeing the exact variables being passed, or do you test specifically for the variables that you need on the view?

So if in the view you have var 'foo' and 'foo2', you can test that the controller is simply passing the info it gets from the service, or you can test that the variables being passed are effectively called 'foo' and 'foo2'.

What approach do you use?

答:
This is where you have to apply a combination of dependency injection and mock tests. You would test the service and controller & view separately. Do this by mocking the service to return a recorded value and then test if you controller end up with this recorded value. </p>

<p>TDD is unit testing. You shouldn't test the coupled configuration (which is integration testing).
Test the 2 modules separately as explained above. </p>

Body:
This is where you have to apply a combination of dependency injection and mock tests. You would test the service and controller & view separately. Do this by mocking the service to return a recorded value and then test if you controller end up with this recorded value.

TDD is unit testing. You shouldn't test the coupled configuration (which is integration testing).
Test the 2 modules separately as explained above.


问:
How do you go about training a replacement?
I recently asked about leaving a position and got a lot of great answers. One of the common threads was that being around to train the new person would be expected and could go a long way.

Now considering that (I think) most people don't stay at a company for a long time after they've given notice, and it will take time for the company to interview/hire one - that leaves for a short amount of time to get someone up to speed.

I've also never trained anyone before. I did a bunch of tutoring in University and College, but teaching a language/technology is far different from training someone to replace you on your job.

So the question is: how do you go about training someone to replace you in a, potentially, short amount of time?

答: You tend to quickly finish what you're doing or at least get it to some stopping point. Then the documentation/brain dump starts. I've been at places where the new hire wasn't familiar with some of the technology (Had to maintain an ASP site.). Had about enough time to explain where all the code was and how to update the site (Finding the production server itself was not hard because it sat under my desk; if that gives a little indication why I left.). </p>


答:
With python, you can enter a line of code into python and expect it to be interpreted and executed immediately.

Compiled languages like c, java, etc. require a compilation step which render an object that may be executable.  There may be additional steps require to make the code executable.

Unlike an compiled language, an interpreted language can run a command like:

```<code>print "Hello"
</code>```

Body:
With python, you can enter a line of code into python and expect it to be interpreted and executed immediately.

Compiled languages like c, java, etc. require a compilation step which render an object that may be executable.  There may be additional steps require to make the code executable.

Unlike an compiled language, an interpreted language can run a command like:

print "Hello"


问:
Most Efficient way to Compute the sum of divisors of N (1 ≤ N ≤ 1 000 000 000)
I want to write a code which computes the sum of divisors of a number N(1 ≤ N ≤ 1 000 000 000), excluding the number itself.

However, I need an efficient way to do it. It suppose to print the answer under 1 second. I know it depends on hardware etc. But I have an i7 machine though it takes more than a second (for the worst case scenario which is 1000000000 ) because of my poor code.

So to make it more understandable:

EX:
Sample input: 10 --> Output should be: 8 (because we know 1 + 2 + 5 = 8)

EX:
Input: 20 --> Output suppose to be: 22 ( 1 + 2 + 4 + 5 + 10 = 22 )

So far i wrote this:

```<code>public class Main
{
public static void main(String[] args)
{
    @SuppressWarnings("resource")
    Scanner read = new Scanner(System.in);

    System.out.print("How many times you would like to try: ");
    int len = read.nextInt();

    for(int w = 0; w < len; w++)
    {
        System.out.print("Number: ");
        int input = read.nextInt();

        int remains = 1;
        int sum = remains;

        /* All I know we only need to check half of the given number as
           I learned ages ago. I mean (input / 2) :D */

        for(int i = 2; i <= input / 2; i++)
        {
            if(input % i == 0) sum += i;
        }

        System.out.print("Result: " + sum);
    }

}
}
</code>```

So the question is How to improve this solution ? How to make it more efficient or let me put it this way. Is there a way to do it more efficient ?

答:
A much more efficient way would be to factorize the number into prime factors (using existing libraries, although I do not know one by heart).

Say the factorization is a HashMap<Integer,Integer> factorization where each prime factor is mapped to its multiplicity, then one can compute your sum as follows.

```<code>int N = 84684684; //your integer
HashMap<Integer,Integer> primeFactorization = factor(N);
long total = 1;
for (int p:primeFactorization.keySet()) {
    int factor = 1;
    for (int i=0;i<primeFactorization.get(p);i++) {
        factor*=p;
        factor+=1;
    }
    total*=factor;
}
return total-N;
</code>```

This should be much, much faster, since you compute the result largely as a product. For example, for 10 you have 10=2*5 and hence the result is (1+2)(1+5)-10=8. For 20 the result is (1+2+4)(1+5)-20=22.

For 1 000 000 000 = 2^9 * 5^9, the result should hence be (1+2+4+8+...+512)*(1+5+25+...+5^9)-1 000 000 000 = 1497558338. I did this computation by hand, rather than requiring 1 second on an i7 processor.

OwnerDisplayName: John Merih

Body:
A much more efficient way would be to factorize the number into prime factors (using existing libraries, although I do not know one by heart).

Say the factorization is a HashMap<Integer,Integer> factorization where each prime factor is mapped to its multiplicity, then one can compute your sum as follows.

int N = 84684684; //your integer
HashMap<Integer,Integer> primeFactorization = factor(N);
long total = 1;
for (int p:primeFactorization.keySet()) {
    int factor = 1;
    for (int i=0;i<primeFactorization.get(p);i++) {
        factor*=p;
        factor+=1;
    }
    total*=factor;
}
return total-N;

This should be much, much faster, since you compute the result largely as a product. For example, for 10 you have 10=2*5 and hence the result is (1+2)(1+5)-10=8. For 20 the result is (1+2+4)(1+5)-20=22.

For 1 000 000 000 = 2^9 * 5^9, the result should hence be (1+2+4+8+...+512)*(1+5+25+...+5^9)-1 000 000 000 = 1497558338. I did this computation by hand, rather than requiring 1 second on an i7 processor.


问:
Why shouldn't a method throw multiple types of checked exceptions?
We use SonarQube to analyse our Java code and it has this rule (set to critical):

Public methods should throw at most one checked exception

Using checked exceptions forces method callers to deal with errors, either by propagating them or by handling them. This makes those exceptions fully part of the API of the method.

To keep the complexity for callers reasonable, methods should not throw more than one kind of checked exception."

Another bit in Sonar has this:

Public methods should throw at most one checked exception

Using checked exceptions forces method callers to deal with errors, either by propagating them or by handling them. This makes those exceptions fully part of the API of the method.

To keep the complexity for callers reasonable, methods should not throw more than one kind of checked exception.

The following code:

```<code>public void delete() throws IOException, SQLException {      // Non-Compliant
  /* ... */
}
</code>```

should be refactored into:

```<code>public void delete() throws SomeApplicationLevelException {  // Compliant
    /* ... */
}
</code>```

Overriding methods are not checked by this rule and are allowed to throw several checked exceptions.

I've never come across this rule/recommendation in my readings on exception handling and have tried to find some standards, discussions etc. on the topic.  The only thing I've found is this from CodeRach: How many exceptions should a method throw at most?

Is this a well accepted standard?

答:
The reason that you would, ideally, want to only throw one type of exception is because doing otherwise likely violates the Single Responsibility and Dependency Inversion principles. Let's use an example to demonstrate.

Let's say we have a method that fetches data from persistence, and that persistence is a set of files. Since we are dealing with files, we can have a FileNotFoundException:

```<code>public String getData(int id) throws FileNotFoundException
</code>```

Now, we have a change in requirements, and our data comes from a database. Instead of a FileNotFoundException (since we are not dealing with files), we now throw an SQLException:

```<code>public String getData(int id) throws SQLException
</code>```

We would now have to go through all code that uses our method and change the exception we have to check for, else the code won't compile. If our method gets called far and wide, that can be a lot to change/have others change. It takes a lot of time, and people aren't going to be happy.

Dependency inversion says that we really shouldn't throw either of these exceptions because they expose internal implementation details we are working to encapsulate. Calling code needs to know what type of persistence we are using, when it really should just be worried about if the record can be retrieved. Instead we should throw an exception that conveys the error at the same level of abstraction as we are exposing through our API:

```<code>public String getData(int id) throws InvalidRecordException
</code>```

Now, if we change the internal implementation, we can simply wrap that exception in an InvalidRecordException and pass it along (or not wrap it, and just throw a new InvalidRecordException). External code does not know or care what type of persistence is being used. It's all encapsulated.

As for Single Responsibility, we need to think about code that throws multiple, unrelated exceptions. Let's say we have the following method:

```<code>public Record parseFile(String filename) throws IOException, ParseException
</code>```

What can we say about this method? We can tell just from the signature that it opens a file and parses it. When we see a conjunction, like "and" or "or" in the description of a method, we know that it is doing more than one thing; it has more than one responsibility. Methods with more than one responsibility are hard to manage as they can change if any of the responsibilities change. Instead, we should break methods up so they have a single responsibility:

```<code>public String readFile(String filename) throws IOException
public Record parse(String data) throws ParseException
</code>```

We've extracted out the responsibility of reading the file from the responsibility of parsing the data. One side effect of this is that we can now pass in any String data to the parse data from any source: in-memory, file, network, etc. We can also test parse more easily now because we don't need a file on disk to run tests against.

Sometimes there really are two (or more) exceptions we can throw from a method, but if we stick to SRP and DIP, the times we encounter this situation become rarer.

Body:
The reason that you would, ideally, want to only throw one type of exception is because doing otherwise likely violates the Single Responsibility and Dependency Inversion principles. Let's use an example to demonstrate.

Let's say we have a method that fetches data from persistence, and that persistence is a set of files. Since we are dealing with files, we can have a FileNotFoundException:

public String getData(int id) throws FileNotFoundException

Now, we have a change in requirements, and our data comes from a database. Instead of a FileNotFoundException (since we are not dealing with files), we now throw an SQLException:

public String getData(int id) throws SQLException

We would now have to go through all code that uses our method and change the exception we have to check for, else the code won't compile. If our method gets called far and wide, that can be a lot to change/have others change. It takes a lot of time, and people aren't going to be happy.

Dependency inversion says that we really shouldn't throw either of these exceptions because they expose internal implementation details we are working to encapsulate. Calling code needs to know what type of persistence we are using, when it really should just be worried about if the record can be retrieved. Instead we should throw an exception that conveys the error at the same level of abstraction as we are exposing through our API:

public String getData(int id) throws InvalidRecordException

Now, if we change the internal implementation, we can simply wrap that exception in an InvalidRecordException and pass it along (or not wrap it, and just throw a new InvalidRecordException). External code does not know or care what type of persistence is being used. It's all encapsulated.

As for Single Responsibility, we need to think about code that throws multiple, unrelated exceptions. Let's say we have the following method:

public Record parseFile(String filename) throws IOException, ParseException

What can we say about this method? We can tell just from the signature that it opens a file and parses it. When we see a conjunction, like "and" or "or" in the description of a method, we know that it is doing more than one thing; it has more than one responsibility. Methods with more than one responsibility are hard to manage as they can change if any of the responsibilities change. Instead, we should break methods up so they have a single responsibility:

public String readFile(String filename) throws IOException
public Record parse(String data) throws ParseException

We've extracted out the responsibility of reading the file from the responsibility of parsing the data. One side effect of this is that we can now pass in any String data to the parse data from any source: in-memory, file, network, etc. We can also test parse more easily now because we don't need a file on disk to run tests against.

Sometimes there really are two (or more) exceptions we can throw from a method, but if we stick to SRP and DIP, the times we encounter this situation become rarer.


问:
Query on Recursive composition
For the below relation between Container and Componentin java.awt class hierarchy, I see that,

in addition to is-a relation, class Container has composite relation with class Component with below line of code,

```<code>/**
     * The components in this container.
     * @see #add
     * @see #getComponents
     */
    private java.util.List<Component> component = new java.util.ArrayList<Component>();
</code>```

But am still not clear with the below diagram wrt operation() method.

So,

1)
What does class Leaf and class Composite signify in the below diagram?

2)
What exactly are we depicting about operation() method in class Leaf and class Composite as per the below diagram?

Note: I am java beginner learning java

答:
What you are looking at in the first diagram is how the AWT classes in Java use the Composite Pattern so that they are able to compose together elements in a larger element of the same type. The second diagram shows the generalized form of the Composite Pattern.

The Composite Pattern

In order to understand the composite pattern, let's use a more concrete example for a better perspective. First, we have a super class (could also be an interface) Vehicle for things that drive on the road, like cars, trucks, 18-wheelers, etc:

```<code>public abstract class Vehicle
{
     public void drive(int distance) {
        System.out.println("Drove " + distance + ". Vroom vroom!");
     }

     public abstract int getWeight();
     // etc.
}
</code>```

Now we also have a concrete class for a car:

```<code>public class Car extends Vehicle
{
    protected int weight;

    // ...

    @Override
    public int getWeight() {
        return this.weight;
    }
}
</code>```

We also have a class for a car carrier, which is a vehicle that can contain other vehicles:

```<code>public class CarCarrier extends Vehicle
{
    protected int weight;
    protected Vehicle[] cars;

    // ...

    @Override
    public int getWeight() {
        int weight = this.weight;
        for(Vehicle car : cars) {
            weight += car.getWeight();
        }
        return weight;
    }
}
</code>```

As we can see in the getWeight method of CarCarrier, we have to calculate the weight of the car carrier as its weight plus the weight of the cars it carries. Thus the getWeight method of CarCarrier calls the getWeight method of each of the child Vehicles in the cars array. The Car class corresponds to the leaf, and the CarCarrier class corresponds to the composite.

The above formula, describing how the composite's operation method should work, basically translates into "for each child, we'll call it 'o', in children, we have to call the operation method on o when the composite's operation method is called." This corresponds to how we called the getWeight method of each of the Vehicles being carried by the CarCarrier to get the total weight of the CarCarrier.

Title: Query on Recursive composition

Body:
What you are looking at in the first diagram is how the AWT classes in Java use the Composite Pattern so that they are able to compose together elements in a larger element of the same type. The second diagram shows the generalized form of the Composite Pattern.

The Composite Pattern

In order to understand the composite pattern, let's use a more concrete example for a better perspective. First, we have a super class (could also be an interface) Vehicle for things that drive on the road, like cars, trucks, 18-wheelers, etc:

public abstract class Vehicle
{
     public void drive(int distance) {
        System.out.println("Drove " + distance + ". Vroom vroom!");
     }

     public abstract int getWeight();
     // etc.
}

Now we also have a concrete class for a car:

public class Car extends Vehicle
{
    protected int weight;

    // ...

    @Override
    public int getWeight() {
        return this.weight;
    }
}

We also have a class for a car carrier, which is a vehicle that can contain other vehicles:

public class CarCarrier extends Vehicle
{
    protected int weight;
    protected Vehicle[] cars;

    // ...

    @Override
    public int getWeight() {
        int weight = this.weight;
        for(Vehicle car : cars) {
            weight += car.getWeight();
        }
        return weight;
    }
}

As we can see in the getWeight method of CarCarrier, we have to calculate the weight of the car carrier as its weight plus the weight of the cars it carries. Thus the getWeight method of CarCarrier calls the getWeight method of each of the child Vehicles in the cars array. The Car class corresponds to the leaf, and the CarCarrier class corresponds to the composite.

The above formula, describing how the composite's operation method should work, basically translates into "for each child, we'll call it 'o', in children, we have to call the operation method on o when the composite's operation method is called." This corresponds to how we called the getWeight method of each of the Vehicles being carried by the CarCarrier to get the total weight of the CarCarrier.


问:
Type Casting in Java
Could anyone explain why short(100000) is -31072 as said in p.48 of java-notes.The article says that "the value -31072 is obtained by taking the the 4 byte int 100000 and throwing away two of these bytes to obtain a short".

The code in the article related to the question is:

```<code>int A;
short B;
A = 17;
B = (short)A;
</code>```

答:
In Java, ints are stored using a 32-bit 2's complement representation and shorts with a 16-bit 2's complement representation.

This means that an int with the value 17 will contain the bitpattern 00000000 00000000 000000000 00010001 and with the value 100000 it will contain the bitpattern 00000000 00000001 10000110 10100000.

When converting these numbers to short, you need to stuff them in 16 bits. This is done by keeping the lower (right-most) 16 bits and throwing the rest away, as that preserves any value that can be represented in a short.

The pattern for 17 becomes 00000000 00010001, which still is the number 17.

The pattern for 100000 becomes 10000110 10100000. Here we have lost one bit that was actually needed for the representation of the number, so the value represented by the remaining bits is different. According to 16-bit 2'complement representation,the bitpattern 10000110 10100000 represents the number -31072.

Title: Type Casting in Java


答:
Here is a simple improvement which will most probably meet your time constraints. For every divisor i of N, there is also a corresponding divisisor N/i. Thus to find all pairs of divisors, you need only to loop from 1 to the square root N. So try something along the lines of

```<code>    int maxD = (int)Math.sqrt(input);
    int sum=1;
    for(int i = 2; i <= maxD; i++)
    {
        if(input % i == 0)
        {
           sum += i;
           int d = input/i;
           if(d!=i)
              sum+=d;
        }
    }
</code>```

Note that the "prime factorization" method from the other answer method hides the complexity of the algorithm behind an invisible factorization method. And when you implement a simple form of prime factorization like "trial division", you end up by an algorithm which works very similar like the one above. So the prime factorization method may speed up things up for values of N with many small prime factors, but not when N itself is a prime (at least not, when you don't want to implement a very sophisticated prime factorization method).

Title: Most Efficient way to Compute the sum of divisors of N (1 ≤ N ≤ 1 000 000 000)

Body:
I want to write a code which computes the sum of divisors of a number N(1 ≤ N ≤ 1 000 000 000), excluding the number itself.

However, I need an efficient way to do it. It suppose to print the answer under 1 second. I know it depends on hardware etc. But I have an i7 machine though it takes more than a second (for the worst case scenario which is 1000000000 ) because of my poor code.

So to make it more understandable:

EX:
Sample input: 10 --> Output should be: 8 (because we know 1 + 2 + 5 = 8)

EX:
Input: 20 --> Output suppose to be: 22 ( 1 + 2 + 4 + 5 + 10 = 22 )

So far i wrote this:

```<code>public class Main
{
public static void main(String[] args)
{
    @SuppressWarnings("resource")
    Scanner read = new Scanner(System.in);

    System.out.print("How many times you would like to try: ");
    int len = read.nextInt();

    for(int w = 0; w < len; w++)
    {
        System.out.print("Number: ");
        int input = read.nextInt();

        int remains = 1;
        int sum = remains;

        /* All I know we only need to check half of the given number as
           I learned ages ago. I mean (input / 2) :D */

        for(int i = 2; i <= input / 2; i++)
        {
            if(input % i == 0) sum += i;
        }

        System.out.print("Result: " + sum);
    }

}
}
</code>```

So the question is How to improve this solution ? How to make it more efficient or let me put it this way. Is there a way to do it more efficient ?

Body:
Here is a simple improvement which will most probably meet your time constraints. For every divisor i of N, there is also a corresponding divisisor N/i. Thus to find all pairs of divisors, you need only to loop from 1 to the square root N. So try something along the lines of

    int maxD = (int)Math.sqrt(input);
    int sum=1;
    for(int i = 2; i <= maxD; i++)
    {
        if(input % i == 0)
        {
           sum += i;
           int d = input/i;
           if(d!=i)
              sum+=d;
        }
    }

Note that the "prime factorization" method from the other answer method hides the complexity of the algorithm behind an invisible factorization method. And when you implement a simple form of prime factorization like "trial division", you end up by an algorithm which works very similar like the one above. So the prime factorization method may speed up things up for values of N with many small prime factors, but not when N itself is a prime (at least not, when you don't want to implement a very sophisticated prime factorization method).


答:
The composite pattern involves a parent that has a set of child objects (all children and the parent have some interface or superclass in common), and one (or more) operations that are implemented by delegating to the same operation in the children, potentially with some additional operations performeda as well.

In the case of Component, the delegated operations are event handling, painting and so on. For instance,, the implementation of paint is to loop over the children, adjust the origin and clipping region of the Graphics object for each, and call its paint method.

Title: Query on Recursive composition

Body:
For the below relation between Container and Componentin java.awt class hierarchy, I see that,

in addition to is-a relation, class Container has composite relation with class Component with below line of code,

```<code>/**
     * The components in this container.
     * @see #add
     * @see #getComponents
     */
    private java.util.List<Component> component = new java.util.ArrayList<Component>();
</code>```

But am still not clear with the below diagram wrt operation() method.

So,

1)
What does class Leaf and class Composite signify in the below diagram?

2)
What exactly are we depicting about operation() method in class Leaf and class Composite as per the below diagram?

Note: I am java beginner learning java


问:
Checking a record is due based on the 'occuring' field
I have records that have dates against them and an occurring field that contains none,yearly and monthly

```<code>id    status    note   date        last_updated   occurring
1     open      ---    01/01/2011  01/02/2010     yearly
2     open      ---    05/05/2011  03/05/2011     monthly
3     open      ---    06/06/2011  05/06/2011     none
</code>```

Now I need to be able to check if a record is due (the date set has passed) which works perfect if occurring is set to none but I'm unsure of how to approach it when it's set to yearly or monthly (IE: This day in the year/month has passed)

So with the above records, if I had a method on the record called due? providing the status is 'open' it needs to return true every year when it's passed that date if it's not been updated within the year yet.

I apologise if this is confusing but it's melting my brain just trying to think of it, let alone put it into words.

答:
I see two big problems here.

1 - When you can't explain what the problem is clearly, then take that as a warning sign that you haven't thought about it enough yet.  It is critical to your understanding of the problem that you can explain it clearly - and you should do that before you start creating fields in a database.

Another symptom of this is the field naming, where you have fields named after types (like date) it doesn't tell you anything about what that field means.  That is something you should see as a warning sign when you or others around you do it.  Is that field the last time the record was modified (then maybe it should be called 'modified') or the subject's birthday (in which case maybe 'dob' or 'birthday').  Giving it useful name will help you or whoever has to deal with the code you've created.

2 - Solving the actual problem... from what I can gather for example you have some kind of reminder/billing system which operates over different periods for customers with an open account.  So it's best to consider that problem in isolation for now, and for our purposes id, status, note are not fields which are relevant to this problem.

You need 2 fields to get to the solution:

due - date, nullable - when the next reminder/action is due

recurs - date/timespan, nullable - the timespan of the next time to process this record.

To find out what records are due for an update you query against the current date.

When you process the record you use the database or software's date/time system to if it's not null then you add the recurs to due, write back your next due date and anything you don't need up update again make null.


答:
Throwing multiple checked exceptions make sense when there is multiple reasonable things to do.

For example lets say you have method

```<code>public void doSomething(Credentials cred, Work work)
    throws CredentialsRequiredException, TryAgainLaterException{...}
</code>```

this violates pne exception rule, but makes sense.

Unfortunatelly, what usuallly happens are methods like

```<code>void doSomething()
    throws IOException, JAXBException,SQLException,MyException {...}
</code>```

Here there is little chance for caller to do something specific based on exception type.
So if we want to nudge him into realizing that these methods CAN and sometimes WILL go wrong, throwing just SomethingMightGoWrongException is enogh and better.

Hence rule at most one checked exception.

But if your project use design where there are multiple meaningfull checked exceptions, this rule should not apply.

Sidenote: Something actually can go wrong almost everywhere, so one can think about using ? extends RuntimeException, but there is difference between "we all do mistakes" and "this talks external system and it sometimes WILL be down, deal with it".

Title: Why shouldn't a method throw multiple types of checked exceptions?

Body:
We use SonarQube to analyse our Java code and it has this rule (set to critical):

Public methods should throw at most one checked exception

Using checked exceptions forces method callers to deal with errors, either by propagating them or by handling them. This makes those exceptions fully part of the API of the method.

To keep the complexity for callers reasonable, methods should not throw more than one kind of checked exception."

Another bit in Sonar has this:

Public methods should throw at most one checked exception

Using checked exceptions forces method callers to deal with errors, either by propagating them or by handling them. This makes those exceptions fully part of the API of the method.

To keep the complexity for callers reasonable, methods should not throw more than one kind of checked exception.

The following code:

```<code>public void delete() throws IOException, SQLException {      // Non-Compliant
  /* ... */
}
</code>```

should be refactored into:

```<code>public void delete() throws SomeApplicationLevelException {  // Compliant
    /* ... */
}
</code>```

Overriding methods are not checked by this rule and are allowed to throw several checked exceptions.

I've never come across this rule/recommendation in my readings on exception handling and have tried to find some standards, discussions etc. on the topic.  The only thing I've found is this from CodeRach: How many exceptions should a method throw at most?

Is this a well accepted standard?

Body:
Throwing multiple checked exceptions make sense when there is multiple reasonable things to do.

For example lets say you have method

public void doSomething(Credentials cred, Work work)
    throws CredentialsRequiredException, TryAgainLaterException{...}

this violates pne exception rule, but makes sense.

Unfortunatelly, what usuallly happens are methods like

void doSomething()
    throws IOException, JAXBException,SQLException,MyException {...}

Here there is little chance for caller to do something specific based on exception type.
So if we want to nudge him into realizing that these methods CAN and sometimes WILL go wrong, throwing just SomethingMightGoWrongException is enogh and better.

Hence rule at most one checked exception.

But if your project use design where there are multiple meaningfull checked exceptions, this rule should not apply.

Sidenote: Something actually can go wrong almost everywhere, so one can think about using ? extends RuntimeException, but there is difference between "we all do mistakes" and "this talks external system and it sometimes WILL be down, deal with it".


问:
Inheritance in imperative programming
My first introduction to programming was Java, which was horrible so I learnt Actionscript3 which was nice...  "The point is" OOP was my introduction to programming where by I went on to gain a career in PHP and while I can confidently write programs/scripts in imperative languages I am no where near as comfortable in doing so.

The primary reason is because I am unable to understand how imperative/procedural languages can be extended in the same way OOP languages use polymorphism and substitution.

I am now looking to learn additional languages and may even have a crack at C, only if I can work out the basic principles for substituting functionality.

Can anyone explain the basic principles used to extend the functionality of a library/function without re-writing that entire function.  Because in OOP you would override one method of a class and possibly call the super method to retain some of the original behavior.

答:
This recent blog post by Bob Martin is relevant. In it, he defines providing convenient ways to implement polymorphism as being the essential element of what makes a language object-oriented.

In light of this, we can read your question as "how do I do object-oriented programing in a non object-oriented language?" The answer to this is quite simple: you don't if you can possibly help it. Yes, it is possible to implement it in many such languages, but the results are always unpleasant and difficult to read or work with. If your problem involves the need to handle different types of data in similar ways (i.e. if it is essentially a polymorphic problem) then use an object oriented language. If you have to work in a non-oo language, try to unify your data such that you never need to handle different types at the same place in your code. Learn to worry less about repeating yourself: it's much harder to avoid in non-oo code. And use function pointers as a last resort, when you absolutely need them only.

Title: Inheritance in imperative programming


问:
Separate servers vs local machine for builds, issue tracking etc on solo project
For solo projects, do you keep your build / management tools on your local machine, or on a separate server? If the server is not guaranteed to be safer or more reliable than my own machine I struggle to see the point, but maybe I'm missing some things.

Note that I'm not debating the value of continuous integration or having a staging environment etc.. just the question of whether it exists on separate hardware.

答: For many projects, it makes sense to have VM dedicated solely to development or for use as a staging server, especially if a complicated software configuration is necessary on the machine. Using a VM gives you the ability to switch between putting the development / staging server on a common or server machine, or putting it on your workstation machine (which can be useful if, for instance, you need to develop from a portable machine or without a network connection.</p>


问:
Why do we have to tell printf() the type of data in C?
Let's consider this C code:

```<code>#include <stdio.h>

main()
{
  int x=5;
  printf("x is ");
  printf("%d",5);
}
</code>```

In this, when we wrote int x=5; we told the computer that x is an integer. The computer must remember that x is an integer. But when we output the value of x in printf() we have to again tell the computer that x is an integer. Why is that?

Why does the computer forget that x was an integer?

答:
Because at the moment when printf is called and does its job, the compiler is no longer there to tell it what to do.

The function doesn't get any information except what's in its parameters, and the vararg parameters don't have any type, so printf would have no clue how to print any if them if it didn't get explicit instructions via the format string. The compiler could (usually) deduce what type each argument is, but you would still have to write  format string to tell it where to print each argument relative to the constant text. Compare "$%d" and "%d$"; they do different things, and the compiler can't guess which you want. Since you have to compose a format string manually anyway to specify argument positions, it's an obvious choice to offload the task of stating the argument types to the user as well.

The alternative would be for the compiler to scan the format string for positions, then deduce the types, rewrite the format string to add the type information, and then compile the changed string into your binary instead. But that would only work for literal format strings; C also allows dynamically assigned format strings, and there would always be cases where the compiler can't accurately reconstruct what the format string is going to be at run-time. (Also, sometimes you want to print something as a different, related type, effectively performing a narrowing cast; that is also something that no compiler can predict.)


答: Think about it like you are passing variables to another function that you have defined. You normally tell the other function which type of data it should expect/receive. The same way with printf(). It is already defined in the stdio.h library and requires you to tell it which data it is receiving so that it can output it in the right format (as in your case int).

Title: Why do we have to tell printf() the type of data in C?

Body:
Let's consider this C code:

```<code>#include <stdio.h>

main()
{
  int x=5;
  printf("x is ");
  printf("%d",5);
}
</code>```

In this, when we wrote int x=5; we told the computer that x is an integer. The computer must remember that x is an integer. But when we output the value of x in printf() we have to again tell the computer that x is an integer. Why is that?

Why does the computer forget that x was an integer?


问:
Exposition of Data Representation
I would like to know how the data representation is exposed in slide 7 of information hiding:

Modifying an exposed data representation propagates to all code which directly accesses that representation

Perhaps the best example of the impact this can have is the Year 2000 problem

Legacy software for applications as diverse as nuclear power station control, air traffic control, finance, and the military were coded using exposed data representations

To ensure the software will work correctly come 2000 every single place that uses the date representation needed to be changed to store years using 4 digits rather than 2

The cost of this conversion has been estimated in billions of dollars!

Exposed data representation leads to change propagation ... affects maintenance costs ... big trouble

I would also really like to know whether information hiding means 'hiding the data using visibility identifiers(public,private)' or whether it means 'hiding data representation'.What actually does data representation mean?Could anyone help me.

答:
Let me start by answering your questions:

Data representation is the storage type of the data and what meaning the possible values of that data have.  For example, a Boolean value may be stored as a single bit, where the bit being 1 means truth and 0 means falsehood.

Data representation is exposed by making something with a type (variable, class member) visible to outside.

Information hiding means using language constructs to prevent the inner workings of a module from being visible to other code.  "Inner workings" can mean anything that makes the module tick, such as the fact that a piece of data exists, its representation and how values are determined (stored, calculated or both).

Here's a practical example that should answer the question I think you're really asking based on some of your comments:

Let's say you're developing an application that needs a class to represent a date.  You come up with something that makes no effort to hide information, where all members are public and there are no methods to manipulate them:

```<code>class Date {    // Irrelevant parts left out for brevity
      ...
    public int month;  // Month of year, 1 = January
      ...
}
</code>```

Your team goes on to write many thousands of lines of code that use Date, all of which assume that the first month of the year, January, is represented by the value 1 and reach directly into the structure to access it:

```<code>Date foo;
  ...
foo.month = 1;  // January
  ...
</code>```

One day, someone discovers that a critical function would be much more efficient if it's given zero-based months (0 for January, 1 for February, etc.) instead of having to do the arithmetic to produce one every time it reads or writes the month member of a Date.  Management decides the business case for making the change is a good one and says to make it happen.

The critical function is re-written to use zero-based months, which means that every other line of code in the application that deals with months is now broken because it doesn't use the correct values.  It may compile because the value is still an integer, but it's no longer using the correct values.  What was January (1) is now February, and what was December (12) is no longer a valid value because zero-based months end at 11.

(This example is a bit contrived, because good practice would dictate having the class define constants for well-known values like Date.MONTH_JANUARY, but bear with me.  The principle still applies.)

Correcting the broken code gives you a lot to do:

Identify every use of a Date in the entire application

Check each of those uses to determine whether or not it makes any assumptions about the value of the month member

Change those that do to use the new rules

Re-test all of it

Get on your knees and pray you didn't miss anything

The costs of this effort can be huge in terms of labor to make and test the changes and risk to the business if a mistake (or the correction of one) would result in lost revenue.

Had Date been developed using information hiding in the first place, there would be ways to manipulate the month that are independent of how it's stored:

```<code>class Date {
      ...
    private int month;  // Month of year, 1 = January
      ...
    // These methods operate on the month as a 1-based value and
    // are the ones all of the existing code uses.
    void set_month(int new_month) { month = new_month; }
    int  get_month() { return month; }
}
</code>```

Making the change to zero-based storage makes your to-do list a lot more pleasant and a lot less risky:

Re-comment the month member to indicate that it's now zero-based

Change set_month() and get_month() to do the arithmetic to convert to/from one-based to zero-based on the way in/out

Test the changed methods for correctness

Add and test methods to do zero-based operations on month so the new version of the critical function can use them

The class now looks like this:

```<code>class Date {
      ...
    private int month;  // Month of year, 0 = January
      ...
    // These methods operate on the month as a 1-based value and
    // are the ones all of the existing code uses.
    void set_month(int new_month) { month = new_month - 1; }
    int  get_month() { return month + 1; }

    // New methods that operate on the month as a 0-based value
    void set_month_zero(int new_month) { month = new_month; }
    int  get_month_zero() { return month; }
}
</code>```

The key here is, again, that nothing outside the class knows anything about how the month is stored or even if it's stored at all.  All they see is two methods called set_month() and get_month() that have to be used to store or retrieve the one-based value.  As long as the new implementations of those methods can be proven to behave as they always did, there's no need to touch the thousands of lines of code that use them.  The critical function can use the new set_month_zero() and get_month_zero() methods to do a zero-based manipulation of the month.

Title: Exposition of Data Representation

Body:
Let me start by answering your questions:

Data representation is the storage type of the data and what meaning the possible values of that data have.  For example, a Boolean value may be stored as a single bit, where the bit being 1 means truth and 0 means falsehood.

Data representation is exposed by making something with a type (variable, class member) visible to outside.

Information hiding means using language constructs to prevent the inner workings of a module from being visible to other code.  "Inner workings" can mean anything that makes the module tick, such as the fact that a piece of data exists, its representation and how values are determined (stored, calculated or both).

Here's a practical example that should answer the question I think you're really asking based on some of your comments:

Let's say you're developing an application that needs a class to represent a date.  You come up with something that makes no effort to hide information, where all members are public and there are no methods to manipulate them:

class Date {    // Irrelevant parts left out for brevity
      ...
    public int month;  // Month of year, 1 = January
      ...
}

Your team goes on to write many thousands of lines of code that use Date, all of which assume that the first month of the year, January, is represented by the value 1 and reach directly into the structure to access it:

Date foo;
  ...
foo.month = 1;  // January
  ...

One day, someone discovers that a critical function would be much more efficient if it's given zero-based months (0 for January, 1 for February, etc.) instead of having to do the arithmetic to produce one every time it reads or writes the month member of a Date.  Management decides the business case for making the change is a good one and says to make it happen.

The critical function is re-written to use zero-based months, which means that every other line of code in the application that deals with months is now broken because it doesn't use the correct values.  It may compile because the value is still an integer, but it's no longer using the correct values.  What was January (1) is now February, and what was December (12) is no longer a valid value because zero-based months end at 11.

(This example is a bit contrived, because good practice would dictate having the class define constants for well-known values like Date.MONTH_JANUARY, but bear with me.  The principle still applies.)

Correcting the broken code gives you a lot to do:

Identify every use of a Date in the entire application

Check each of those uses to determine whether or not it makes any assumptions about the value of the month member

Change those that do to use the new rules

Re-test all of it

Get on your knees and pray you didn't miss anything

The costs of this effort can be huge in terms of labor to make and test the changes and risk to the business if a mistake (or the correction of one) would result in lost revenue.

Had Date been developed using information hiding in the first place, there would be ways to manipulate the month that are independent of how it's stored:

class Date {
      ...
    private int month;  // Month of year, 1 = January
      ...
    // These methods operate on the month as a 1-based value and
    // are the ones all of the existing code uses.
    void set_month(int new_month) { month = new_month; }
    int  get_month() { return month; }
}

Making the change to zero-based storage makes your to-do list a lot more pleasant and a lot less risky:

Re-comment the month member to indicate that it's now zero-based

Change set_month() and get_month() to do the arithmetic to convert to/from one-based to zero-based on the way in/out

Test the changed methods for correctness

Add and test methods to do zero-based operations on month so the new version of the critical function can use them

The class now looks like this:

class Date {
      ...
    private int month;  // Month of year, 0 = January
      ...
    // These methods operate on the month as a 1-based value and
    // are the ones all of the existing code uses.
    void set_month(int new_month) { month = new_month - 1; }
    int  get_month() { return month + 1; }

    // New methods that operate on the month as a 0-based value
    void set_month_zero(int new_month) { month = new_month; }
    int  get_month_zero() { return month; }
}

The key here is, again, that nothing outside the class knows anything about how the month is stored or even if it's stored at all.  All they see is two methods called set_month() and get_month() that have to be used to store or retrieve the one-based value.  As long as the new implementations of those methods can be proven to behave as they always did, there's no need to touch the thousands of lines of code that use them.  The critical function can use the new set_month_zero() and get_month_zero() methods to do a zero-based manipulation of the month.


问:
Should an event listener be called if attached after the event has already fired?
Should an event listener be called if it is attached after the event has already fired? What if the event will only be fired once?

The first example that comes to mind is the ready event in jQuery. The following snippet, when evaluated after the page has loaded, will still call the callback:

```<code>$(document).ready(function () {
    console.log("Works.");
});
</code>```

The alternative to this behaviour could be a flag that is set when the page is loaded, forcing the consumer of the API to check to see if the event has already happened and act accordingly:

```<code>if (document.readyState == "complete") {
    console.log("Works.");
} else {
    $(document).ready(function () {
        console.log("Works.");
    });
}
</code>```

While the above example is in the context of a web page loading where anything and everything (usually) needs to happen after the page has completely loaded, the same arguments could be made for any single component in an application, which has "singleton" events (load, start, end, etc). An example of a single component could be a map with a load event that fires to specify that the map that has loaded:

```<code>map.on("load", function () {
    console.log("The map has loaded.");
});
</code>```

The above example comes from the ArcGIS API for JavaScript, where that event is fired only once, and if an a consumer "waits" for the map to load after the map is already loaded, the listener will never be called. The desired result requires checking the state of the map before the listener is attached:

```<code>if (map.loaded) {
    console.log("The map has loaded.");
} else {
    map.on("load", function () {
        console.log("The map has loaded.");
    });
}
</code>```

Which behaviour is correct, requiring the consumer to check if an event has already fired or always calling the callback?

答:
That depends upon whether it is really an Event or State Notification (which is what ready is).  If it is an event, then you don't tell the listener about all prior events.  If it is State Notification, then you tell them immediately after they have subscribed and you are in the specified state.

The tricky bit will be where it can be either a state or an event, depending upon how you look at it -- at worst, that is explained by the documentaion.  At best you pick a good name that makes it clear which you mean.


答:
printf() is what's known as a variadic function, which is one that accepts a variable number of arguments.

Variadic functions in C use a special prototype to tell the compiler that the list of arguments is of unknown length:

```<code>int printf(const char *format, ...);
</code>```

Standard C provides a set of functions in stdarg.h that can be used to retrieve the arguments one at a time and cast them to a given type.  This means that variadic functions have to decide the type of each argument for themselves.  printf() makes this decision based on what's in the format string.

This is a gross oversimplification of how printf() actually works, but the process goes like this:

```<code>int printf(const char *format, ...) {

    /* Get ready to process arguments that follow 'format' */
    va_list ap;
    va_start(ap, format);

    /* Deep in the function, something that's dissected the
       format string has decided that the next argument is a
       string.  Grab the next argument, cast it to char * and
       write it to wherever it should go.
     */
    char *string = va_arg(ap, char *);
    write_string_to_output(string);

    /* Conclude processing of arguments */
    va_end(ap);
}
</code>```

The same process happens for all of the types printf() is capable of converting.  You can see an example of this in the source code for OpenBSD's implementation of vfprintf(), which is the function that underpins printf().

Some C compilers are smart enough to spot calls to printf(), evaluate the format string if it's a constant and verify that the types of the rest of the arguments are compatible with the conversions specified.  This behavior is not required, which is why the standard still requires providing the type as part of the format string.  Before these kinds of checks were made, mismatches between the format string and the argument list simply produced bogus output.

In C++, << is an operator, which makes uses of cout such as cout << foo << bar an infix expression that can be evaluated for correctness at compile time and turned into code that casts the right-hand expressions into something cout can deal with.

Body:
printf() is what's known as a variadic function, which is one that accepts a variable number of arguments.

Variadic functions in C use a special prototype to tell the compiler that the list of arguments is of unknown length:

int printf(const char *format, ...);

Standard C provides a set of functions in stdarg.h that can be used to retrieve the arguments one at a time and cast them to a given type.  This means that variadic functions have to decide the type of each argument for themselves.  printf() makes this decision based on what's in the format string.

This is a gross oversimplification of how printf() actually works, but the process goes like this:

int printf(const char *format, ...) {

    /* Get ready to process arguments that follow 'format' */
    va_list ap;
    va_start(ap, format);

    /* Deep in the function, something that's dissected the
       format string has decided that the next argument is a
       string.  Grab the next argument, cast it to char * and
       write it to wherever it should go.
     */
    char *string = va_arg(ap, char *);
    write_string_to_output(string);

    /* Conclude processing of arguments */
    va_end(ap);
}

The same process happens for all of the types printf() is capable of converting.  You can see an example of this in the source code for OpenBSD's implementation of vfprintf(), which is the function that underpins printf().

Some C compilers are smart enough to spot calls to printf(), evaluate the format string if it's a constant and verify that the types of the rest of the arguments are compatible with the conversions specified.  This behavior is not required, which is why the standard still requires providing the type as part of the format string.  Before these kinds of checks were made, mismatches between the format string and the argument list simply produced bogus output.

In C++, << is an operator, which makes uses of cout such as cout << foo << bar an infix expression that can be evaluated for correctness at compile time and turned into code that casts the right-hand expressions into something cout can deal with.


问:
How to avoid switches?
I use Laravel as a PHP framework, although the question is not exactly about laravel, more about structuring controller methods.

I have a route to orders page. Depending on the user role I need to include different views and I have different logic for each role. It looks like this:

```<code>    public function index()
    {
        switch ($this->user->role->name) {
            case 'admin': {
                // Some code
                break;
            }
            case 'customer': {
                // Some code
                break;
            }
            case 'manager': {
                // Some code
                break;
            }
        }
    }
</code>```

I repeat this pattern for all routes which are accessible for many roles. I know that using repeatedly if/else, switch or this kind of stuff is not the best solution. Also the function becomes quite big (not much but depends on logic). Of course I can break it into 3 subfunctions lie (indexAdmin, indexManager, indexCustomer) but am still not sure if it's good.

Could anybody explain how to deal with it, preferably using Laravel (I use 5 dev version)?

Update

Here is the full code: http://laravel.io/bin/eDkmj

答:
I think that break into 3 functions like you said is the best alternative, mainly to separate the logic of each user.

Here's an example of how this can be made:

```<code>public function index() {
    $method = "index" . ucfirst($this->user->role->name);
    $this->$method();
}

private function indexAdmin() {
    // do stuff
}

private function indexCustomer() {
    // do stuff
}

private function indexManager() {
    // do stuff
}
</code>```

Title: How to avoid switches?

Body:
I think that break into 3 functions like you said is the best alternative, mainly to separate the logic of each user.

Here's an example of how this can be made:

public function index() {
    $method = "index" . ucfirst($this->user->role->name);
    $this->$method();
}

private function indexAdmin() {
    // do stuff
}

private function indexCustomer() {
    // do stuff
}

private function indexManager() {
    // do stuff
}


问:
Is there any license which prohibits usage for hiring purposes?
I develop code review tool which analyzes the code and gives it passed grade and output details of code review.

I want to prohibit to use this software for recruiting/hiring purposes. I don't want to be responsible for someone doesn't going to be hired because of my software. I don't want to prohibit for development usage, but I do want to prohibit it for hiring purpose only.

Is there any free existing licenses that prohibit usage of project for hiring  purposes? If no, can I modify MIT license for this purpose?

Thank you for attention!

答:
There are no licenses with such restrictions in common use. Licenses with such a restriction also fall outside the definition of open source.

Fears, such as yours of being held accountable for conclusions drawn from the results given by your application, are usually dealt with by adding a disclaimer to the software that you don't guarantee that the software is suitable for any purpose. These disclaimers are included with just about all open source licenses.

If you still want to use a custom license with restrictions on how the software can be used, you need to consult with a lawyer to draft a legally enforcible license.


问:
Is there an alternative to instanceof when filtering a Java stream by class?
I have an unexpected situation in a project in which all types extending one class are packed into a Java collection; but only a specific extension of that class contains an additional method. Let's call it "also()"; and let me be clear that no other extension has it. Right before performing one task on every item in that collection, I need to call also() on every item that implements it.

The easiest way forward is this:

```<code>stuff.stream().filter(item -> item instanceof SpecificItem)
            .forEach(item -> ((SpecificItem)item).also()));
stuff.stream().forEach(item -> item.method());
</code>```

It works fine, but I'm not comfortable with the "instanceof" in there. That's generally a marker of bad code smell. It is very possible that I will refactor this class just to get rid of it. Before I do something that dramatic, though, I thought I would check with the community and see if someone with more experience with either Streams or Collections had a simpler solution.

As an example (certainly nonexclusive), is it possible to get a view of a collection that filters entries by class?

答:
an alternative:

make SpecificItem implement an interface (say "Filterable")

make a new class that extends Stream

create a new 'filter' method which accept object that implement your interface

override the original stream method and redirect it to your implementation (by casting the predicate parameter to your interface)

that way only objects which implement your interface would be able to pass themeselves to your method... no need to use instanceof

```<code>public class MyStream extends Stream
{
    //...

    Stream<Filterable> filter(Predicate<? implements Filterable> predicate)
    {
         return super.filter(predicate);
    }
}
</code>```

Body:
an alternative:

make SpecificItem implement an interface (say "Filterable")

make a new class that extends Stream

create a new 'filter' method which accept object that implement your interface

override the original stream method and redirect it to your implementation (by casting the predicate parameter to your interface)

that way only objects which implement your interface would be able to pass themeselves to your method... no need to use instanceof

public class MyStream extends Stream
{
    //...

    Stream<Filterable> filter(Predicate<? implements Filterable> predicate)
    {
         return super.filter(predicate);
    }
}


答:
I have an unexpected situation in a project in which all types extending one class are packed into a Java collection; but only an extension of that class implements a method. Let's call it "also()". Right before performing one task on every item in that collection, I need to call also() on every item that implements it.

That is obviously a defective design. From what you wrote it is not clear, what it means, that one class does not implement the method. If it simply does nothing, it wouldn't matter, so I assume there is an unwanted side effect.

It works fine, but I'm not comfortable with the "instanceof" in there.

Your guts are right. Good object oriented design would work without further knowledge what exactly an object, resp whether it is an instance of a special kind.

Before I do something that dramatic, though, I thought I would check with the community and see if someone with more experience with either Streams or Collections had a simpler solution.

Refactoring is not dramatic. It improves code quality.

With your given codebase, the simplest solution would be, to make sure, you have two separate collections, one with the parent and one with the child class. But that's not quite clean.

Title: Is there an alternative to instanceof when filtering a Java stream by class?

Body:
I have an unexpected situation in a project in which all types extending one class are packed into a Java collection; but only a specific extension of that class contains an additional method. Let's call it "also()"; and let me be clear that no other extension has it. Right before performing one task on every item in that collection, I need to call also() on every item that implements it.

The easiest way forward is this:

```<code>stuff.stream().filter(item -> item instanceof SpecificItem)
            .forEach(item -> ((SpecificItem)item).also()));
stuff.stream().forEach(item -> item.method());
</code>```

It works fine, but I'm not comfortable with the "instanceof" in there. That's generally a marker of bad code smell. It is very possible that I will refactor this class just to get rid of it. Before I do something that dramatic, though, I thought I would check with the community and see if someone with more experience with either Streams or Collections had a simpler solution.

As an example (certainly nonexclusive), is it possible to get a view of a collection that filters entries by class?